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(navigation): star products directly instead of custom products (#117252)

Rafael Audibert4ad6027fb762
diff --git a/.agents/skills/styling-sidebar-products/SKILL.md b/.agents/skills/styling-sidebar-products/SKILL.md
index bf5df7f5fb4f..7946d7b50acb 100644
--- a/.agents/skills/styling-sidebar-products/SKILL.md
+++ b/.agents/skills/styling-sidebar-products/SKILL.md
@@ -43,7 +43,7 @@ Always give both a light and a dark variable, because a single value is reused f
Stars come from two writers:
- The frontend (`shortcutFromEntry` in `ProjectTree/utils.tsx`) sets `href`. The customize dialog saves all its changes in one `file_system_shortcut/bulk_update/` call.
-- The backend (`star_custom_products` in `posthog/models/file_system/starred_products.py`) stars new custom products for simple sidebar users. It sets no `href`, because product URLs exist only in the frontend.
+- The backend (`star_products` in `posthog/models/file_system/starred_products.py`) stars the default products when a user gets a project, and the products of a new product intent. It sets no `href`, because product URLs exist only in the frontend.
When shortcuts load, `withProductShortcutHref` in `defaultTree.tsx` fills in a missing `href` by product name.
The file tree then looks up the product by `href` (`getSidebarProduct` in `defaultTree.tsx`) and uses its current name, tags, icon and color. It wraps custom icons in `ProductIconWrapper`.
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 957f9a2aaabb..8c6cb2f54abd 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -683,7 +683,7 @@ jobs:
run: bin/ci-wait-for-docker launch personhog-replica personhog-router
- name: Seed test data
- run: python manage.py generate_demo_data --n-clusters 10 --days-past 7 --days-future 0 --skip-materialization --skip-flag-sync --skip-user-product-list
+ run: python manage.py generate_demo_data --n-clusters 10 --days-past 7 --days-future 0 --skip-materialization --skip-flag-sync
- name: Create API key and extract test IDs
run: |
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.ts
index 0b3d037d835f..1bbf3e681e62 100644
--- a/common/storybook/.storybook/app-context.ts
+++ b/common/storybook/.storybook/app-context.ts
@@ -17,43 +17,6 @@ export const getStorybookAppContext = (): AppContext => ({
commit_sha: undefined,
preflight: null as any, // `null` triggers a fetch and lets us mock the data
switched_team: null,
- custom_products: [
- {
- id: 'product-1',
- product_path: 'Product analytics',
- enabled: true,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- {
- id: 'product-2',
- product_path: 'Session replay',
- enabled: true,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- {
- id: 'product-3',
- product_path: 'Feature flags',
- enabled: true,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- {
- id: 'product-4',
- product_path: 'Dashboards',
- enabled: true,
- created_at: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
- updated_at: new Date().toISOString(),
- },
- {
- id: 'product-5',
- product_path: 'Experiments',
- enabled: true,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- ],
oauth_application: {
client_id: 'storybook-client-id',
name: 'Storybook OAuth App',
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 745fb7de6490..284425c0615f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4412,14 +4412,6 @@ snapshots:
hash: v1.k794b7964.6695fe610e3f2c6defc39393d92d7075ee02c494f49c840a6aacb90f521bfe1f.6pIULWHpgkRwZOKuJOF4mNBxJlVemTXRwX0f-wbvnXI
layout-products-and-files--search--light:
hash: v1.k794b7964.2f1fc9d1cd3b0c4141c564ba244b0cf17599ff92a95fbea4937f5a7c05fd5040.hwD6HSMsaa7NWobGJRS5hjX89po3O5KU10hOKbE-Zbs
- layout-products-and-files--starred-setup--dark:
- hash: v1.k794b7964.4b84c0b4ad1ed54202d5186e8a397d49c242e244569d00309fee244f0b3a74e6.bRdajXCYxVPeEO9YAfyqIZ51JIaSdrgOLPCE6th6Sro
- layout-products-and-files--starred-setup--light:
- hash: v1.k794b7964.1bbea1b1ea41e87c054397e538d41a565fcd1e329da1d0bfcdd8a8925db9891c.TmbrXVSTY3kW7f_e3y5lHgK2K6Kc9zK1HQrjdhCBA4w
- layout-products-and-files--starred-setup-prompt--dark:
- hash: v1.k794b7964.beea56ac68b66228422d2dd2f662a8bcc4430f593175baa3c02b0e1f50d896b8.ojdYf6YY1yx6JNiEP8CxYkYJuJpAq11gpTL06L2siPg
- layout-products-and-files--starred-setup-prompt--light:
- hash: v1.k794b7964.73b5e24788a70c4d9adc0abda73530a0c7e8f559b495bf48e021e6a955da7479.RrDjzpXdyvPwDOyhUtJM0hzIblbxkmnKM-uXlmSrSlk
layout-products-product-tooltip--dark--dark:
hash: v1.k794b7964.52ba01b050e579d7c600df08497a2dfab2dba9cf670553e032afce3819d6d00d.PNNtTamfHv5qRTsFnRwxhlFEaIteMOgYQgAab2QRRj0
layout-products-product-tooltip--dark--light:
diff --git a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts
deleted file mode 100644
index 69a9c87b4eb5..000000000000
--- a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { useMocks } from '~/mocks/jest'
-import { UserProductListItem } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-
-import { customProductsLogic } from './customProductsLogic'
-
-const serverRow = (productPath: string): UserProductListItem => ({
- id: `id-${productPath}`,
- product_path: productPath,
- enabled: true,
- created_at: '2026-01-01T00:00:00Z',
- updated_at: '2026-01-01T00:00:00Z',
-})
-
-describe('customProductsLogic', () => {
- let logic: ReturnType<typeof customProductsLogic.build>
- let listCalls: number
- let serverPaths: string[]
- let failBulkUpdate: boolean
-
- beforeEach(() => {
- listCalls = 0
- serverPaths = []
- failBulkUpdate = false
- useMocks({
- get: {
- '/api/environments/:team_id/user_product_list/': () => {
- listCalls += 1
- return [200, { results: serverPaths.map(serverRow) }]
- },
- },
- patch: {
- '/api/environments/:team_id/user_product_list/bulk_update/': () =>
- failBulkUpdate ? [400, { detail: 'nope' }] : [200, { results: [] }],
- },
- })
- initKeaTests()
- logic = customProductsLogic()
- logic.mount()
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- it('keeps a toggle made while an earlier save was in flight', async () => {
- // The server still only knows about product A. A refetch on A's success would answer with
- // just A and wipe B off the screen, which is what the user notices.
- serverPaths = ['a']
-
- await expectLogic(logic, () => {
- logic.actions.setProductEnabled('a', true)
- logic.actions.setProductEnabled('b', true)
- }).toFinishAllListeners()
-
- expect(logic.values.enabledProductPaths).toEqual(new Set(['a', 'b']))
- })
-
- it('does not refetch when a save succeeds', async () => {
- await expectLogic(logic, () => {
- logic.actions.setProductEnabled('a', true)
- }).toFinishAllListeners()
-
- expect(listCalls).toBe(0)
- })
-
- it('refetches to revert the optimistic row when a save fails', async () => {
- failBulkUpdate = true
- serverPaths = []
-
- await expectLogic(logic, () => {
- logic.actions.setProductEnabled('a', true)
- }).toFinishAllListeners()
-
- expect(listCalls).toBe(1)
- expect(logic.values.enabledProductPaths).toEqual(new Set())
- })
-})
diff --git a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx
deleted file mode 100644
index f36c6e98f65f..000000000000
--- a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import { MakeLogicType, actions, kea, listeners, path, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import posthog from 'posthog-js'
-
-import { lemonToast } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-import { getAppContext } from 'lib/utils/getAppContext'
-
-import { UserProductListItem } from '~/queries/schema/schema-general'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customProductsLogicValues {
- customProducts: UserProductListItem[]
- customProductsLoading: boolean
- enabledProductPaths: Set<string>
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customProductsLogicActions {
- loadCustomProducts: () => any
- loadCustomProductsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadCustomProductsSuccess: (
- customProducts: UserProductListItem[],
- payload?: any
- ) => {
- customProducts: UserProductListItem[]
- payload?: any
- }
- setProductEnabled: (
- productPath: string,
- enabled: boolean
- ) => {
- enabled: boolean
- productPath: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customProductsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- enabledProductPaths: (customProducts: UserProductListItem[]) => Set<string>
- }
-}
-
-export type customProductsLogicType = MakeLogicType<
- customProductsLogicValues,
- customProductsLogicActions,
- Record<string, any>,
- customProductsLogicMeta
->
-
-export const customProductsLogic = kea<customProductsLogicType>([
- path(['layout', 'panel-layout', 'ProjectTree', 'customProductsLogic']),
- actions({
- setProductEnabled: (productPath: string, enabled: boolean) => ({ productPath, enabled }),
- }),
- loaders(() => ({
- customProducts: [
- getAppContext()?.custom_products ?? [],
- {
- loadCustomProducts: async (): Promise<UserProductListItem[]> => {
- const response = await api.userProductList.list()
-
- return response.results ?? []
- },
- },
- ],
- })),
- selectors({
- enabledProductPaths: [
- (s) => [s.customProducts],
- (customProducts: UserProductListItem[]): Set<string> =>
- new Set(customProducts.map((item) => item.product_path)),
- ],
- }),
- listeners(({ actions, values }) => ({
- setProductEnabled: async ({ productPath, enabled }) => {
- posthog.capture('sidebar my tools changed', { product_path: productPath, enabled })
- // Placeholder row: every consumer reads `product_path` only, so the fields the server
- // would fill in are never looked at and there is nothing to reconcile on success.
- const now = new Date().toISOString()
- const withoutProduct = values.customProducts.filter((item) => item.product_path !== productPath)
- actions.loadCustomProductsSuccess(
- enabled
- ? [
- ...withoutProduct,
- {
- id: '',
- product_path: productPath,
- enabled: true,
- created_at: now,
- updated_at: now,
- },
- ]
- : withoutProduct
- )
- try {
- await api.userProductList.bulkUpdate([{ product_path: productPath, enabled }])
- } catch (error) {
- console.error('Failed to save product changes:', error)
- lemonToast.error('Failed to save some changes. Try again?')
- // Only refetch to undo the failed toggle. Refetching on success would race a
- // toggle the user made while this call was in flight, reverting it on screen.
- actions.loadCustomProducts()
- }
- },
- })),
-])
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 554cda33f07b..50364c73e20f 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -19,6 +19,7 @@ import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { capitalizeFirstLetter, humanList, identifierToHuman, pluralize } from 'lib/utils/strings'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -267,6 +268,27 @@ export interface projectTreeDataLogicActions {
searchParams: Record<string, any>
url: string
} // router
+ addProductIntentForCrossSellSuccess: (
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
+ payload?: import('../../../lib/utils/product-intents').ProductCrossSellProperties | undefined
+ ) => {
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
+ payload?: import('../../../lib/utils/product-intents').ProductCrossSellProperties
+ } // teamLogic
+ addProductIntentSuccess: (
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
+ payload?: import('../../../lib/utils/product-intents').ProductIntentProperties | undefined
+ ) => {
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
+ payload?: import('../../../lib/utils/product-intents').ProductIntentProperties
+ } // teamLogic
+ recordProductIntentOnboardingCompleteSuccess: (
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
+ payload?: import('scenes/teamLogic').ProductOnboardingCompleteProperties | undefined
+ ) => {
+ currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
+ payload?: import('scenes/teamLogic').ProductOnboardingCompleteProperties
+ } // teamLogic
addLoadedResults: (results: RecentResults | SearchResults) => {
results: RecentResults | SearchResults
}
@@ -644,7 +666,16 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
userLogic,
['user'],
],
- actions: [router, ['locationChanged']],
+ actions: [
+ router,
+ ['locationChanged'],
+ teamLogic,
+ [
+ 'addProductIntentSuccess',
+ 'addProductIntentForCrossSellSuccess',
+ 'recordProductIntentOnboardingCompleteSuccess',
+ ],
+ ],
})),
actions({
setStarredNavigationRef: (ref: ProjectTreeRef | null, href?: string) => ({ ref, href }),
@@ -1725,6 +1756,16 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
actions.loadShortcuts()
}
},
+ // A new product intent can star products on the backend.
+ addProductIntentSuccess: () => {
+ actions.loadShortcuts()
+ },
+ addProductIntentForCrossSellSuccess: () => {
+ actions.loadShortcuts()
+ },
+ recordProductIntentOnboardingCompleteSuccess: () => {
+ actions.loadShortcuts()
+ },
loadHomeFolderSuccess: () => {
actions.loadShortcuts()
actions.loadFolder('', true)
diff --git a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
index 7db9f567d347..9799ffc69559 100644
--- a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
+++ b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
import type { Meta, StoryObj } from '@storybook/react'
import { within, waitFor } from '@testing-library/dom'
@@ -318,20 +318,6 @@ export const CustomizeSidebarNarrow: Story = {
...CustomizeSidebarRanked,
parameters: { testOptions: { viewport: { width: 600, height: 900 } } },
}
-export const StarredSetupPrompt: Story = {
- decorators: [
- mswDecorator({
- get: { '/api/users/@me/': [200, { ...MOCK_DEFAULT_USER, ui_configuration: null }] },
- }),
- ],
-}
-export const StarredSetup: Story = {
- ...StarredSetupPrompt,
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement)
- await userEvent.click(await canvas.findByText('Choose starred products'))
- },
-}
export const Files: Story = { args: { tab: 'files' } }
export const FilesOptions: Story = {
...Files,
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx b/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
index 6c57bbb264d3..77dc9aba4c62 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
@@ -8,49 +8,29 @@ import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
import { navProductsTabLogic } from './navProductsTabLogic'
import { SidebarSuggestionsSetting } from './SidebarSuggestionsSetting'
import { StarredProductsPicker } from './StarredProductsPicker'
-import { StarredSetupIntro } from './StarredSetupIntro'
export function CustomizeSidebarModal(): JSX.Element {
- const { customizeSidebarOpen, customizeSidebarMode, starredProductsSaving, hasDraftStarredChanges } =
- useValues(navProductsTabLogic)
- const { setCustomizeSidebarOpen, saveStarredProducts, confirmCleanSlate } = useActions(navProductsTabLogic)
+ const { customizeSidebarOpen, starredProductsSaving, hasDraftStarredChanges } = useValues(navProductsTabLogic)
+ const { setCustomizeSidebarOpen, saveStarredProducts } = useActions(navProductsTabLogic)
const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)
- const isStarredSetup = customizeSidebarMode === 'starred-setup'
return (
<LemonModal
- title={isStarredSetup ? 'Set up your new sidebar' : 'Customize sidebar'}
+ title="Customize sidebar"
isOpen={customizeSidebarOpen}
- onClose={() => setCustomizeSidebarOpen(false, 'dismiss')}
+ onClose={() => setCustomizeSidebarOpen(false)}
hasUnsavedInput={hasDraftStarredChanges}
width={720}
footer={
<div className="flex flex-wrap items-center gap-2 w-full">
<div className="flex-1">
- {isStarredSetup ? (
- <LemonButton
- type="tertiary"
- onClick={confirmCleanSlate}
- disabledReason={
- starredProductsSaving
- ? 'Saving your starred products'
- : !shortcutDataHasLoaded
- ? 'Loading your starred products'
- : undefined
- }
- data-attr="starred-setup-clean-slate-footer"
- >
- Start with a clean slate
- </LemonButton>
- ) : (
- <p className="text-xs text-secondary mb-0">
- Tip: Drag starred items in the sidebar to rearrange them.
- </p>
- )}
+ <p className="text-xs text-secondary mb-0">
+ Tip: Drag starred items in the sidebar to rearrange them.
+ </p>
</div>
<LemonButton
type="secondary"
- onClick={() => setCustomizeSidebarOpen(false, 'cancel_button')}
+ onClick={() => setCustomizeSidebarOpen(false)}
disabledReason={starredProductsSaving ? 'Saving your starred products' : undefined}
data-attr="customize-sidebar-cancel"
>
@@ -61,7 +41,7 @@ export function CustomizeSidebarModal(): JSX.Element {
onClick={saveStarredProducts}
loading={starredProductsSaving}
disabledReason={!shortcutDataHasLoaded ? 'Loading your starred products' : undefined}
- data-attr={isStarredSetup ? 'starred-setup-save' : 'customize-sidebar-save'}
+ data-attr="customize-sidebar-save"
>
Save
</LemonButton>
@@ -69,20 +49,14 @@ export function CustomizeSidebarModal(): JSX.Element {
}
>
<div className="flex flex-col gap-6">
- {isStarredSetup ? (
- <StarredSetupIntro />
- ) : (
- <>
- <section className="flex flex-col gap-2">
- <div>
- <LemonLabel>Homepage</LemonLabel>
- <p className="text-xs text-secondary mb-0">The page that opens when you select Home.</p>
- </div>
- <HomepageConfiguration />
- </section>
- <SidebarSuggestionsSetting />
- </>
- )}
+ <section className="flex flex-col gap-2">
+ <div>
+ <LemonLabel>Homepage</LemonLabel>
+ <p className="text-xs text-secondary mb-0">The page that opens when you select Home.</p>
+ </div>
+ <HomepageConfiguration />
+ </section>
+ <SidebarSuggestionsSetting />
<StarredProductsPicker />
</div>
</LemonModal>
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx b/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx
index 944b5387ef6b..6d95c9ccfaf1 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx
@@ -12,14 +12,8 @@ import { NavProductTooltip } from './NavProductTooltip'
import { productsItemName } from './productsCatalog'
export function StarredProductsPicker(): JSX.Element {
- const {
- customizeProductGroups,
- draftStarredPaths,
- customizeSearch,
- customizeSidebarMode,
- customProducts,
- appRecommendationsEnabled,
- } = useValues(navProductsTabLogic)
+ const { customizeProductGroups, draftStarredPaths, customizeSearch, appRecommendationsEnabled } =
+ useValues(navProductsTabLogic)
const { setDraftStarred, setCustomizeSearch, unselectAllStarred } = useActions(navProductsTabLogic)
const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)
@@ -28,11 +22,7 @@ export function StarredProductsPicker(): JSX.Element {
<div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-1">
<div>
<LemonLabel>Starred</LemonLabel>
- <p className="text-xs text-secondary mb-0">
- {customizeSidebarMode === 'starred-setup' && customProducts.length > 0
- ? 'Your custom products and existing stars are already picked.'
- : 'Star the products you want to see in your sidebar.'}
- </p>
+ <p className="text-xs text-secondary mb-0">Star the products you want to see in your sidebar.</p>
</div>
{shortcutDataHasLoaded && (
<div className="flex items-center gap-2">
@@ -49,7 +39,7 @@ export function StarredProductsPicker(): JSX.Element {
</div>
)}
</div>
- {customizeSidebarMode === 'customize' && appRecommendationsEnabled && <JevProductSuggestions />}
+ {appRecommendationsEnabled && <JevProductSuggestions />}
<LemonInput
type="search"
size="small"
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsx b/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsx
deleted file mode 100644
index 571d83ca7db9..000000000000
--- a/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import * as star from '@posthog/brand/hoggies/png/star'
-import { Link } from '@posthog/lemon-ui'
-
-import { pngHoggie } from 'lib/brand/hoggies'
-import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
-
-import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
-import { navProductsTabLogic } from './navProductsTabLogic'
-
-const HedgehogStar = pngHoggie(star)
-
-export function StarredSetupIntro(): JSX.Element {
- const { confirmCleanSlate } = useActions(navProductsTabLogic)
- const { starredProductsSaving } = useValues(navProductsTabLogic)
- const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)
-
- return (
- <section className="@container flex items-center gap-4 border-b pb-4">
- <div className="flex flex-1 flex-col gap-3">
- <p className="mb-0">
- Many of you told us things were too hard to find in the old sidebar, so we simplified it. Your
- sidebar now shows only the products you star.
- </p>
- <p className="mb-0">
- Rather see everything?{' '}
- <Link
- onClick={confirmCleanSlate}
- disabledReason={
- !shortcutDataHasLoaded
- ? 'Loading your starred products'
- : starredProductsSaving
- ? 'Saving your starred products'
- : undefined
- }
- data-attr="starred-setup-clean-slate"
- >
- Start with a clean slate
- </Link>{' '}
- and star products as you go.
- </p>
- <p className="mb-0 text-secondary">
- Looking for something specific? Press <KeyboardShortcut command k /> to open the{' '}
- <strong>improved search</strong> and jump anywhere in PostHog.
- </p>
- </div>
- <HedgehogStar className="hidden h-32 w-auto shrink-0 @md:block" loading="eager" />
- </section>
- )
-}
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts
index d29055554619..1298ff26b4c5 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
@@ -10,7 +10,6 @@ import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { FileSystemEntry } from '~/queries/schema/schema-general'
@@ -19,7 +18,6 @@ import { ActivityTab } from '~/types'
import { DecideRequestApi } from 'products/ml_inference/frontend/generated/api.schemas'
-import { customProductsLogic } from '../../ProjectTree/customProductsLogic'
import { getDefaultTreeData, getDefaultTreeProducts } from '../../ProjectTree/defaultTree'
import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'
@@ -137,20 +135,6 @@ describe('navProductsTabLogic', () => {
expect(navProductsTabLogic.values).toMatchObject({ allProductsCollapsible: true, allProductsVisible: true })
})
- it('reloads stars after custom products reload', async () => {
- const list = jest.fn(() => [200, { results: [] }])
- useMocks({ get: { '/api/projects/:team_id/file_system_shortcut/': list } })
- await expectLogic(projectTreeDataLogic).toFinishAllListeners()
- list.mockClear()
-
- await expectLogic(navProductsTabLogic, () =>
- customProductsLogic.actions.loadCustomProductsSuccess([])
- ).toFinishAllListeners()
- await expectLogic(projectTreeDataLogic).toFinishAllListeners()
-
- expect(list).toHaveBeenCalledTimes(1)
- })
-
it('fills in the link of product stars the backend created without one', async () => {
const results = [
{ id: 'backend-star', path: 'Session replay', type: 'session_replay' },
@@ -221,72 +205,32 @@ describe('navProductsTabLogic', () => {
})
it.each([
- ['saves', 200, false, true],
- ['keeps the dialog and choices after a failed save', 500, true, false],
- ])('starred setup starts from custom products and %s', async (_name, status, staysOpen, completed) => {
+ ['closes after a successful save', 200, false],
+ ['keeps the dialog and choices after a failed save', 500, true],
+ ])('customize sidebar %s', async (_name, status, staysOpen) => {
const bulkUpdate = jest.fn(() => [status, status === 200 ? [] : { detail: 'Try again' }])
- const updateUser = jest.fn(async ({ request }: { request: Request }) => {
- updateUser.body = await request.json()
- return [200, { ...MOCK_DEFAULT_USER, ...(updateUser.body as object) }]
- }) as jest.Mock & { body?: unknown }
- userLogic.mount()
- userLogic.actions.loadUserSuccess({
- ...MOCK_DEFAULT_USER,
- ui_configuration: { version: 1, sidebar: { density: 'compact' } },
- })
- useMocks({
- post: { '/api/projects/:team_id/file_system_shortcut/bulk_update/': bulkUpdate },
- patch: { '/api/users/@me/': updateUser },
- })
- // Custom products reload the stars, so that reload has to finish before the stars are set.
- customProductsLogic.actions.loadCustomProductsSuccess([
- { id: '1', product_path: 'Session replay', enabled: true, created_at: '', updated_at: '' },
- { id: '2', product_path: 'Removed product', enabled: true, created_at: '', updated_at: '' },
- ])
+ useMocks({ post: { '/api/projects/:team_id/file_system_shortcut/bulk_update/': bulkUpdate } })
await expectLogic(projectTreeDataLogic).toFinishAllListeners()
projectTreeDataLogic.actions.loadShortcutsSuccess([
{ id: 'analytics', path: 'Product analytics', type: 'product_analytics', href: '/insights' },
])
- navProductsTabLogic.actions.openStarredSetup()
- expect([...navProductsTabLogic.values.draftStarredPaths].sort()).toEqual([
- 'Product analytics',
- 'Session replay',
- ])
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)
navProductsTabLogic.actions.setDraftStarred('Feature flags', true)
- navProductsTabLogic.actions.setAllProductsOpen(true)
await expectLogic(navProductsTabLogic, () => navProductsTabLogic.actions.saveStarredProducts())
.toDispatchActions([staysOpen ? 'saveStarredProductsFailure' : 'saveStarredProductsSuccess'])
.toFinishAllListeners()
.toMatchValues({ customizeSidebarOpen: staysOpen, starredProductsSaving: false })
- expect(updateUser).toHaveBeenCalledTimes(completed ? 1 : 0)
- expect(navProductsTabLogic.values.allProductsOpen).toBe(!completed)
- expect(updateUser.body).toEqual(
- completed
- ? {
- ui_configuration: {
- version: 1,
- sidebar: { density: 'compact', starred_products_setup_completed: true },
- },
- }
- : undefined
- )
expect(navProductsTabLogic.values.draftStarredPaths.has('Feature flags')).toBe(true)
- expect(customProductsLogic.values.customProducts).toHaveLength(2)
})
- it('clean slate unstars every product, keeps folders, and completes setup in one save', async () => {
+
+ it('unselect all also removes stars the dialog cannot list', async () => {
const bulkUpdate = jest.fn(async ({ request }: { request: Request }) => {
bulkUpdate.body = await request.json()
return [200, [{ id: 'folder', path: 'Research', type: 'folder', ref: 'Research' }]]
}) as jest.Mock & { body?: unknown }
- const updateUser = jest.fn(() => [200, MOCK_DEFAULT_USER])
- useMocks({
- post: { '/api/projects/:team_id/file_system_shortcut/bulk_update/': bulkUpdate },
- patch: { '/api/users/@me/': updateUser },
- })
- userLogic.mount()
- userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, ui_configuration: null })
+ useMocks({ post: { '/api/projects/:team_id/file_system_shortcut/bulk_update/': bulkUpdate } })
await expectLogic(projectTreeDataLogic).toFinishAllListeners()
projectTreeDataLogic.actions.loadShortcutsSuccess([
{ id: 'folder', path: 'Research', type: 'folder', ref: 'Research' },
@@ -294,28 +238,22 @@ describe('navProductsTabLogic', () => {
// Listed in the sidebar but not in the dialog, like a product the user lost access to.
{ id: 'activity', path: 'Activity', type: 'activity', href: urls.activity(ActivityTab.ExploreEvents) },
])
- customProductsLogic.actions.loadCustomProductsSuccess([
- { id: '1', product_path: 'Session replay', enabled: true, created_at: '', updated_at: '' },
- ])
- navProductsTabLogic.actions.openStarredSetup()
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)
+ navProductsTabLogic.actions.unselectAllStarred()
- await expectLogic(navProductsTabLogic, () => navProductsTabLogic.actions.startWithCleanSlate())
+ await expectLogic(navProductsTabLogic, () => navProductsTabLogic.actions.saveStarredProducts())
.toDispatchActions(['saveStarredProductsSuccess'])
.toFinishAllListeners()
.toMatchValues({ customizeSidebarOpen: false })
expect(bulkUpdate.body).toEqual({ add: [], remove_ids: ['analytics', 'activity'] })
- expect(updateUser).toHaveBeenCalledTimes(1)
})
- it('unselects every star, including preselected custom products, until the dialog reopens', async () => {
+ it('unselects every star until the dialog reopens', async () => {
await expectLogic(projectTreeDataLogic).toFinishAllListeners()
projectTreeDataLogic.actions.loadShortcutsSuccess([
{ id: 'analytics', path: 'Product analytics', type: 'product_analytics', href: '/insights' },
])
- customProductsLogic.actions.loadCustomProductsSuccess([
- { id: '1', product_path: 'Session replay', enabled: true, created_at: '', updated_at: '' },
- ])
- navProductsTabLogic.actions.openStarredSetup()
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)
navProductsTabLogic.actions.setDraftStarred('Logs', true)
expect(navProductsTabLogic.values.hasDraftStarredChanges).toBe(true)
navProductsTabLogic.actions.setDraftStarred('Logs', false)
@@ -327,11 +265,8 @@ describe('navProductsTabLogic', () => {
expect([...navProductsTabLogic.values.draftStarredPaths]).toEqual(['Logs'])
navProductsTabLogic.actions.setCustomizeSidebarOpen(false)
- navProductsTabLogic.actions.openStarredSetup()
- expect([...navProductsTabLogic.values.draftStarredPaths].sort()).toEqual([
- 'Product analytics',
- 'Session replay',
- ])
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)
+ expect([...navProductsTabLogic.values.draftStarredPaths]).toEqual(['Product analytics'])
})
it.each([
@@ -461,10 +396,6 @@ describe('navProductsTabLogic', () => {
'Web analytics',
'SQL editor',
])
- navProductsTabLogic.actions.openStarredSetup()
- expect(navProductsTabLogic.values.customizeProductGroups.map((group) => group.label)).not.toContain(
- SUGGESTED_GROUP_LABEL
- )
expect(
(navProductsTabLogic.values.appMatchGroups?.matching.length ?? 0) +
(navProductsTabLogic.values.appMatchGroups?.other.length ?? 0)
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
index 7e192f52a9c0..30c9c4209faa 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
@@ -4,7 +4,7 @@ import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'
-import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+import { lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -16,13 +16,11 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import { teamLogic } from 'scenes/teamLogic'
import { fileSystemShortcutBulkUpdateCreate } from '~/generated/core/api'
-import { uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
-import { FileSystemEntry, FileSystemImport, UserProductListItem } from '~/queries/schema/schema-general'
+import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
import type { PreflightStatus } from '~/types'
import * as decisionsApi from 'products/ml_inference/frontend/generated/api'
-import { customProductsLogic } from '../../ProjectTree/customProductsLogic'
import { withProductShortcutHref } from '../../ProjectTree/defaultTree'
import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'
@@ -34,18 +32,11 @@ import { ProductsItemGroup, groupProducts, productMatchesSearch, productsItemNam
// projectTreeLogic persists state under its logic key, so renaming this value resets it.
export const PRODUCTS_STARRED_TREE_KEY = 'navbar-apps-starred'
-// `starred-setup` moves a user's custom products to starred products when they switch to the simple sidebar.
-export type CustomizeSidebarMode = 'customize' | 'starred-setup'
-
-// `dismiss` covers the modal's close button, Escape, and overlay clicks.
-export type CustomizeSidebarCloseMethod = 'cancel_button' | 'dismiss'
-
export const SUGGESTED_GROUP_LABEL = 'Suggested'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navProductsTabLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
- customProducts: UserProductListItem[] // customProductsLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
preflight: PreflightStatus | null // preflightLogic
shortcutData: FileSystemEntry[] // projectTreeDataLogic
@@ -66,7 +57,6 @@ export interface navProductsTabLogicValues {
configurableProducts: FileSystemImport[]
customizeProductGroups: ProductsItemGroup[]
customizeSearch: string
- customizeSidebarMode: CustomizeSidebarMode
customizeSidebarOpen: boolean
draftStarredChanges: Record<string, boolean>
draftStarredPaths: Set<string>
@@ -83,13 +73,6 @@ export interface navProductsTabLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navProductsTabLogicActions {
- loadCustomProductsSuccess: (
- customProducts: UserProductListItem[],
- payload?: any
- ) => {
- customProducts: UserProductListItem[]
- payload?: any
- } // customProductsLogic
deleteShortcutSuccess: (
shortcutData: FileSystemEntry[],
payload?:
@@ -154,18 +137,6 @@ export interface navProductsTabLogicActions {
currentTeam: null | import('~/types').TeamPublicType
payload?: any
} // teamLogic
- completeStarredProductsSetup: () => {
- value: true
- } // uiCustomizationLogic
- confirmCleanSlate: () => {
- value: true
- }
- dismissStarredSetup: () => {
- value: true
- }
- openStarredSetup: () => {
- value: true
- }
rankApps: ({ query }: { query: string }) => {
query: string
}
@@ -214,11 +185,7 @@ export interface navProductsTabLogicActions {
setCustomizeSearch: (search: string) => {
search: string
}
- setCustomizeSidebarOpen: (
- open: boolean,
- closeMethod?: CustomizeSidebarCloseMethod
- ) => {
- closeMethod: CustomizeSidebarCloseMethod | undefined
+ setCustomizeSidebarOpen: (open: boolean) => {
open: boolean
}
setDraftStarred: (
@@ -231,9 +198,6 @@ export interface navProductsTabLogicActions {
setSearch: (search: string) => {
search: string
}
- startWithCleanSlate: () => {
- value: true
- }
unselectAllStarred: () => {
value: true
}
@@ -267,14 +231,11 @@ export interface navProductsTabLogicMeta {
customizeProductGroups: (
configurableProducts: FileSystemImport[],
customizeSearch: string,
- appMatchGroups: AppMatchGroups | null,
- customizeSidebarMode: CustomizeSidebarMode
+ appMatchGroups: AppMatchGroups | null
) => ProductsItemGroup[]
initialStarredPaths: (
configurableProducts: FileSystemImport[],
- starredProductIds: Record<string, string>,
- customizeSidebarMode: CustomizeSidebarMode,
- customProducts: UserProductListItem[]
+ starredProductIds: Record<string, string>
) => string[]
draftStarredPaths: (
configurableProducts: FileSystemImport[],
@@ -315,20 +276,14 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
['dataProcessingAccepted'],
projectTreeDataLogic,
['shortcutData', 'shortcutDataHasLoaded', 'shortcutDataLoading'],
- customProductsLogic,
- ['customProducts'],
],
actions: [
projectTreeDataLogic,
['deleteShortcutSuccess', 'loadShortcuts', 'loadShortcutsFailure', 'loadShortcutsSuccess'],
- customProductsLogic,
- ['loadCustomProductsSuccess'],
router,
['locationChanged'],
teamLogic,
['loadCurrentTeamSuccess'],
- uiCustomizationLogic,
- ['completeStarredProductsSetup'],
],
logic: [projectTreeLogic({ key: PRODUCTS_STARRED_TREE_KEY, root: 'shortcuts://', shortcutScope: 'products' })],
})),
@@ -337,18 +292,11 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
setSearch: (search: string) => ({ search }),
setAppRecommendationQuery: (query: string) => ({ query }),
setAppRankingError: (error: string | null) => ({ error }),
- setCustomizeSidebarOpen: (open: boolean, closeMethod?: CustomizeSidebarCloseMethod) => ({
- open,
- closeMethod,
- }),
+ setCustomizeSidebarOpen: (open: boolean) => ({ open }),
setAllProductsOpen: (open: boolean) => ({ open }),
revealAllProductsForFind: true,
- openStarredSetup: true,
- dismissStarredSetup: true,
setDraftStarred: (productPath: string, starred: boolean) => ({ productPath, starred }),
unselectAllStarred: true,
- confirmCleanSlate: true,
- startWithCleanSlate: true,
setCustomizeSearch: (search: string) => ({ search }),
saveStarredProducts: true,
saveStarredProductsSuccess: true,
@@ -432,19 +380,10 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
false,
{
setCustomizeSidebarOpen: (_, { open }) => open,
- openStarredSetup: () => true,
saveStarredProductsSuccess: () => false,
resetAppConfiguration: () => false,
},
],
- // Kept while the dialog closes, so its content does not switch mid-animation.
- customizeSidebarMode: [
- 'customize' as CustomizeSidebarMode,
- {
- setCustomizeSidebarOpen: (state, { open }) => (open ? 'customize' : state),
- openStarredSetup: () => 'starred-setup',
- },
- ],
// Choices made in the dialog, applied over the starting selection. Nothing is saved until Save.
draftStarredChanges: [
{} as Record<string, boolean>,
@@ -452,7 +391,6 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
setDraftStarred: (state, { productPath, starred }) => ({ ...state, [productPath]: starred }),
unselectAllStarred: () => ({}),
setCustomizeSidebarOpen: (state, { open }) => (open ? {} : state),
- openStarredSetup: () => ({}),
},
],
// After "Unselect all", the draft starts from nothing instead of the current stars.
@@ -461,7 +399,6 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
{
unselectAllStarred: () => true,
setCustomizeSidebarOpen: (state, { open }) => (open ? false : state),
- openStarredSetup: () => false,
},
],
customizeSearch: [
@@ -469,7 +406,6 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
{
setCustomizeSearch: (_, { search }) => search,
setCustomizeSidebarOpen: (state, { open }) => (open ? '' : state),
- openStarredSetup: () => '',
},
],
starredProductsSaving: [
@@ -574,16 +510,10 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
return ids
},
],
- // Jev suggestions lead the list only in the regular dialog. The setup keeps the plain category list.
customizeProductGroups: [
- (s) => [s.configurableProducts, s.customizeSearch, s.appMatchGroups, s.customizeSidebarMode],
- (
- items: FileSystemImport[],
- search: string,
- appMatchGroups: AppMatchGroups | null,
- mode: CustomizeSidebarMode
- ): ProductsItemGroup[] => {
- if (!appMatchGroups || mode === 'starred-setup') {
+ (s) => [s.configurableProducts, s.customizeSearch, s.appMatchGroups],
+ (items: FileSystemImport[], search: string, appMatchGroups: AppMatchGroups | null): ProductsItemGroup[] => {
+ if (!appMatchGroups) {
return groupProducts(items, search)
}
const suggested = appMatchGroups.matching.filter((item) => productMatchesSearch(item, search))
@@ -591,24 +521,10 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
return suggested.length > 0 ? [{ label: SUGGESTED_GROUP_LABEL, items: suggested }, ...rest] : rest
},
],
- // Custom products only seed the setup: they stay stored so the old sidebar keeps them if the flag is reverted.
initialStarredPaths: [
- (s) => [s.configurableProducts, s.starredProductIds, s.customizeSidebarMode, s.customProducts],
- (
- items: FileSystemImport[],
- starredProductIds: Record<string, string>,
- mode: CustomizeSidebarMode,
- customProducts: UserProductListItem[]
- ): string[] => {
- const customProductPaths = new Set(customProducts.map((product) => product.product_path))
- return items
- .filter(
- (item) =>
- !!starredProductIds[item.path] ||
- (mode === 'starred-setup' && customProductPaths.has(item.path))
- )
- .map((item) => item.path)
- },
+ (s) => [s.configurableProducts, s.starredProductIds],
+ (items: FileSystemImport[], starredProductIds: Record<string, string>): string[] =>
+ items.filter((item) => !!starredProductIds[item.path]).map((item) => item.path),
],
draftStarredPaths: [
(s) => [s.configurableProducts, s.initialStarredPaths, s.draftStarredChanges, s.draftStartsEmpty],
@@ -681,60 +597,15 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
loadShortcutsSuccess: keepAllProductsOpenWithoutStars,
loadShortcutsFailure: keepAllProductsOpenWithoutStars,
deleteShortcutSuccess: keepAllProductsOpenWithoutStars,
- // A product intent can add custom products, and the backend stars them in the same request.
- // Custom products reload after that write, so shortcuts follow.
- loadCustomProductsSuccess: () => actions.loadShortcuts(),
revealAllProductsForFind: () => {
posthog.capture('sidebar all products revealed by find')
},
- openStarredSetup: () => {
- posthog.capture('sidebar starred setup opened', {
- custom_products_count: values.customProducts.length,
- })
- },
- dismissStarredSetup: () => {
- posthog.capture('sidebar starred setup dismissed')
- actions.completeStarredProductsSetup()
- },
- confirmCleanSlate: () => {
- if (!values.shortcutDataHasLoaded || values.starredProductsSaving) {
- return
- }
- LemonDialog.open({
- title: 'Start with a clean slate?',
- description:
- 'This unstars every product, including any you starred before. You can star products again from the sidebar at any time.',
- maxWidth: '30rem',
- primaryButton: {
- children: 'Unstar everything',
- status: 'danger',
- onClick: () => actions.startWithCleanSlate(),
- 'data-attr': 'starred-setup-clean-slate-confirm',
- },
- secondaryButton: { children: 'Cancel' },
- })
- },
- startWithCleanSlate: () => {
- posthog.capture('sidebar starred setup clean slate chosen', {
- starred_count: Object.keys(values.starredProductIds).length,
- })
- actions.unselectAllStarred()
- actions.saveStarredProducts()
- },
setDraftStarred: ({ starred }) => {
// Picking a star means the starred list, not the full catalog, leads the sidebar.
if (starred && values.allProductsOpen) {
actions.setAllProductsOpen(false)
}
},
- setCustomizeSidebarOpen: ({ open, closeMethod }) => {
- if (!open && values.customizeSidebarMode === 'starred-setup') {
- posthog.capture('sidebar starred setup cancelled', {
- close_method: closeMethod,
- had_changes: values.hasDraftStarredChanges,
- })
- }
- },
saveStarredProducts: async () => {
// The footer buttons are disabled in these states, but the intro link and repeated
// dispatches reach this listener directly.
@@ -746,7 +617,7 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
actions.saveStarredProductsFailure()
return
}
- const { draftStarredPaths, starredProductIds, customizeSidebarMode, draftStartsEmpty } = values
+ const { draftStarredPaths, starredProductIds, draftStartsEmpty } = values
// New stars follow the order the dialog lists them in.
const orderedProducts = groupProducts(values.configurableProducts, '').flatMap((group) => group.items)
const configurablePaths = new Set(orderedProducts.map((item) => item.path))
@@ -788,19 +659,12 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
cache.starredSaveInFlight = false
}
}
- if (customizeSidebarMode === 'starred-setup') {
- actions.completeStarredProductsSetup()
- // Setup can save only the preselected custom products, without any star picked here.
- if (draftStarredPaths.size > 0) {
- actions.setAllProductsOpen(false)
- }
- }
posthog.capture('sidebar starred products saved', {
- mode: customizeSidebarMode,
+ // pinned: saved insights filter on this value
+ mode: 'customize',
added_count: add.length,
removed_count: removeIds.length,
starred_count: draftStarredPaths.size,
- custom_products_count: values.customProducts.length,
})
actions.saveStarredProductsSuccess()
},
diff --git a/frontend/src/layout/uiCustomizationLogic.test.ts b/frontend/src/layout/uiCustomizationLogic.test.ts
deleted file mode 100644
index 4f43806b2c28..000000000000
--- a/frontend/src/layout/uiCustomizationLogic.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { MOCK_DEFAULT_USER } from 'lib/api.mock'
-
-import { expectLogic } from 'kea-test-utils'
-
-import { userLogic } from 'scenes/userLogic'
-
-import { useMocks } from '~/mocks/jest'
-import { UserUIConfiguration } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-import { UserType } from '~/types'
-
-import { uiCustomizationLogic } from './uiCustomizationLogic'
-
-describe('uiCustomizationLogic', () => {
- let logic: ReturnType<typeof uiCustomizationLogic.build>
- let patchedUser: Partial<UserType> | null
-
- function seedUser(uiConfiguration: UserUIConfiguration | null): void {
- userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, ui_configuration: uiConfiguration })
- }
-
- beforeEach(() => {
- patchedUser = null
- useMocks({
- patch: {
- '/api/users/@me/': async ({ request }) => {
- patchedUser = (await request.json()) as Partial<UserType>
- return [200, { ...MOCK_DEFAULT_USER, ...patchedUser }]
- },
- },
- })
- initKeaTests()
- logic = uiCustomizationLogic()
- logic.mount()
- })
-
- it('completes the starred setup optimistically without dropping the rest of the configuration', async () => {
- seedUser({ version: 1, sidebar: { density: 'compact' }, sql_editor: { vim_mode_enabled: true } })
-
- await expectLogic(logic, () => {
- logic.actions.completeStarredProductsSetup()
- }).toFinishAllListeners()
-
- expect(logic.values.starredProductsSetupCompleted).toBe(true)
- expect(patchedUser?.ui_configuration).toEqual({
- version: 1,
- sidebar: { density: 'compact', starred_products_setup_completed: true },
- sql_editor: { vim_mode_enabled: true },
- })
- })
-})
diff --git a/frontend/src/layout/uiCustomizationLogic.ts b/frontend/src/layout/uiCustomizationLogic.ts
index 595b73d592a0..0f59954d3556 100644
--- a/frontend/src/layout/uiCustomizationLogic.ts
+++ b/frontend/src/layout/uiCustomizationLogic.ts
@@ -2,29 +2,17 @@ import { MakeLogicType, actions, connect, kea, listeners, path, reducers, select
import { userLogic } from 'scenes/userLogic'
-import { SidebarConfiguration, UserUIConfiguration } from '~/queries/schema/schema-general'
+import { UserUIConfiguration } from '~/queries/schema/schema-general'
import { UserType } from '~/types'
/** Version stamped onto the configuration whenever this client persists it. */
export const UI_CONFIGURATION_VERSION = 1
-export function withSidebarPatch(
- configuration: UserUIConfiguration | null,
- patch: Partial<SidebarConfiguration>
-): UserUIConfiguration {
- return {
- version: UI_CONFIGURATION_VERSION,
- ...configuration,
- sidebar: { ...configuration?.sidebar, ...patch },
- }
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface uiCustomizationLogicValues {
user: UserType | null // userLogic
userLoading: boolean // userLogic
pendingUiConfiguration: UserUIConfiguration | null
- starredProductsSetupCompleted: boolean
uiConfiguration: UserUIConfiguration | null
}
@@ -59,9 +47,6 @@ export interface uiCustomizationLogicActions {
clearPendingUiConfiguration: (configuration: UserUIConfiguration) => {
configuration: UserUIConfiguration
}
- completeStarredProductsSetup: () => {
- value: true
- }
setPendingUiConfiguration: (configuration: UserUIConfiguration | null) => {
configuration: UserUIConfiguration | null
}
@@ -83,7 +68,6 @@ export interface uiCustomizationLogicMeta {
user: UserType | null,
pendingUiConfiguration: UserUIConfiguration | null
) => UserUIConfiguration | null
- starredProductsSetupCompleted: (uiConfiguration: UserUIConfiguration | null) => boolean
}
}
@@ -109,7 +93,6 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
successCallback?: () => void,
failureCallback?: () => void
) => ({ configuration, successCallback, failureCallback }),
- completeStarredProductsSetup: true,
}),
reducers({
// Optimistic copy held while the user PATCH is in flight, so toggles apply instantly.
@@ -128,13 +111,8 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
(user: UserType | null, pendingUiConfiguration: UserUIConfiguration | null): UserUIConfiguration | null =>
pendingUiConfiguration ?? user?.ui_configuration ?? null,
],
- starredProductsSetupCompleted: [
- (s) => [s.uiConfiguration],
- (uiConfiguration: UserUIConfiguration | null): boolean =>
- !!uiConfiguration?.sidebar?.starred_products_setup_completed,
- ],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions }) => ({
updateUiConfiguration: ({ configuration, successCallback, failureCallback }) => {
actions.setPendingUiConfiguration(configuration)
actions.updateUser({ ui_configuration: configuration }, successCallback, () => {
@@ -142,9 +120,5 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
failureCallback?.()
})
},
- completeStarredProductsSetup: () => {
- const configuration = withSidebarPatch(values.uiConfiguration, { starred_products_setup_completed: true })
- actions.updateUiConfiguration(configuration)
- },
})),
])
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 411fde81efbf..b2def25169f5 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -68,7 +68,6 @@ import {
RefreshType,
SpanTreeNode,
TileFilters,
- UserProductListItem,
} from '~/queries/schema/schema-general'
import { HogQLQueryString, setLatestVersionsOnQuery } from '~/queries/utils'
import {
@@ -686,11 +685,6 @@ export class ApiRequest {
return this.fileSystemShortcut(teamId).addPathComponent('reorder')
}
- // # User product list
- public userProductList(teamId?: TeamType['id']): ApiRequest {
- return this.teamProjectDetail(teamId).addPathComponent('user_product_list')
- }
-
// # Plugins
public plugins(orgId?: OrganizationType['id']): ApiRequest {
return this.organizationsDetail(orgId).addPathComponent('plugins')
@@ -2476,17 +2470,6 @@ const api = {
},
},
- userProductList: {
- async list(): Promise<CountedPaginatedResponse<UserProductListItem>> {
- return await new ApiRequest().userProductList().get()
- },
- async bulkUpdate(
- items: { product_path: string; enabled: boolean }[]
- ): Promise<{ results: UserProductListItem[] }> {
- return await new ApiRequest().userProductList().withAction('bulk_update').update({ data: { items } })
- },
- },
-
organizationFeatureFlags: {
async get(
orgId: OrganizationType['id'] = ApiConfig.getCurrentOrganizationId(),
diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx
index e4ba6d823efa..b4ca9f6da35e 100644
--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx
+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx
@@ -6,22 +6,17 @@ import { preflightLogic } from 'lib/logic/preflightLogic'
import { userLogic } from 'scenes/userLogic'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
-import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
-import { uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
import { BroadcastPayload, isBroadcastPayload } from './navPanelAdShared'
import { NavPanelBroadcastAd } from './NavPanelBroadcastAd'
import { NavPanelProductPushAd } from './NavPanelProductPushAd'
import { navPanelProductPushLogic } from './navPanelProductPushLogic'
-import { NavPanelStarredSetupAd } from './NavPanelStarredSetupAd'
export function NavPanelAdvertisement(): JSX.Element | null {
const { activeCampaign } = useValues(navPanelProductPushLogic)
const { isLayoutNavCollapsed } = useValues(panelLayoutLogic)
const { isCloudOrDev } = useValues(preflightLogic)
const { user } = useValues(userLogic)
- const { starredProductsSetupCompleted } = useValues(uiCustomizationLogic)
- const { customProducts } = useValues(customProductsLogic)
const broadcastPayload = getFeatureFlagPayload(FEATURE_FLAGS.NAV_PANEL_BROADCAST) as BroadcastPayload | undefined
@@ -29,13 +24,6 @@ export function NavPanelAdvertisement(): JSX.Element | null {
return null
}
- // A one-time setup for everyone moving from custom products to starred products, so it outranks promotional cards.
- // Users without custom products have nothing to move, which includes brand new users before
- // their defaults are seeded.
- if (user && !starredProductsSetupCompleted && customProducts.length > 0) {
- return <NavPanelStarredSetupAd />
- }
-
// A hand-authored broadcast outranks the scheduler, so a deliberate message is never preempted
// by an automated push. Both cards promote cloud features, so neither is shown on hobby.
if (isCloudOrDev && isBroadcastPayload(broadcastPayload)) {
diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelStarredSetupAd.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelStarredSetupAd.tsx
deleted file mode 100644
index 9dabf9d42075..000000000000
--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelStarredSetupAd.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import { useEffect } from 'react'
-
-import * as star from '@posthog/brand/hoggies/png/star'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { pngHoggie } from 'lib/brand/hoggies'
-
-import { navProductsTabLogic } from '~/layout/panel-layout/navbar/tabs/navProductsTabLogic'
-
-import { AdvertisementCard, NAV_PANEL_CARD_TYPE, ProductPushDisplay } from './navPanelAdShared'
-import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'
-
-const logicProps = { dismissKey: 'starred-products-setup' }
-
-const STARRED_SETUP_HERO: ProductPushDisplay = {
- Hoggie: pngHoggie(star),
- accentColor: 'var(--color-accent)',
- tagline: '',
- hoggieOffset: { x: 58 },
-}
-
-export function NavPanelStarredSetupAd(): JSX.Element | null {
- const { hidden } = useValues(navPanelAdvertisementLogic(logicProps))
- const { openStarredSetup, dismissStarredSetup } = useActions(navProductsTabLogic)
-
- useEffect(() => {
- if (!hidden) {
- posthog.capture('nav panel starred setup shown', { card_type: NAV_PANEL_CARD_TYPE.STARRED_SETUP })
- }
- }, [hidden])
-
- if (hidden) {
- return null
- }
-
- return (
- <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>
- <AdvertisementCard
- title="A simpler sidebar"
- hero={STARRED_SETUP_HERO}
- text={
- <span className="flex flex-col items-start gap-2">
- <span>
- Many of you told us things were too hard to find, so we rebuilt the sidebar around the
- products you pick.
- </span>
- <LemonButton
- type="primary"
- size="xsmall"
- onClick={() => {
- posthog.capture('nav panel starred setup clicked', {
- card_type: NAV_PANEL_CARD_TYPE.STARRED_SETUP,
- })
- openStarredSetup()
- }}
- data-attr="nav-panel-starred-setup-open"
- >
- Choose starred products
- </LemonButton>
- </span>
- }
- onClose={() => {
- posthog.capture('nav panel starred setup dismissed', {
- card_type: NAV_PANEL_CARD_TYPE.STARRED_SETUP,
- })
- dismissStarredSetup()
- }}
- />
- </BindLogic>
- )
-}
diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx
index 1e66c55a36ad..a62822ccc254 100644
--- a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx
+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx
@@ -19,7 +19,6 @@ import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'
export const NAV_PANEL_CARD_TYPE = {
BROADCAST: 'broadcast',
PRODUCT_PUSH: 'product_push',
- STARRED_SETUP: 'starred_setup',
} as const
export interface BroadcastPayload {
diff --git a/frontend/src/lib/components/Superpowers/Superpowers.tsx b/frontend/src/lib/components/Superpowers/Superpowers.tsx
index f37b7e835435..1b2755ca7d57 100644
--- a/frontend/src/lib/components/Superpowers/Superpowers.tsx
+++ b/frontend/src/lib/components/Superpowers/Superpowers.tsx
@@ -6,7 +6,6 @@ import { IconArrowLeft, IconChevronRight, IconTrash } from '@posthog/icons'
import { LemonButton, LemonDivider, LemonSelect, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
@@ -14,7 +13,7 @@ import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
-import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
+import { navProductsTabLogic } from '~/layout/panel-layout/navbar/tabs/navProductsTabLogic'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
import { getTreeItemsProducts } from '~/products'
import type { TeamType } from '~/types'
@@ -171,30 +170,25 @@ function CaptureOptionDot({ option, team }: { option: CaptureOption; team: TeamT
)
}
-function EnablementTag({ enabled }: { enabled: boolean }): JSX.Element {
- return enabled ? (
+function StarredTag({ starred }: { starred: boolean }): JSX.Element {
+ return starred ? (
<LemonTag type="success" className="shrink-0">
- Enabled
+ Starred
</LemonTag>
) : (
- <LemonTag className="shrink-0">Disabled</LemonTag>
+ <LemonTag className="shrink-0">Not starred</LemonTag>
)
}
function ProductsSection(): JSX.Element {
- const { customProducts, customProductsLoading } = useValues(customProductsLogic)
- const { loadCustomProducts } = useActions(customProductsLogic)
+ const { starredProductIds } = useValues(navProductsTabLogic)
const { currentTeam } = useValues(teamLogic)
- // The modal content unmounts on close, so each open refetches the sidebar list.
- useOnMountEffect(() => loadCustomProducts())
-
const team = currentTeam as TeamType | null
- const enabledByPath = new Map(customProducts.map((item) => [item.product_path, item]))
const products = getTreeItemsProducts()
const withOptions = products.filter((item) => PRODUCT_CAPTURE_OPTIONS[item.path])
const others = products.filter((item) => !PRODUCT_CAPTURE_OPTIONS[item.path])
- const enabledCount = products.filter((item) => enabledByPath.has(item.path)).length
+ const starredCount = products.filter((item) => !!starredProductIds[item.path]).length
return (
<Section
@@ -202,35 +196,32 @@ function ProductsSection(): JSX.Element {
<>
Products{' '}
<span className="font-normal text-secondary text-sm">
- ({enabledCount} of {products.length} in sidebar)
+ ({starredCount} of {products.length} starred)
</span>
</>
}
- description="Sidebar enablement per product (UserProductList), plus the team capture settings behind each product. A red dot means the product renders but captures nothing."
+ description="Whether you starred each product, plus the team capture settings behind it. A red dot means the product renders but captures nothing."
>
<div className="space-y-2">
<div className="space-y-1.5">
- {withOptions.map((item) => {
- const listItem = enabledByPath.get(item.path)
- return (
- <div key={item.path} className="border rounded p-2.5 space-y-1.5">
- <div className="flex items-center gap-2">
- <span className="flex shrink-0 group/colorful-product-icons colorful-product-icons-true">
- {iconForType(item.iconType)}
- </span>
- <span className="flex-1 text-sm font-medium truncate">{item.path}</span>
- <EnablementTag enabled={!!listItem} />
- </div>
- {team && (
- <div className="grid grid-cols-2 gap-x-4 gap-y-1 pl-6">
- {PRODUCT_CAPTURE_OPTIONS[item.path].map((option) => (
- <CaptureOptionDot key={option.field} option={option} team={team} />
- ))}
- </div>
- )}
+ {withOptions.map((item) => (
+ <div key={item.path} className="border rounded p-2.5 space-y-1.5">
+ <div className="flex items-center gap-2">
+ <span className="flex shrink-0 group/colorful-product-icons colorful-product-icons-true">
+ {iconForType(item.iconType)}
+ </span>
+ <span className="flex-1 text-sm font-medium truncate">{item.path}</span>
+ <StarredTag starred={!!starredProductIds[item.path]} />
</div>
- )
- })}
+ {team && (
+ <div className="grid grid-cols-2 gap-x-4 gap-y-1 pl-6">
+ {PRODUCT_CAPTURE_OPTIONS[item.path].map((option) => (
+ <CaptureOptionDot key={option.field} option={option} team={team} />
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
</div>
{others.length > 0 && (
<>
@@ -242,14 +233,13 @@ function ProductsSection(): JSX.Element {
{iconForType(item.iconType)}
</span>
<span className="flex-1 text-xs truncate">{item.path}</span>
- <EnablementTag enabled={enabledByPath.has(item.path)} />
+ <StarredTag starred={!!starredProductIds[item.path]} />
</div>
))}
</div>
</>
)}
</div>
- {customProductsLoading && <div className="text-xs text-secondary">Refreshing…</div>}
</Section>
)
}
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 89d2dbd14f15..9f1ac8c70eb5 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -109,7 +109,6 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/dashboards/': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/alerts/': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/hog_functions/': EMPTY_PAGINATED_RESPONSE,
- '/api/environments/:team_id/user_product_list/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/dashboard_templates': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/dashboard_templates/repository/': [],
'/api/environments/:team_id/external_data_sources/': EMPTY_PAGINATED_RESPONSE,
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b9cb79268961..1d3af17f2588 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -57697,28 +57697,6 @@
"required": ["distinct_id", "email", "first_name", "id", "uuid"],
"type": "object"
},
- "UserProductListItem": {
- "additionalProperties": false,
- "properties": {
- "created_at": {
- "type": "string"
- },
- "enabled": {
- "type": "boolean"
- },
- "id": {
- "type": "string"
- },
- "product_path": {
- "type": "string"
- },
- "updated_at": {
- "type": "string"
- }
- },
- "required": ["id", "product_path", "enabled", "created_at", "updated_at"],
- "type": "object"
- },
"UserUIConfiguration": {
"additionalProperties": {},
"description": "Per-user UI customization, persisted on the User model as a single JSONB blob. A null configuration and any absent key mean \"default\", which for visibility is \"shown\", so newly added UI surfaces appear for everyone until explicitly hidden. Writers must send the complete object; the server validates and replaces it wholesale.",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index c507ccc6b2fb..5e311df905a5 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -9200,14 +9200,6 @@ export interface ProductsData {
metadata: ProductItem[]
}
-export interface UserProductListItem {
- id: string
- product_path: string
- enabled: boolean
- created_at: string
- updated_at: string
-}
-
/** Visibility of a single customizable UI element. An absent config or an absent `visible` means the element is shown. */
export interface UIVisibilityConfig {
visible?: boolean
diff --git a/frontend/src/scenes/teamLogic.test.ts b/frontend/src/scenes/teamLogic.test.ts
index a215c5c44b6b..c634696667ac 100644
--- a/frontend/src/scenes/teamLogic.test.ts
+++ b/frontend/src/scenes/teamLogic.test.ts
@@ -109,9 +109,6 @@ describe('teamLogic', () => {
beforeEach(() => {
initKeaTests()
useMocks({
- get: {
- '/api/environments/:id/user_product_list': () => [200, { results: [], count: 0 }],
- },
patch: {
// Simulates the race hit in production: `complete_product_onboarding` serializes
// the team from a snapshot taken before the concurrent onboarding-completion
diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsx
index 588e3cb885f9..7ea6d3b57279 100644
--- a/frontend/src/scenes/teamLogic.tsx
+++ b/frontend/src/scenes/teamLogic.tsx
@@ -20,7 +20,6 @@ import {
} from 'lib/utils/product-intents'
import { identifierToHuman } from 'lib/utils/strings'
-import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
import {
CurrencyCode,
CustomerAnalyticsConfig,
@@ -124,7 +123,6 @@ export interface teamLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamLogicActions {
- loadCustomProducts: () => any // customProductsLogic
loadCurrentOrganization: () => any // organizationLogic
loadCurrentProjectSuccess: (
currentProject: ProjectType | null,
@@ -351,8 +349,6 @@ export const teamLogic = kea<teamLogicType>([
['loadUser', 'switchTeam'],
organizationLogic,
['loadCurrentOrganization'],
- customProductsLogic,
- ['loadCustomProducts'],
projectLogic,
['loadCurrentProjectSuccess'],
],
@@ -516,24 +512,17 @@ export const teamLogic = kea<teamLogicType>([
await api.update(`api/projects/${values.currentTeamId}/delete_secret_token_backup`, {}),
/**
* If adding a product intent that also represents regular product usage, see explainer in posthog.models.product_intent.product_intent.py.
- * Also, we refresh the list of custom products to show the possible new entry in the sidebar after we've added the intent.
*/
addProductIntent: async (properties: ProductIntentProperties) => {
const result = await addProductIntent(properties)
- actions.loadCustomProducts()
-
return withProductIntentsFrom(values.currentTeam, result)
},
addProductIntentForCrossSell: async (properties: ProductCrossSellProperties) => {
const result = await addProductIntentForCrossSell(properties)
- actions.loadCustomProducts()
-
return withProductIntentsFrom(values.currentTeam, result)
},
recordProductIntentOnboardingComplete: async (properties: ProductOnboardingCompleteProperties) => {
const result = await completeProductOnboarding(values.currentTeamIdStrict, properties)
- actions.loadCustomProducts()
-
return withProductIntentsFrom(values.currentTeam, result)
},
},
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index f68cab3923cd..0b264f260eed 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -82,7 +82,6 @@ import type {
RevenueAnalyticsConfig,
SharingConfigurationSettings,
TileFilters,
- UserProductListItem,
UserUIConfiguration,
} from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
@@ -5376,7 +5375,6 @@ export interface AppContext {
frontend_apps?: Record<number, FrontendAppConfig>
effective_resource_access_control: Record<AccessControlResourceType, AccessControlLevel>
resource_access_control: Record<AccessControlResourceType, AccessControlLevel>
- custom_products: UserProductListItem[]
commit_sha?: string
/** Whether the user was autoswitched to the current item's team. */
switched_team: TeamType['id'] | null
diff --git a/posthog/api/file_system/user_product_list.py b/posthog/api/file_system/user_product_list.py
deleted file mode 100644
index 73b15b9f311c..000000000000
--- a/posthog/api/file_system/user_product_list.py
+++ /dev/null
@@ -1,95 +0,0 @@
-from typing import Any, cast
-
-from django.db import transaction
-from django.db.models import QuerySet
-from django.db.models.functions import Lower
-
-from rest_framework import serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models import User
-from posthog.models.file_system.starred_products import star_custom_products
-from posthog.models.file_system.user_product_list import UserProductList, user_has_custom_products
-
-
-class UserProductListSerializer(serializers.ModelSerializer):
- class Meta:
- model = UserProductList
- fields = [
- "id",
- "product_path",
- "enabled",
- "created_at",
- "updated_at",
- ]
- read_only_fields = [
- "id",
- "product_path",
- "created_at",
- "updated_at",
- ]
-
- def create(self, validated_data: dict[str, Any], *args: Any, **kwargs: Any) -> UserProductList:
- request = self.context["request"]
- team = self.context["get_team"]()
-
- user = cast(User, request.user)
- had_custom_products = user_has_custom_products(user)
- user_product_list = UserProductList.objects.create(
- team=team,
- user=user,
- **validated_data,
- )
- if user_product_list.enabled:
- star_custom_products(user, team, [user_product_list.product_path], had_custom_products=had_custom_products)
-
- return user_product_list
-
-
-class UserProductListViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- queryset = UserProductList.objects.all()
- scope_object = "INTERNAL"
- serializer_class = UserProductListSerializer
-
- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
- return queryset.filter(team=self.team, user=self.request.user, enabled=True).order_by(Lower("product_path"))
-
- @action(methods=["PATCH"], detail=False, url_path="bulk_update")
- def bulk_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- items = request.data.get("items")
- if not isinstance(items, list) or len(items) == 0:
- return Response(
- {"error": "items is required and must be a non-empty list"}, status=status.HTTP_400_BAD_REQUEST
- )
-
- user = cast(User, request.user)
- had_custom_products = user_has_custom_products(user)
- results = []
- enabled_paths = []
- with transaction.atomic():
- for item in items:
- product_path = item.get("product_path")
- enabled = item.get("enabled")
- if not product_path or enabled is None:
- continue
-
- existing_item, created = UserProductList.objects.get_or_create(
- team=self.team,
- user=user,
- product_path=product_path,
- defaults={"enabled": enabled},
- )
- was_enabled = existing_item.enabled and not created
-
- serializer = self.get_serializer(existing_item, data=item, partial=True)
- serializer.is_valid(raise_exception=True)
- serializer.save()
- results.append(serializer.data)
- if existing_item.enabled and not was_enabled:
- enabled_paths.append(product_path)
-
- star_custom_products(user, self.team, enabled_paths, had_custom_products=had_custom_products)
- return Response({"results": results}, status=status.HTTP_200_OK)
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index ef554d4b3cde..41b970ef2a63 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -82,7 +82,7 @@ from .core_event import CoreEventViewSet
from .data_management import DataManagementViewSet
from .emoji_search import EmojiSearchViewSet
from .event_filter_config import EventFilterConfigViewSet
-from .file_system import file_system, file_system_shortcut, user_product_list
+from .file_system import file_system, file_system_shortcut
from .llm_prompt import LLMPromptViewSet
from .oauth import OrganizationOAuthApplicationViewSet
from .organization_notification_locks import OrganizationNotificationLockViewSet
@@ -232,13 +232,6 @@ projects_router.register(
)
-projects_router.register(
- r"user_product_list",
- user_product_list.UserProductListViewSet,
- "project_user_product_list",
- ["team_id"],
-)
-
projects_router.register(
r"event_definitions",
event_definition.EventDefinitionViewSet,
diff --git a/posthog/api/test/test_organization_invites.py b/posthog/api/test/test_organization_invites.py
index 3a201a749e06..96c5be6da349 100644
--- a/posthog/api/test/test_organization_invites.py
+++ b/posthog/api/test/test_organization_invites.py
@@ -16,6 +16,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import User
+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
from posthog.models.instance_setting import set_instance_setting
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -23,6 +24,8 @@ from posthog.models.organization_invite import OrganizationInvite
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.products import Products
+from posthog.schema_enums import ProductItemCategory
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role, RoleMembership
@@ -1642,12 +1645,14 @@ class TestOnboardingDelegationInviteAPI(APIBaseTest):
response = self.client.post(self._delegate_url(), {"target_email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ @patch("posthog.tasks.email.send_invite.apply_async")
@patch("posthoganalytics.capture")
- def test_delegate_creates_admin_level_invite_with_flag(self, _mock_capture):
- response = self.client.post(
- self._delegate_url(),
- {"target_email": "[email protected]", "message": "please help"},
- )
+ def test_delegate_creates_admin_level_invite_with_flag(self, _mock_capture, _mock_send_invite):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ self._delegate_url(),
+ {"target_email": "[email protected]", "message": "please help"},
+ )
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
invite = OrganizationInvite.objects.get(target_email="[email protected]")
self.assertTrue(invite.is_setup_delegation)
@@ -1658,6 +1663,14 @@ class TestOnboardingDelegationInviteAPI(APIBaseTest):
self.assertEqual(self.user.onboarding_delegated_to_invite_id, invite.id)
self.assertIsNotNone(self.user.onboarding_skipped_at)
self.assertEqual(self.user.onboarding_skipped_reason, "delegated")
+ # The delegator skipped onboarding, so every released product is starred to fill the sidebar.
+ released_paths = {
+ product.path for product in Products.products() if product.category != ProductItemCategory.UNRELEASED
+ }
+ starred_paths = set(
+ FileSystemShortcut.objects.filter(user=self.user, team=self.team).values_list("path", flat=True)
+ )
+ self.assertLessEqual(released_paths, starred_paths)
def test_delegate_rejects_email_outside_enforced_verified_domain(self):
# Delegation grants admin, so it must respect the same verified-domain rule as a normal invite.
diff --git a/posthog/management/commands/generate_demo_data.py b/posthog/management/commands/generate_demo_data.py
index b56c9875b776..8e4863bdb1f4 100644
--- a/posthog/management/commands/generate_demo_data.py
+++ b/posthog/management/commands/generate_demo_data.py
@@ -16,11 +16,8 @@ from django.db.utils import OperationalError
from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.health import get_pending_postgres_migrations
from posthog.management.commands.sync_feature_flags_from_api import sync_feature_flags_from_api
-from posthog.models import User
-from posthog.models.file_system.user_product_list import UserProductList
from posthog.models.team.setup_tasks import SetupTaskId
from posthog.models.team.team import Team
-from posthog.products import Products
from posthog.taxonomy.taxonomy import PERSON_PROPERTIES_ADAPTED_FROM_EVENT
from products.demo.backend.facade.api import (
@@ -117,12 +114,6 @@ class Command(BaseCommand):
default=False,
help="Skip syncing feature flags from API after data generation",
)
- parser.add_argument(
- "--skip-user-product-list",
- action="store_true",
- default=False,
- help="Skip creating UserProductList entries after data generation",
- )
parser.add_argument(
"--say-on-complete",
action="store_true",
@@ -236,15 +227,6 @@ class Command(BaseCommand):
else:
print("Skipping feature flag sync.")
- if not options.get("skip_user_product_list"):
- # Create UserProductList entries for all products
- # Skip if existing_team_id == 0 (master project reset)
- if existing_team_id != 0 and team and user:
- print("Creating UserProductList entries for all products...")
- self.create_default_user_product_list(team, user)
- else:
- print("Skipping UserProductList creation.")
-
if existing_team_id != 0 and team:
print("Marking all quick start tasks as completed...")
self.complete_all_quick_start_tasks(team)
@@ -390,21 +372,6 @@ class Command(BaseCommand):
backfill_period_days=backfill_days,
)
- def create_default_user_product_list(self, team: Team, user: User) -> None:
- """Create UserProductList entries for all default sidebar products."""
- product_paths = Products.get_product_paths()
- created_count = 0
- for product_path in product_paths:
- _, created = UserProductList.objects.get_or_create(
- team=team,
- user=user,
- product_path=product_path,
- defaults={"enabled": True},
- )
- if created:
- created_count += 1
- print(f"Created {created_count} UserProductList entries for {len(product_paths)} products.")
-
@staticmethod
def complete_all_quick_start_tasks(team: Team) -> None:
"""Mark all quick start tasks as completed so the setup UI doesn't show."""
diff --git a/posthog/models/file_system/starred_products.py b/posthog/models/file_system/starred_products.py
index e003176b556f..4acf99972041 100644
--- a/posthog/models/file_system/starred_products.py
+++ b/posthog/models/file_system/starred_products.py
@@ -1,15 +1,28 @@
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
from django.db import transaction
+from django.db.models import QuerySet
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut, lock_user_shortcuts
from posthog.models.user import User
from posthog.products import Products
+from posthog.schema_enums import ProductItemCategory, ProductKey
if TYPE_CHECKING:
+ from posthog.models.organization import Organization
+ from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.team import Team
+# The products every user starts with in a project. Paths must match `path` values in frontend/src/products.json.
+DEFAULT_PRODUCT_PATHS = [
+ "Product analytics",
+ "Dashboards",
+ "Web analytics",
+ "Error tracking",
+ "Session replay",
+]
+
def starred_products_setup_completed(user: User) -> bool:
configuration = user.ui_configuration
@@ -33,6 +46,17 @@ def mark_starred_products_setup_completed(user: User) -> None:
user.save(update_fields=["ui_configuration"])
+def _project_shortcuts(user: User, team: "Team") -> QuerySet[FileSystemShortcut]:
+ # The sidebar lists the shortcuts of every environment in the project, so checks span them all.
+ # nosemgrep: environment-model-scoped-by-project -- the shortcut API lists a user's own stars project-wide
+ return FileSystemShortcut.objects.filter(surface_q(DEFAULT_SURFACE), team__project_id=team.project_id, user=user)
+
+
+def _product_stars(user: User, team: "Team") -> QuerySet[FileSystemShortcut]:
+ # Product stars have no ref. Starred files and folders point at their item through one.
+ return _project_shortcuts(user, team).filter(ref__isnull=True).exclude(type="folder")
+
+
def star_products(user: User, team: "Team", product_paths: list[str]) -> int:
"""Star products on the user's sidebar for a team, after their existing stars. Returns how many were added.
@@ -42,14 +66,8 @@ def star_products(user: User, team: "Team", product_paths: list[str]) -> int:
with transaction.atomic():
# Concurrent writes for the same user would otherwise both miss the star and add it twice.
lock_user_shortcuts(team.pk, user.pk)
- # The sidebar lists the stars of every environment in the project, so check them all.
- # nosemgrep: environment-model-scoped-by-project -- the shortcut API lists a user's own stars project-wide
- user_shortcuts = FileSystemShortcut.objects.filter(
- surface_q(DEFAULT_SURFACE), team__project_id=team.project_id, user=user
- )
- starred_paths = set(
- user_shortcuts.filter(ref__isnull=True).exclude(type="folder").values_list("path", flat=True)
- )
+ user_shortcuts = _project_shortcuts(user, team)
+ starred_paths = set(_product_stars(user, team).values_list("path", flat=True))
next_order = max(user_shortcuts.values_list("order", flat=True), default=0) + 1
to_create: list[FileSystemShortcut] = []
@@ -73,25 +91,45 @@ def star_products(user: User, team: "Team", product_paths: list[str]) -> int:
return len(to_create)
-def star_custom_products(user: User, team: "Team", product_paths: list[str], *, had_custom_products: bool) -> None:
- """Star products that were just added to a user's custom products.
-
- The simple sidebar shows starred products instead of custom products, so every write that adds
- custom products calls this to keep the two in step. `had_custom_products` says whether the user
- had any custom products, in any project, before the write:
+def star_default_products(user: User, team: "Team") -> None:
+ """Star the default products for a user who just got access to a project.
- - A user with none is brand new, so their products are starred and the setup is marked done.
- - A user who finished the setup gets the new products starred too.
- - A user with custom products who has not done the setup yet is left alone. The setup card
- offers their whole list, so starring one suggestion must not complete it for them.
+ A user who already has product stars in the project made their own choice, so nothing is added.
"""
- if not product_paths:
- return
- completed = starred_products_setup_completed(user)
- if not completed and had_custom_products:
+ if _product_stars(user, team).exists():
return
+ star_products(user, team, DEFAULT_PRODUCT_PATHS)
+
- star_products(user, team, product_paths)
+def star_default_products_for_accessible_teams(user: User, organization: "Organization") -> None:
+ """Star the default products in every project of the organization the user has access to."""
+ from products.access_control.backend.facade.user_access_control import ( # noqa: PLC0415 - avoids a circular import
+ UserAccessControl,
+ )
- if not completed:
- mark_starred_products_setup_completed(user)
+ uac = UserAccessControl(user=user, organization_id=str(organization.id))
+ accessible_teams = uac.filter_queryset_by_access_level(organization.teams.all(), include_all_if_admin=True)
+
+ for team in accessible_teams:
+ star_default_products(user, team)
+
+
+def star_released_products(user: User, team: "Team") -> None:
+ """Star every released product. Unreleased products stay opt-in, so they are left out."""
+ star_products(
+ user,
+ team,
+ [product.path for product in Products.products() if product.category != ProductItemCategory.UNRELEASED],
+ )
+
+
+def star_products_from_intent(product_intent: "ProductIntent", user: User) -> None:
+ """Star the products behind a new product intent, unless the user turned off sidebar suggestions.
+
+ Call this only when the intent is first created. Intents are registered again every time the
+ product is used, so starring on every call would bring back products the user unstarred.
+ """
+ if user.allow_sidebar_suggestions is False:
+ return
+ products = Products.get_products_by_intent(cast(ProductKey, product_intent.product_type))
+ star_products(user, product_intent.team, [product.path for product in products])
diff --git a/posthog/models/file_system/test/test_user_product_list.py b/posthog/models/file_system/test/test_user_product_list.py
deleted file mode 100644
index 22c6e0a8cc81..000000000000
--- a/posthog/models/file_system/test/test_user_product_list.py
+++ /dev/null
@@ -1,133 +0,0 @@
-from typing import cast
-
-from posthog.test.base import BaseTest
-
-from django.utils.functional import SimpleLazyObject
-
-from parameterized import parameterized
-
-from posthog.models import ProductIntent, Team, User
-from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
-from posthog.models.file_system.starred_products import starred_products_setup_completed
-from posthog.models.file_system.user_product_list import (
- DEFAULT_PRODUCT_PATHS,
- UserProductList,
- add_default_products_for_user,
-)
-from posthog.products import Products
-from posthog.schema_enums import ProductKey
-
-
-class TestUserProductList(BaseTest):
- def test_default_product_paths_are_valid_products(self):
- valid_paths = set(Products.get_product_paths())
- assert set(DEFAULT_PRODUCT_PATHS) <= valid_paths
-
- def test_add_default_products_creates_the_default_set(self):
- user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
-
- created_items = add_default_products_for_user(user, self.team)
-
- assert {item.product_path for item in created_items} == set(DEFAULT_PRODUCT_PATHS)
-
- rows = UserProductList.objects.filter(user=user, team=self.team)
- assert {row.product_path for row in rows} == set(DEFAULT_PRODUCT_PATHS)
- for row in rows:
- assert row.enabled is True
-
- def test_add_default_products_leaves_existing_rows_untouched(self):
- user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
-
- UserProductList.objects.create(
- user=user,
- team=self.team,
- product_path="Product analytics",
- enabled=False,
- )
-
- created_items = add_default_products_for_user(user, self.team)
-
- assert "Product analytics" not in {item.product_path for item in created_items}
- existing = UserProductList.objects.get(user=user, team=self.team, product_path="Product analytics")
- assert existing.enabled is False
-
- add_default_products_for_user(user, self.team)
- assert UserProductList.objects.filter(user=user, team=self.team).count() == len(DEFAULT_PRODUCT_PATHS)
-
- def test_join_seeds_default_products_for_accessible_teams(self):
- # Guards joins that don't go through an invite (e.g. domain/SSO auto-join):
- # seeding must live in User.join itself, not only in the invite flow.
- user = User.objects.create_user(email="[email protected]", password="password", first_name="Joiner")
-
- user.join(organization=self.organization)
-
- rows = UserProductList.objects.filter(user=user, team=self.team)
- assert {row.product_path for row in rows} == set(DEFAULT_PRODUCT_PATHS)
- for row in rows:
- assert row.enabled is True
-
-
-class TestStarCustomProductsForSimpleSidebar(BaseTest):
- def _starred(self, user: User) -> dict[str, str]:
- return dict(FileSystemShortcut.objects.filter(user=user, team=self.team).values_list("path", "type"))
-
- @parameterized.expand(
- [
- ("brand_new_user", False, False, set(DEFAULT_PRODUCT_PATHS), True),
- ("existing_user_mid_migration", True, False, set(), False),
- ("user_who_finished_setup", True, True, set(DEFAULT_PRODUCT_PATHS), True),
- ]
- )
- def test_default_products_are_starred_only_for_new_or_finished_users(
- self,
- _name: str,
- has_custom_products: bool,
- setup_completed: bool,
- expected_starred: set[str],
- expected_completed: bool,
- ) -> None:
- user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
- if has_custom_products:
- other_team = Team.objects.create(organization=self.organization, name="Other")
- UserProductList.objects.create(user=user, team=other_team, product_path="Logs", enabled=True)
- if setup_completed:
- user.ui_configuration = {
- "version": 1,
- "sidebar": {"density": "compact", "starred_products_setup_completed": True},
- }
- user.save()
-
- add_default_products_for_user(cast(User, SimpleLazyObject(lambda: user)), self.team)
-
- assert set(self._starred(user)) == expected_starred
- user.refresh_from_db()
- assert starred_products_setup_completed(user) is expected_completed
- if setup_completed:
- assert (user.ui_configuration or {})["sidebar"]["density"] == "compact"
-
- def test_product_intent_stars_only_new_products_without_duplicates(self) -> None:
- user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
- user.ui_configuration = {"version": 1, "sidebar": {"starred_products_setup_completed": True}}
- user.save()
- FileSystemShortcut.objects.create(team=self.team, user=user, path="Session replay", type="session_replay")
- intent = ProductIntent.objects.create(team=self.team, product_type="session_replay")
-
- UserProductList.create_from_product_intent(intent, user)
- UserProductList.create_from_product_intent(intent, user)
-
- assert FileSystemShortcut.objects.filter(user=user, team=self.team, path="Session replay").count() == 1
- assert set(self._starred(user)) == {
- product.path for product in Products.get_products_by_intent(ProductKey.SESSION_REPLAY)
- }
-
- def test_enable_all_keeps_the_star_choice_of_already_enabled_products(self) -> None:
- user = User.objects.create_user(email="[email protected]", password="password", first_name="User")
- user.ui_configuration = {"version": 1, "sidebar": {"starred_products_setup_completed": True}}
- user.save()
- UserProductList.objects.create(user=user, team=self.team, product_path="Session replay", enabled=True)
-
- UserProductList.enable_all_for_user(user, self.team)
-
- starred = set(self._starred(user))
- assert "Session replay" not in starred
- assert "Product analytics" in starred
diff --git a/posthog/models/file_system/user_product_list.py b/posthog/models/file_system/user_product_list.py
index a77e824c4978..47f310733c0a 100644
--- a/posthog/models/file_system/user_product_list.py
+++ b/posthog/models/file_system/user_product_list.py
@@ -1,86 +1,20 @@
-from typing import TYPE_CHECKING, ClassVar, cast
+from typing import ClassVar
from django.conf import settings
from django.db import models, transaction
from django.db.models.expressions import F
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
-from django.utils import timezone
-from posthog.models.file_system.starred_products import star_custom_products
+from posthog.models.file_system.starred_products import star_default_products
from posthog.models.utils import UpdatedMetaFields, UUIDModel, uuid7
-from posthog.products import Products
-from posthog.schema_enums import ProductItemCategory, ProductKey
-
-if TYPE_CHECKING:
- from posthog.models.organization import Organization
- from posthog.models.product_intent.product_intent import ProductIntent
- from posthog.models.team import Team
- from posthog.models.user import User
-
-# The baseline sidebar: every user gets these whenever they gain access to a project.
-# Paths must match `path` values in frontend/src/products.json.
-DEFAULT_PRODUCT_PATHS = [
- "Product analytics",
- "Dashboards",
- "Web analytics",
- "Error tracking",
- "Session replay",
-]
-
-
-def add_default_products_for_user(user: "User", team: "Team") -> "list[UserProductList]":
- """
- Add the default set of products to a user's sidebar for a team.
-
- Called whenever a user/project connection is created (project creation, invite
- acceptance, access grants). Rows the user already has - enabled or intentionally
- disabled - are left untouched.
- """
- existing_paths = set(
- UserProductList.objects.filter(user=user, team=team, product_path__in=DEFAULT_PRODUCT_PATHS).values_list(
- "product_path", flat=True
- )
- )
- missing_paths = [path for path in DEFAULT_PRODUCT_PATHS if path not in existing_paths]
- if not missing_paths:
- return []
-
- had_custom_products = user_has_custom_products(user)
- # `ignore_conflicts` + `unique_together` on (team, user, product_path) keep this
- # idempotent under concurrent seeding.
- created = UserProductList.objects.bulk_create(
- [UserProductList(user=user, team=team, product_path=path, enabled=True) for path in missing_paths],
- ignore_conflicts=True,
- )
- star_custom_products(user, team, missing_paths, had_custom_products=had_custom_products)
- return created
-
-
-def user_has_custom_products(user: "User") -> bool:
- """Whether the user has any enabled custom product in any project."""
- return UserProductList.objects.filter(user=user, enabled=True).exists()
-
-
-def add_default_products_for_accessible_teams(user: "User", organization: "Organization") -> None:
- """
- Add the default products to the user's sidebar for every team in the organization
- they have access to. Called when a user/organization connection is created (invite
- acceptance, domain/SSO auto-join).
- """
- from products.access_control.backend.facade.user_access_control import UserAccessControl
-
- uac = UserAccessControl(user=user, organization_id=str(organization.id))
- accessible_teams = uac.filter_queryset_by_access_level(organization.teams.all(), include_all_if_admin=True)
-
- for team in accessible_teams:
- add_default_products_for_user(user, team)
class UserProductList(UUIDModel, UpdatedMetaFields):
"""
- Stores a user's custom list of products they care about.
- Products are identified by their path from the static products list.
+ A user's custom sidebar products from before starred products replaced them.
+
+ Nothing writes it anymore. It stays until the starred products backfill has moved every user over.
"""
# django-stubs normally injects the default `objects` manager during mypy's semantic pass,
@@ -115,82 +49,15 @@ class UserProductList(UUIDModel, UpdatedMetaFields):
verbose_name = "User Product List"
verbose_name_plural = "User Product Lists"
- @staticmethod
- def enable_all_for_user(user: "User", team: "Team") -> "list[UserProductList]":
- """Enable every released product in the sidebar for a user on a given team.
-
- Skips Unreleased/alpha products — those are intentionally opt-in (mirroring the
- EditCustomProductsModal "Unreleased" group, which the user must enable one-by-one).
- Re-enables rows the user previously disabled.
- """
- target_paths = [
- product.path for product in Products.products() if product.category != ProductItemCategory.UNRELEASED
- ]
- if not target_paths:
- return []
-
- # Bulk-create rows that don't yet exist (~one query) instead of N sequential
- # `get_or_create` round-trips, then bulk-flip any rows the user had previously
- # disabled. `unique_together` on (team, user, product_path) makes this idempotent.
- # `auto_now` doesn't fire on bulk update, so set updated_at explicitly.
- had_custom_products = user_has_custom_products(user)
- already_enabled = set(
- UserProductList.objects.filter(
- user=user, team=team, product_path__in=target_paths, enabled=True
- ).values_list("product_path", flat=True)
- )
- UserProductList.objects.bulk_create(
- [UserProductList(user=user, team=team, product_path=path, enabled=True) for path in target_paths],
- ignore_conflicts=True,
- )
- UserProductList.objects.filter(user=user, team=team, product_path__in=target_paths, enabled=False).update(
- enabled=True, updated_at=timezone.now()
- )
- # Products that were already enabled keep whatever star choice the user made for them.
- newly_enabled = [path for path in target_paths if path not in already_enabled]
- star_custom_products(user, team, newly_enabled, had_custom_products=had_custom_products)
- return list(UserProductList.objects.filter(user=user, team=team, product_path__in=target_paths))
-
- @staticmethod
- def create_from_product_intent(product_intent: "ProductIntent", user: "User") -> "list[UserProductList]":
- if user.allow_sidebar_suggestions is False:
- return []
-
- products = Products.get_products_by_intent(cast(ProductKey, product_intent.product_type))
- if not products:
- return []
-
- had_custom_products = user_has_custom_products(user)
- user_product_lists = []
- added_paths = []
- for product in products:
- item, created = UserProductList.objects.get_or_create(
- user=user,
- team=product_intent.team,
- product_path=product.path,
- defaults={"enabled": True},
- )
- user_product_lists.append(item)
- if created:
- added_paths.append(product.path)
-
- star_custom_products(user, product_intent.team, added_paths, had_custom_products=had_custom_products)
- return user_product_lists
-
@receiver(post_save, sender="ee.AccessControl")
def access_control_created(sender, instance, created, **kwargs):
- """
- Handle AccessControl creation to seed UserProductList for users gaining access to a team.
-
- When a user is granted access to a team via AccessControl, we add the default set of
- products to their sidebar for that team.
- """
+ """Star the default products for a user who is granted access to a project."""
if created and instance.organization_member and instance.resource == "project":
user = instance.organization_member.user
team = instance.team
if settings.TEST:
- add_default_products_for_user(user, team)
+ star_default_products(user, team)
else:
- transaction.on_commit(lambda: add_default_products_for_user(user, team))
+ transaction.on_commit(lambda: star_default_products(user, team))
diff --git a/posthog/models/onboarding_delegation.py b/posthog/models/onboarding_delegation.py
index 32e6f4b3715b..8d38c59bb76a 100644
--- a/posthog/models/onboarding_delegation.py
+++ b/posthog/models/onboarding_delegation.py
@@ -87,9 +87,8 @@ def set_delegated_state(*, locked_user: User, invite: OrganizationInvite, organi
"onboarding_delegation_accepted_at",
]
)
- # Sidebar seeding runs ~37 get_or_create calls (one per released product). Defer it
- # to post-commit so the held select_for_update locks on Organization and User aren't
- # extended by dozens of sequential DB roundtrips.
+ # Defer sidebar seeding to post-commit, so the held select_for_update locks on Organization
+ # and User aren't extended by the extra DB roundtrips it needs.
user_id = locked_user.id
def _seed_after_commit() -> None:
@@ -109,18 +108,18 @@ def set_delegated_state(*, locked_user: User, invite: OrganizationInvite, organi
def _seed_sidebar_for_delegator(*, user_id: int, organization_id: UUID | str) -> None:
- """Enable all released products on the delegator's sidebar for the delegated org.
+ """Star all released products on the delegator's sidebar for the delegated org.
The post-delegation home page would otherwise be empty (no product intents recorded
during a skipped onboarding). We seed against the user's current_team if it's in the
delegated org; otherwise pick any team in the org they have access to. A failure here
must not block the delegation itself, so we swallow exceptions after capturing them.
"""
- # Local imports to avoid pulling Team and UserProductList (and their transitive model
- # graph) into module-load order — onboarding_delegation is imported by Django model
+ # Local imports to avoid pulling Team and the starred products module (and their transitive
+ # model graph) into module-load order — onboarding_delegation is imported by Django model
# modules during app loading and module-level cross-model imports here have triggered
# apps-not-ready issues.
- from posthog.models.file_system.user_product_list import UserProductList
+ from posthog.models.file_system.starred_products import star_released_products
from posthog.models.team.team import Team
try:
@@ -135,7 +134,7 @@ def _seed_sidebar_for_delegator(*, user_id: int, organization_id: UUID | str) ->
team = Team.objects.filter(organization_id=organization_id).order_by("id").first()
if team is None:
return
- UserProductList.enable_all_for_user(user=user, team=team)
+ star_released_products(user, team)
except Exception as exc: # noqa: BLE001 - sidebar seeding must never block delegation
capture_exception(exc)
# Pair the Sentry capture with an indexable structured log so ops can correlate
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index a2dfc9fb70f4..5b5d484225f4 100644
--- a/posthog/models/product_intent/product_intent.py
+++ b/posthog/models/product_intent/product_intent.py
@@ -315,7 +315,7 @@ class ProductIntent(UUIDTModel, RootTeamMixin):
is_onboarding: bool = False,
) -> "ProductIntent":
from posthog.event_usage import report_user_action
- from posthog.models.file_system.user_product_list import UserProductList
+ from posthog.models.file_system.starred_products import star_products_from_intent
product_intent, created = ProductIntent.objects.get_or_create(team=team, product_type=product_type)
@@ -358,7 +358,8 @@ class ProductIntent(UUIDTModel, RootTeamMixin):
)
try:
- UserProductList.create_from_product_intent(product_intent, user)
+ if created:
+ star_products_from_intent(product_intent, user)
except Exception as e:
capture_exception(
e, additional_properties={"product_type": product_type, "context": context, "user_id": user.id}
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 5a8d1aa17dc2..610e4801269f 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -85,7 +85,7 @@ assert len(CURRENCY_CODE_CHOICES) == 152
DEFAULT_CURRENCY = CurrencyCode.USD.value
-ASYNC_USER_PRODUCT_LIST_SYNC_THRESHOLD = 100
+ASYNC_DEFAULT_STARRED_PRODUCTS_THRESHOLD = 100
class AvailableExtraSettings:
@@ -166,15 +166,15 @@ class TeamManager(models.Manager):
)
team.save()
- # Add UserProductList for all users who have access to this new team
+ # Star the default products for all users who have access to this new team
# For large orgs, dispatch async to avoid request timeouts
- from posthog.tasks.tasks import sync_user_product_lists_for_new_team
+ from posthog.tasks.tasks import star_default_products_for_new_team
user_count = OrganizationMembership.objects.filter(organization_id=team.organization_id).count()
- if user_count > ASYNC_USER_PRODUCT_LIST_SYNC_THRESHOLD:
- transaction.on_commit(lambda: sync_user_product_lists_for_new_team.delay(team.id))
+ if user_count > ASYNC_DEFAULT_STARRED_PRODUCTS_THRESHOLD:
+ transaction.on_commit(lambda: star_default_products_for_new_team.delay(team.id))
else:
- sync_user_product_lists_for_new_team(team.id)
+ star_default_products_for_new_team(team.id)
return team
diff --git a/posthog/models/test/test_user_product_list_invites.py b/posthog/models/test/test_default_starred_products.py
similarity index 63%
rename from posthog/models/test/test_user_product_list_invites.py
rename to posthog/models/test/test_default_starred_products.py
index 2cee17aeb11c..fe99699c7b78 100644
--- a/posthog/models/test/test_user_product_list_invites.py
+++ b/posthog/models/test/test_default_starred_products.py
@@ -1,20 +1,43 @@
from posthog.test.base import BaseTest
from unittest.mock import patch
+from parameterized import parameterized
+
from posthog.constants import AvailableFeature
from posthog.models import Team, User
-from posthog.models.file_system.user_product_list import DEFAULT_PRODUCT_PATHS, UserProductList
+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
+from posthog.models.file_system.starred_products import DEFAULT_PRODUCT_PATHS, star_default_products
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_invite import OrganizationInvite
+from posthog.products import Products
from products.access_control.backend.models.access_control import AccessControl
-class TestUserProductListDefaults(BaseTest):
+class TestDefaultStarredProducts(BaseTest):
def _default_paths_for(self, user: User, team: Team) -> set[str]:
- return set(
- UserProductList.objects.filter(user=user, team=team, enabled=True).values_list("product_path", flat=True)
+ return set(FileSystemShortcut.objects.filter(user=user, team=team).values_list("path", flat=True))
+
+ def test_default_product_paths_are_valid_products(self):
+ assert set(DEFAULT_PRODUCT_PATHS) <= set(Products.get_product_paths())
+
+ @parameterized.expand([("same_environment", False), ("other_environment_of_the_project", True)])
+ def test_leaves_a_user_who_already_starred_products_in_the_project_alone(
+ self, _name: str, star_in_other_environment: bool
+ ) -> None:
+ user = User.objects.create_user(email="[email protected]", password="password", first_name="Starred")
+ other_environment = Team.objects.create(organization=self.organization, project=self.project, name="Staging")
+ starred_team = other_environment if star_in_other_environment else self.team
+ FileSystemShortcut.objects.create(team=starred_team, user=user, path="Logs", type="logs")
+
+ star_default_products(user, self.team)
+
+ starred = list(
+ FileSystemShortcut.objects.filter(user=user, team__project_id=self.project.id).values_list(
+ "path", flat=True
+ )
)
+ assert starred == ["Logs"]
def _make_team_private(self, team: Team) -> None:
# Project-level access controls only apply when the org has the feature.
@@ -52,22 +75,31 @@ class TestUserProductListDefaults(BaseTest):
assert self._default_paths_for(new_user, self.team) == set(DEFAULT_PRODUCT_PATHS)
- def test_creating_team_adds_default_products_for_all_users_with_access(self):
+ @parameterized.expand([("new_project", False), ("new_environment_of_an_existing_project", True)])
+ def test_creating_team_adds_default_products_only_for_a_new_project(
+ self, _name: str, in_existing_project: bool
+ ) -> None:
member = User.objects.create_user(email="[email protected]", password="password", first_name="Member")
member.join(organization=self.organization)
creator = User.objects.create_user(email="[email protected]", password="password", first_name="Creator")
creator.join(organization=self.organization)
+ # Both users removed every star, which the new environment must not undo.
+ FileSystemShortcut.objects.filter(user__in=[member, creator]).delete()
new_team = Team.objects.create_with_data(
- initiating_user=creator, organization=self.organization, name="New Team"
+ initiating_user=creator,
+ organization=self.organization,
+ name="New Team",
+ **({"project": self.project} if in_existing_project else {}),
)
- assert self._default_paths_for(creator, new_team) == set(DEFAULT_PRODUCT_PATHS)
- assert self._default_paths_for(member, new_team) == set(DEFAULT_PRODUCT_PATHS)
+ expected = set() if in_existing_project else set(DEFAULT_PRODUCT_PATHS)
+ assert self._default_paths_for(creator, new_team) == expected
+ assert self._default_paths_for(member, new_team) == expected
def test_creating_team_in_a_large_organization_adds_default_products_after_commit(self) -> None:
with (
- patch("posthog.models.team.team.ASYNC_USER_PRODUCT_LIST_SYNC_THRESHOLD", 0),
+ patch("posthog.models.team.team.ASYNC_DEFAULT_STARRED_PRODUCTS_THRESHOLD", 0),
self.captureOnCommitCallbacks(execute=True),
):
new_team = Team.objects.create_with_data(
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index d3f9300e6180..691f3747010c 100644
--- a/posthog/models/test/test_product_intent.py
+++ b/posthog/models/test/test_product_intent.py
@@ -11,7 +11,7 @@ from parameterized import parameterized
from posthog.schema import ProductIntentContext, ProductKey
-from posthog.models.file_system.user_product_list import UserProductList
+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
from posthog.models.product_intent.product_intent import (
ProductIntent,
_fetch_product_intents,
@@ -36,9 +36,9 @@ from products.workflows.backend.facade.testing import create_workflow_for_test
class TestProductIntent(BaseTest):
def setUp(self):
super().setUp()
- # Joining the org seeds the fixed default product set; these tests assert on
- # product-intent-driven rows, so start from a clean slate.
- UserProductList.objects.filter(user=self.user, team=self.team).delete()
+ # Joining the org stars the default products. These tests assert on the stars that
+ # product intents add, so they start without any.
+ FileSystemShortcut.objects.filter(user=self.user, team=self.team).delete()
self.product_intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.DATA_WAREHOUSE)
def test_str_representation(self):
@@ -627,111 +627,39 @@ class TestProductIntent(BaseTest):
assert self.product_intent.activation_last_checked_at == datetime(2024, 6, 15, 12, 0, 0, tzinfo=UTC)
assert self.product_intent.activation_last_checked_at != initial_last_checked
- def test_register_creates_user_product_list_entries_for_single_product_intent(self):
- ProductIntent.register(
- self.team, ProductKey.SESSION_REPLAY, ProductIntentContext.SESSION_REPLAY_SET_FILTERS, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 1
-
- upl = user_product_lists.get()
- assert upl.product_path == "Session replay"
- assert upl.enabled is True
-
- def test_register_creates_user_product_list_entries_for_multiple_product_intent(self):
- ProductIntent.register(
- self.team, ProductKey.DATA_WAREHOUSE, ProductIntentContext.DATA_WAREHOUSE_SOURCES_TABLE, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team).order_by("product_path")
- assert user_product_lists.count() == 3
-
- product_paths = {upl.product_path for upl in user_product_lists}
- assert product_paths == {"Data warehouse", "SQL editor", "ETL"}
+ def _starred_paths(self) -> set[str]:
+ return set(FileSystemShortcut.objects.filter(user=self.user, team=self.team).values_list("path", flat=True))
- enabled = [upl.enabled for upl in user_product_lists]
- assert all(enabled)
-
- def test_register_ignores_product_key_without_products(self):
- ProductIntent.register(
- self.team, ProductKey.ANNOTATIONS, ProductIntentContext.DATA_WAREHOUSE_SOURCES_TABLE, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 0
-
- def test_register_respects_allow_sidebar_suggestions_false(self):
- self.user.allow_sidebar_suggestions = False
+ @parameterized.expand(
+ [
+ ("single_product", ProductKey.SESSION_REPLAY, None, {"Session replay"}),
+ ("several_products", ProductKey.PRODUCT_ANALYTICS, None, {"Dashboards", "Product analytics"}),
+ ("no_products", ProductKey.ANNOTATIONS, None, set()),
+ ("suggestions_on", ProductKey.SURVEYS, True, {"Surveys"}),
+ ("suggestions_off", ProductKey.SURVEYS, False, set()),
+ ]
+ )
+ def test_register_stars_the_products_of_a_new_intent(
+ self, _name: str, product_key: ProductKey, allow_sidebar_suggestions: bool | None, expected: set[str]
+ ) -> None:
+ self.user.allow_sidebar_suggestions = allow_sidebar_suggestions
self.user.save()
- ProductIntent.register(
- self.team, ProductKey.DATA_WAREHOUSE, ProductIntentContext.DATA_WAREHOUSE_SOURCES_TABLE, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 0
+ ProductIntent.register(self.team, product_key, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user)
- def test_register_does_not_create_duplicates_on_multiple_calls(self):
- assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 0
+ assert self._starred_paths() == expected
+ def test_register_does_not_star_again_once_the_intent_exists(self) -> None:
ProductIntent.register(
self.team, ProductKey.SESSION_REPLAY, ProductIntentContext.ONBOARDING_PRODUCT_SELECTED___PRIMARY, self.user
)
- assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 1
+ FileSystemShortcut.objects.filter(user=self.user, team=self.team, path="Session replay").delete()
ProductIntent.register(
self.team, ProductKey.SESSION_REPLAY, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
)
- assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 1
- def test_register_creates_user_product_list_for_different_intents(self):
- ProductIntent.register(
- self.team, ProductKey.SESSION_REPLAY, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
- )
- assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 1
-
- ProductIntent.register(
- self.team, ProductKey.PRODUCT_ANALYTICS, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
- )
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 3
-
- product_paths = {upl.product_path for upl in user_product_lists}
- assert product_paths == {"Session replay", "Dashboards", "Product analytics"}
-
- def test_register_allows_creation_when_allow_sidebar_suggestions_is_none(self):
- self.user.allow_sidebar_suggestions = None
- self.user.save()
-
- ProductIntent.register(
- self.team, ProductKey.SURVEYS, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 1
- assert user_product_lists.get().product_path == "Surveys"
-
- def test_register_allows_creation_when_allow_sidebar_suggestions_is_true(self):
- self.user.allow_sidebar_suggestions = True
- self.user.save()
-
- ProductIntent.register(
- self.team, ProductKey.SURVEYS, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
- )
-
- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)
- assert user_product_lists.count() == 1
- assert user_product_lists.get().product_path == "Surveys"
-
- def test_register_rejects_creation_when_allow_sidebar_suggestions_is_false(self):
- self.user.allow_sidebar_suggestions = False
- self.user.save()
-
- ProductIntent.register(
- self.team, ProductKey.SURVEYS, ProductIntentContext.QUICK_START_PRODUCT_SELECTED, self.user
- )
- assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 0
+ assert self._starred_paths() == set()
def _make_ai_generation_event_definition(self) -> EventDefinition:
return EventDefinition.objects.create(team=self.team, name="$ai_generation")
diff --git a/posthog/models/user.py b/posthog/models/user.py
index c6fb978a7be6..589a4ef595e8 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -560,11 +560,11 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
# After role assignment, so role-granted project access is included. Covers joins
# that don't go through an invite (e.g. domain/SSO auto-join).
- from posthog.models.file_system.user_product_list import ( # noqa: PLC0415 - avoids a circular import
- add_default_products_for_accessible_teams,
+ from posthog.models.file_system.starred_products import ( # noqa: PLC0415 - avoids a circular import
+ star_default_products_for_accessible_teams,
)
- add_default_products_for_accessible_teams(self, organization)
+ star_default_products_for_accessible_teams(self, organization)
return membership
diff --git a/posthog/schema.py b/posthog/schema.py
index b7fa79d969ad..930b65e86024 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -3529,17 +3529,6 @@ class UserBasicType(BaseModel):
uuid: str
-class UserProductListItem(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- created_at: str
- enabled: bool
- id: str
- product_path: str
- updated_at: str
-
-
class VectorSearchResponseItem(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index a17f485cd02a..3344cc714095 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -1798,30 +1798,37 @@ def refresh_activity_log_fields_cache(flush: bool = False, hours_back: int = 14)
)
-@shared_task(ignore_result=True)
+# Registered under the previous name, so messages queued by the previous deploy still run.
+@shared_task(ignore_result=True, name="posthog.tasks.tasks.sync_user_product_lists_for_new_team")
@skip_team_scope_audit
-def sync_user_product_lists_for_new_team(team_id: int) -> None:
+def star_default_products_for_new_team(team_id: int) -> None:
"""
- Sync UserProductList for all users who have access to a new team.
+ Star the default products for all users who have access to a new team.
Called during project creation to avoid request timeouts for large organizations.
"""
- from posthog.models.file_system.user_product_list import add_default_products_for_user
+ from posthog.models.file_system.starred_products import star_default_products
from posthog.models.team import Team
try:
team = Team.objects.get(id=team_id)
except Team.DoesNotExist:
- logger.info("sync_user_product_lists_for_new_team: Team not found, skipping", team_id=team_id)
+ logger.info("star_default_products_for_new_team: Team not found, skipping", team_id=team_id)
+ return
+
+ # Environments of a project share its sidebar stars. Seeding a new environment would restore
+ # defaults that users of the project already removed.
+ if Team.objects.filter(project_id=team.project_id).exclude(id=team.id).exists():
+ logger.info("star_default_products_for_new_team: Team is a new environment, skipping", team_id=team_id)
return
users = list(team.all_users_with_access())
logger.info(
- "sync_user_product_lists_for_new_team: Starting sync",
+ "star_default_products_for_new_team: Starting",
team_id=team_id,
user_count=len(users),
)
for user in users:
- add_default_products_for_user(user, team)
+ star_default_products(user, team)
- logger.info("sync_user_product_lists_for_new_team: Completed", team_id=team_id)
+ logger.info("star_default_products_for_new_team: Completed", team_id=team_id)
diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.py
index 061421a185f7..fb3390a44ada 100644
--- a/posthog/test/playwright_setup_functions.py
+++ b/posthog/test/playwright_setup_functions.py
@@ -176,7 +176,6 @@ def create_organization_with_team(
"say_on_complete": False,
"skip_materialization": True,
"skip_flag_sync": True,
- "skip_user_product_list": True,
}
with tags_context(product=Product.INTERNAL, feature=Feature.MANAGEMENT_COMMAND):
diff --git a/posthog/test/starred_products.py b/posthog/test/starred_products.py
index 4a3ccc93f819..1fddefd7ab99 100644
--- a/posthog/test/starred_products.py
+++ b/posthog/test/starred_products.py
@@ -10,6 +10,6 @@ def start_without_default_starred_products(test_case: TestCase) -> None:
For tests about the shortcuts a user creates, where the defaults would only add rows to every assertion.
"""
FileSystemShortcut.objects.all().delete()
- patcher = patch("posthog.models.file_system.user_product_list.add_default_products_for_accessible_teams")
+ patcher = patch("posthog.models.file_system.starred_products.star_default_products_for_accessible_teams")
patcher.start()
test_case.addCleanup(patcher.stop)
diff --git a/posthog/utils.py b/posthog/utils.py
index 99b34dbb536f..affdd602c62e 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -27,7 +27,7 @@ from django.apps import apps
from django.conf import settings
from django.core.cache import cache
from django.db import ProgrammingError, models
-from django.db.models.functions import Coalesce, Lower
+from django.db.models.functions import Coalesce
from django.db.utils import DatabaseError
from django.http import HttpRequest, HttpResponse
from django.template.loader import get_template
@@ -594,12 +594,10 @@ def _build_template_context(
# Set the frontend app context
# nosemgrep: api-query-param-underscore -- shipped public API param, a rename breaks clients
if not request.GET.get("no-preloaded-app-context"):
- from posthog.api.file_system.user_product_list import UserProductListSerializer
from posthog.api.project import ProjectSerializer
from posthog.api.shared import TeamPublicSerializer
from posthog.api.team.team_serializer import TeamSerializer
from posthog.api.user import UserSerializer
- from posthog.models.file_system.user_product_list import UserProductList
from posthog.models.user_home_settings import UserHomeSettings
from posthog.user_permissions import UserPermissions
from posthog.views import preflight_check
@@ -618,7 +616,6 @@ def _build_template_context(
"current_team": None,
"preflight": preflight_payload,
"default_event_name": "$pageview",
- "custom_products": [],
"switched_team": getattr(request, "switched_team", None),
"suggested_users_with_access": getattr(request, "suggested_users_with_access", None),
"project_access_denied": getattr(request, "project_access_denied", None),
@@ -698,15 +695,6 @@ def _build_template_context(
posthog_app_context["has_screen"] = event_info["has_screen"]
posthog_app_context["has_person_email"] = get_has_person_email(user.team)
- with tracer.start_as_current_span("template.user_product_list"):
- user_product_list = UserProductListSerializer(
- UserProductList.objects.filter(team=user.team, user=user, enabled=True).order_by(
- Lower("product_path")
- ),
- many=True,
- )
- posthog_app_context["custom_products"] = user_product_list.data
-
with tracer.start_as_current_span("template.user_home_settings"):
home_settings = UserHomeSettings.objects.filter(team=user.team, user=user).first()
posthog_app_context["homepage"] = (home_settings.homepage or None) if home_settings else None
diff --git a/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts
index 17f386ad8fa0..1092b359b500 100644
--- a/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts
+++ b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts
@@ -5,7 +5,6 @@ import { expectLogic } from 'kea-test-utils'
import { userLogic } from 'scenes/userLogic'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
-import { uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
import { useMocks } from '~/mocks/jest'
import { UserUIConfiguration } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -101,67 +100,49 @@ describe('sqlEditorVimLogic', () => {
expect(logic.values.vimrcEditorKey).toBeNull()
})
- it.each(['vimrc', 'sidebar-after-vim', 'sidebar-before-vim'] as const)(
- 'preserves both settings when the queued change is %s',
- async (scenario) => {
- const patches: Partial<UserType>[] = []
- let releaseFirstPatch: () => void = () => {}
- let reportFirstStarted: () => void = () => {}
- const firstStarted = new Promise<void>((resolve) => {
- reportFirstStarted = resolve
- })
- const firstPatchHeld = new Promise<void>((resolve) => {
- releaseFirstPatch = resolve
- })
- useMocks({
- patch: {
- '/api/users/@me/': async ({ request }) => {
- const body = (await request.json()) as Partial<UserType>
- patches.push(body)
- if (patches.length === 1) {
- reportFirstStarted()
- await firstPatchHeld
- }
- return [200, { ...MOCK_DEFAULT_USER, ...body }]
- },
+ it('preserves both settings when a vimrc change is queued behind a Vim mode change', async () => {
+ const patches: Partial<UserType>[] = []
+ let releaseFirstPatch: () => void = () => {}
+ let reportFirstStarted: () => void = () => {}
+ const firstStarted = new Promise<void>((resolve) => {
+ reportFirstStarted = resolve
+ })
+ const firstPatchHeld = new Promise<void>((resolve) => {
+ releaseFirstPatch = resolve
+ })
+ useMocks({
+ patch: {
+ '/api/users/@me/': async ({ request }) => {
+ const body = (await request.json()) as Partial<UserType>
+ patches.push(body)
+ if (patches.length === 1) {
+ reportFirstStarted()
+ await firstPatchHeld
+ }
+ return [200, { ...MOCK_DEFAULT_USER, ...body }]
},
- })
- setUp({ uiConfiguration: { version: 1 } })
+ },
+ })
+ setUp({ uiConfiguration: { version: 1 } })
- if (scenario === 'sidebar-before-vim') {
- uiCustomizationLogic.actions.completeStarredProductsSetup()
- } else {
- logic.actions.setVimModeEnabled(true)
- }
- await firstStarted
+ logic.actions.setVimModeEnabled(true)
+ await firstStarted
+ logic.actions.setVimrcDraft('set relativenumber')
+ logic.actions.saveVimrc()
+ const requestsBeforeRelease = patches.length
+ const optimisticConfiguration = logic.values.uiConfiguration
+ await expectLogic(userLogic, releaseFirstPatch).toFinishAllListeners()
- if (scenario === 'vimrc') {
- logic.actions.setVimrcDraft('set relativenumber')
- logic.actions.saveVimrc()
- } else if (scenario === 'sidebar-after-vim') {
- uiCustomizationLogic.actions.completeStarredProductsSetup()
- } else {
- logic.actions.setVimModeEnabled(true)
- }
- const requestsBeforeRelease = patches.length
- const optimisticConfiguration = logic.values.uiConfiguration
- await expectLogic(userLogic, releaseFirstPatch).toFinishAllListeners()
-
- const expectedConfiguration = {
- version: 1,
- ...(scenario === 'vimrc' ? {} : { sidebar: { starred_products_setup_completed: true } }),
- sql_editor: {
- vim_mode_enabled: true,
- ...(scenario === 'vimrc' ? { vimrc: 'set relativenumber' } : {}),
- },
- }
- expect(requestsBeforeRelease).toBe(1)
- expect(patches).toHaveLength(2)
- expect(optimisticConfiguration).toEqual(expectedConfiguration)
- expect(patches[1].ui_configuration).toEqual(expectedConfiguration)
- expect(logic.values.uiConfiguration).toEqual(expectedConfiguration)
+ const expectedConfiguration = {
+ version: 1,
+ sql_editor: { vim_mode_enabled: true, vimrc: 'set relativenumber' },
}
- )
+ expect(requestsBeforeRelease).toBe(1)
+ expect(patches).toHaveLength(2)
+ expect(optimisticConfiguration).toEqual(expectedConfiguration)
+ expect(patches[1].ui_configuration).toEqual(expectedConfiguration)
+ expect(logic.values.uiConfiguration).toEqual(expectedConfiguration)
+ })
it.each([200, 400])('keeps queued Vim changes when an unrelated update returns %s', async (status) => {
let releaseAccountPatch: () => void = () => {}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4e00ea47821e..1b7f96f87e26 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -76753,24 +76753,6 @@ export namespace Schemas {
results: User[];
}
- export interface UserProductList {
- readonly id: string;
- readonly product_path: string;
- enabled?: boolean;
- readonly created_at: string;
- /** @nullable */
- readonly updated_at: string | null;
- }
-
- export interface PaginatedUserProductListList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: UserProductList[];
- }
-
export interface ViewLink {
readonly id: string;
/**
@@ -87099,15 +87081,6 @@ export namespace Schemas {
custom_facets?: UserFacetSettingsEntry[];
}
- export interface PatchedUserProductList {
- readonly id?: string;
- readonly product_path?: string;
- enabled?: boolean;
- readonly created_at?: string;
- /** @nullable */
- readonly updated_at?: string | null;
- }
-
export interface PatchedViewLink {
readonly id?: string;
/**
@@ -131242,17 +131215,6 @@ export namespace Schemas {
purpose?: UploadedMediaCreateBodyPurpose;
};
- export type UserProductListListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- };
-
export type VisionAlertsListParams = {
/**
* Number of results to return per page.