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): suggest starred apps with jev (#106730)

Marius Andraedd37ff39d0f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c2e16f4815ea..c2195a9bc700 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3841,9 +3841,37 @@ snapshots:
layout-products-and-files--collapsed--light:
hash: v1.k794b7964.de50a58a262adfe7c5541fcf12dcc6733ff6126028ce8444bffb111820a90acf.ZB3fLSm9GPnhA7f33FtGRfW8_h3eC9WOzNSLd-4Kjsg
layout-products-and-files--customize-sidebar--dark:
- hash: v1.k794b7964.8431e1b7c0cf491435d1412e5fd235f10091ccc8642597c9c406f2fa670dbbcc.ofrtq-cnIF1EKpYpZ3xhxYy6BFrjNu8QIWA_O1uR8vk
+ hash: v1.k794b7964.c6a992ab4999e3a5b5b885919b7131c71311fea430ed193a44fe44786222bb7c.6HxA3KaL9Hyk6o5uc5A5cbciTR3iN5-KfaU6N6EvQYE
layout-products-and-files--customize-sidebar--light:
- hash: v1.k794b7964.5905dcae3eec5871b7d57ae73defe18195a516006f9f20b69ebfd07d80cc3bef.dw9bCthloDPwI7ifSY7GltfoobQqOjrDvxON1rfmWQc
+ hash: v1.k794b7964.10f3ab766db91ff8b14fe19b7ff9d4996afa3cf84adbdd5b601d3f54f81d0902.A0h0J3zJbZgXSzVJUGnahcVwt08CgYUD-f-6RHpiUIg
+ layout-products-and-files--customize-sidebar-dark--dark:
+ hash: v1.k794b7964.05a51b1449bb8e976dffe0d4815e63c44078c26bf70f55a7d5d0f8d7d744ca3c.RYJ_l9w5YVrQctZT2_Miya06FUSMA4lfU15dJp3yK5o
+ layout-products-and-files--customize-sidebar-dark--light:
+ hash: v1.k794b7964.b6baacc32cf10129dfba83235fa4e606a50a8110789f283de53e4d90f543ae89.HmgQJo3t0X5T0a4nIc9VjAAolixRcsR85SBYFoaMshc
+ layout-products-and-files--customize-sidebar-narrow--dark:
+ hash: v1.k794b7964.345106e6ab9a1e227b1d295779fbed8c49f75caef7b70dbdbd127d0ddbeedf8b.ozDtVp-hB4gNYYuHQZysI3HraHWHfoE5gCn8y4fVcbA
+ layout-products-and-files--customize-sidebar-narrow--light:
+ hash: v1.k794b7964.b7d41bdc7007f2c6b9f6c4c7e44f52ebb57c8e25497e6a53f9c881e976ed79eb.8QXqFUC3rpF-_h0_e5PNKYCNV3a-1-i1KgvujP6zdLI
+ layout-products-and-files--customize-sidebar-no-matches--dark:
+ hash: v1.k794b7964.b92ba9c1b54014073967b38b02055587c6a0e4a3bd97a65c5da5a81cb32693f4.ApnzD-Eims6KZ6pQP-_p_nmyOgJiy2PLLdwArjviA0k
+ layout-products-and-files--customize-sidebar-no-matches--light:
+ hash: v1.k794b7964.9d52b011230ad04a69c1814cdf838a80122a6b019f8f2fb031cc594a751ab14a.90LTu817rC_Gg8Kx0iDQ9hRo4vpZ2ng7WH3Fqi3QKcg
+ layout-products-and-files--customize-sidebar-ranked--dark:
+ hash: v1.k794b7964.05a51b1449bb8e976dffe0d4815e63c44078c26bf70f55a7d5d0f8d7d744ca3c.4xiHRDVXj0KGrjmDD4UdmnqXaPhKSRO8_hA4Qo3vOGg
+ layout-products-and-files--customize-sidebar-ranked--light:
+ hash: v1.k794b7964.253b9a8c46174185dfcc2b6fcfad634e2c6359e2f577e4ae25f241fe20b5e1fc.RouliTzTRw-dyTTxnIwNKcpxZsjwakSM4-JEvNDLLM4
+ layout-products-and-files--customize-sidebar-save-failure--dark:
+ hash: v1.k794b7964.714edb955993bbec40e254d7c7210f20b284bef85ed5f0ea210db6dc40ec10c7.g3g8MptQuJM_i3qil7CtBtvgRx-_8T9-WHq8pdylgcE
+ layout-products-and-files--customize-sidebar-save-failure--light:
+ hash: v1.k794b7964.a60b826c8a7e82a94a218411eeae93f500217a64184501c484eb45d623c162bb.o4rrr16rAbLvtRYqohjE6GJmkObcc4j4JDhDm1AztCQ
+ layout-products-and-files--customize-sidebar-unavailable--dark:
+ hash: v1.k794b7964.e56531c2cd17072fe59aee280d17b8062e1514bfa16b4785d8139126c8592d1a.kuIhADh3OqPkoXUDsfUOmwyoAcA-qzxzCVYhps_LDgQ
+ layout-products-and-files--customize-sidebar-unavailable--light:
+ hash: v1.k794b7964.d1dc188e7717e5fba1abcf4356a1cb6b1e473eeff6ab3fb5ccf548a3452d4cb6.-oNtA06PsEJgd0glBlHsQ0mDcnKxsblr2EIg7R6awuc
+ layout-products-and-files--customize-sidebar-without-ai-consent--dark:
+ hash: v1.k794b7964.8431e1b7c0cf491435d1412e5fd235f10091ccc8642597c9c406f2fa670dbbcc.zauFCQoS6Et_PEkwetyCOOsFOAYN2cI7h0QZNxnnhnM
+ layout-products-and-files--customize-sidebar-without-ai-consent--light:
+ hash: v1.k794b7964.c64fe35c2a02a388a315c2d46b48ec7c05d5c3cddf8433d4209ba9af51ef012b.veAl0R0LOhZt2nN4mA2t5PDhAvyMlifu55ceBmNWVfw
layout-products-and-files--dark--dark:
hash: v1.k794b7964.f55ca77f155ea0686bdc1e177b6cd43b81264e2148a081d839ed48e2bdfdbc5c.BCJ0-VUSm4Tj6MGofFGpJ_Ls4o8addpeUTV8Ydg0vPc
layout-products-and-files--dark--light:
diff --git a/frontend/src/layout/panel-layout/navbar/NavBar.tsx b/frontend/src/layout/panel-layout/navbar/NavBar.tsx
index a5d63464b21c..c4b1b7c1aa58 100644
--- a/frontend/src/layout/panel-layout/navbar/NavBar.tsx
+++ b/frontend/src/layout/panel-layout/navbar/NavBar.tsx
@@ -2,7 +2,7 @@ import './NavBar.scss'
import { Tabs } from '@base-ui/react/tabs'
import { cva } from 'cva'
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'
import { Suspense, useEffect, useRef } from 'react'
@@ -38,6 +38,7 @@ import { navigation3000Logic } from '../../navigation-3000/navigationLogic'
import { NavBarFooter } from './NavBarFooter'
import { PanelLayoutPanels } from './PanelLayoutPanels'
import { FlatNavBrowse } from './tabs/flat-nav/FlatNavBrowse'
+import { navProductsTabLogic } from './tabs/navProductsTabLogic'
import { NavTabBrowse } from './tabs/NavTabBrowse'
import { NavTabFiles } from './tabs/NavTabFiles'
import { NavTabProducts } from './tabs/NavTabProducts'
@@ -112,6 +113,7 @@ const TAB_CONFIG: { id: NavExperimentTab; label: string; icon: JSX.Element }[] =
]
export function NavBar(): JSX.Element {
+ useMountedLogic(navProductsTabLogic)
const containerRef = useRef<HTMLDivElement | null>(null)
const {
toggleLayoutNavCollapsed,
diff --git a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
index af8e851a7fc0..a737d268ce5e 100644
--- a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
+++ b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx
@@ -1,16 +1,21 @@
-import { MOCK_DEFAULT_BASIC_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 } from '@testing-library/dom'
+import { within, waitFor } from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
import { useActions, useMountedLogic } from 'kea'
+import { Slide, ToastContainer } from 'react-toastify'
import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { organizationLogic } from 'scenes/organizationLogic'
import { mswDecorator } from '~/mocks/browser'
import { FileSystemEntry } from '~/queries/schema/schema-general'
+import { DecideRequestApi } from 'products/ml_inference/frontend/generated/api.schemas'
+
import { NavExperimentTab, panelLayoutLogic } from '../panelLayoutLogic'
import { getDefaultTreeDataAndPeople, getDefaultTreeProducts } from '../ProjectTree/defaultTree'
import { projectTreeDataLogic } from '../ProjectTree/projectTreeDataLogic'
@@ -65,6 +70,7 @@ function SidebarStory({
empty = false,
recentsCollapsed = false,
allProductsOpen = true,
+ aiConsent = true,
folderToOpen,
}: {
tab?: NavExperimentTab
@@ -74,6 +80,7 @@ function SidebarStory({
empty?: boolean
recentsCollapsed?: boolean
allProductsOpen?: boolean
+ aiConsent?: boolean
folderToOpen?: string
}): JSX.Element {
const { setNavExperimentTab, toggleLayoutNavCollapsed, clearActivePanelIdentifier, setNavOverlayOpen } =
@@ -81,8 +88,10 @@ function SidebarStory({
const { setRecentsCollapsed } = useActions(navRecentsLogic)
const { setSearch, setAllProductsOpen } = useActions(navProductsTabLogic)
const { loadShortcutsSuccess } = useActions(projectTreeDataLogic)
+ const { loadCurrentOrganizationSuccess } = useActions(organizationLogic)
useMountedLogic(navFilesTabLogic)
useOnMountEffect(() => {
+ loadCurrentOrganizationSuccess({ ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: aiConsent })
setNavExperimentTab(tab)
toggleLayoutNavCollapsed(collapsed)
setNavOverlayOpen(overlay)
@@ -114,6 +123,7 @@ const meta: Meta<typeof SidebarStory> = {
),
FEATURE_FLAGS.PRODUCT_AUTONOMY,
FEATURE_FLAGS.SIMPLE_SIDEPANEL,
+ FEATURE_FLAGS.ML_INFERENCE_DECISIONS,
],
},
decorators: [
@@ -145,6 +155,30 @@ const meta: Meta<typeof SidebarStory> = {
'/api/environments/:team_id/file_system_shortcut/': [200, { results: starred }],
},
post: {
+ '/api/projects/:team_id/ml_inference/decisions/decide/': async ({ request }) => {
+ const { questions } = (await request.json()) as DecideRequestApi
+ return [
+ 200,
+ {
+ model: 'storybook',
+ input_tokens: 1,
+ latency_ms: 1,
+ answers: Object.fromEntries(
+ Object.entries(questions).map(([key, question]) => [
+ key,
+ {
+ type: 'noul',
+ probability: question.instructions.includes('App: Web analytics.')
+ ? 0.98
+ : question.instructions.includes('App: Product analytics.')
+ ? 0.8
+ : 0.1,
+ },
+ ])
+ ),
+ },
+ ]
+ },
'/api/projects/:team_id/file_system/home_folder/': [
200,
{ id: 'home-folder', path: 'Users/Alex Example' },
@@ -171,6 +205,115 @@ export const CustomizeSidebar: Story = {
await userEvent.click(await canvas.findByLabelText('Customize sidebar'))
},
}
+export const CustomizeSidebarWithoutAIConsent: Story = {
+ args: { aiConsent: false },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/@current/': [
+ 200,
+ { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: false },
+ ],
+ },
+ }),
+ ],
+ play: CustomizeSidebar.play,
+}
+export const CustomizeSidebarSaveFailure: Story = {
+ parameters: {
+ testOptions: {
+ waitForLoadersToDisappear: false,
+ },
+ },
+ decorators: [
+ (Story, { globals }) => (
+ <>
+ <Story />
+ <ToastContainer
+ autoClose={6000}
+ transition={Slide}
+ closeButton={<ToastCloseButton />}
+ position="bottom-right"
+ theme={globals.theme === 'dark' ? 'dark' : 'light'}
+ />
+ </>
+ ),
+ mswDecorator({
+ post: { '/api/projects/:team_id/file_system_shortcut/': [500, { detail: 'Unavailable' }] },
+ }),
+ ],
+ play: async (context) => {
+ await CustomizeSidebar.play!(context)
+ const body = within(context.canvasElement.ownerDocument.body)
+ const dialog = within(body.getByRole('dialog'))
+ await userEvent.click(dialog.getByRole('switch', { name: 'Actions' }))
+ await userEvent.click(dialog.getByText('Done', { exact: true }))
+ await body.findByText('Some changes could not be saved. Toggle those apps again to retry.')
+ },
+}
+export const CustomizeSidebarRanked: Story = {
+ play: async (context) => {
+ await CustomizeSidebar.play!(context)
+ const body = within(context.canvasElement.ownerDocument.body)
+ await userEvent.click(body.getByText('Track website visitors', { exact: true }))
+ const matches = within(await body.findByRole('region', { name: 'Matching apps' }))
+ await waitFor(() => {
+ if (matches.getAllByRole('switch')[0] !== matches.getByRole('switch', { name: 'Web analytics' })) {
+ throw new Error('Waiting for Web analytics to be the first rendered match')
+ }
+ })
+ },
+}
+export const CustomizeSidebarNoMatches: Story = {
+ decorators: [
+ mswDecorator({
+ post: {
+ '/api/projects/:team_id/ml_inference/decisions/decide/': async ({ request }) => {
+ const { questions } = (await request.json()) as DecideRequestApi
+ return [
+ 200,
+ {
+ model: 'storybook',
+ input_tokens: 1,
+ latency_ms: 1,
+ answers: Object.fromEntries(
+ Object.keys(questions).map((key) => [key, { type: 'noul', probability: 0.1 }])
+ ),
+ },
+ ]
+ },
+ },
+ }),
+ ],
+ play: async (context) => {
+ await CustomizeSidebar.play!(context)
+ const body = within(context.canvasElement.ownerDocument.body)
+ await userEvent.type(body.getByLabelText('Filter by jev'), 'Plan a hiking trip')
+ await body.findByText(
+ 'No apps meet the match threshold. Try another description or choose from the apps below.'
+ )
+ },
+}
+export const CustomizeSidebarUnavailable: Story = {
+ decorators: [
+ mswDecorator({
+ post: { '/api/projects/:team_id/ml_inference/decisions/decide/': [503, { detail: 'Unavailable' }] },
+ }),
+ ],
+ play: async (context) => {
+ await CustomizeSidebar.play!(context)
+ const body = within(context.canvasElement.ownerDocument.body)
+ await userEvent.click(body.getByText('Query databases', { exact: true }))
+ await body.findByText(
+ 'Jev could not suggest apps. Edit your description to try again, or choose from all apps below.'
+ )
+ },
+}
+export const CustomizeSidebarDark: Story = { ...CustomizeSidebarRanked, globals: { theme: 'dark' } }
+export const CustomizeSidebarNarrow: Story = {
+ ...CustomizeSidebarRanked,
+ parameters: { testOptions: { viewport: { width: 600, height: 900 } } },
+}
export const Files: Story = { args: { tab: 'files' } }
export const FilesOptions: Story = {
...Files,
@@ -191,6 +334,7 @@ export const FilesOptions: Story = {
export const OpenFolder: Story = { args: { collapsed: true, folderToOpen: 'Product research' } }
export const Chat: Story = {
args: { tab: 'chat' },
+ parameters: { mockDate: '2026-01-01T12:00:00Z' },
decorators: [
mswDecorator({
get: {
@@ -202,8 +346,8 @@ export const Chat: Story = {
title,
status: 'idle',
type: 'assistant',
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
+ created_at: '2026-01-01T11:59:00Z',
+ updated_at: '2026-01-01T11:59:00Z',
user: MOCK_DEFAULT_BASIC_USER,
})),
next: null,
@@ -212,6 +356,11 @@ export const Chat: Story = {
},
}),
],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await canvas.findByText('Review signup trends')
+ await canvas.findByText('Explore checkout events')
+ },
}
export const FilesSearch: Story = { args: { tab: 'files', search: 'Weekly' } }
export const FilesFiltered: Story = { args: { tab: 'files', search: 'type:notebook' } }
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx b/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
index 35965c64c7bc..c8e3b50c886e 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx
@@ -1,8 +1,17 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonLabel, LemonModal, LemonSwitch, Spinner } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonLabel,
+ LemonModal,
+ LemonSwitch,
+ LemonTextArea,
+ Spinner,
+} from '@posthog/lemon-ui'
import { Link } from 'lib/lemon-ui/Link'
+import { cn } from 'lib/utils/css-classes'
import { HomepageConfiguration } from '~/layout/scenes/HomepageConfiguration'
@@ -13,9 +22,20 @@ import { navProductsTabLogic } from './navProductsTabLogic'
import { productsItemName } from './productsCatalog'
export function CustomizeSidebarModal(): JSX.Element {
- const { customizeSidebarOpen, configurableProducts, starredProductIds } = useValues(navProductsTabLogic)
- const { setCustomizeSidebarOpen, setProductStarred } = useActions(navProductsTabLogic)
- const { shortcutDataHasLoaded, shortcutDataLoading } = useValues(projectTreeDataLogic)
+ const {
+ customizeSidebarOpen,
+ rankedConfigurableApps,
+ appMatchGroups,
+ selectedAppStars,
+ pendingAppStars,
+ starSaveError,
+ appRecommendationQuery,
+ appRecommendationsEnabled,
+ appRankingsLoading,
+ appRankingError,
+ } = useValues(navProductsTabLogic)
+ const { setCustomizeSidebarOpen, setProductStarred, setAppRecommendationQuery } = useActions(navProductsTabLogic)
+ const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)
return (
<LemonModal
@@ -25,79 +45,173 @@ export function CustomizeSidebarModal(): JSX.Element {
onClose={() => setCustomizeSidebarOpen(false)}
width={640}
footer={
- <div className="flex items-center gap-4 w-full">
- <p className="text-xs text-secondary mb-0 flex-1">
- Tip: Drag starred items in the sidebar to rearrange them.
- </p>
- <LemonButton type="primary" onClick={() => setCustomizeSidebarOpen(false)}>
+ <div className="flex items-center gap-4 w-full flex-wrap">
+ <div className="text-xs text-secondary flex-1" role="status">
+ {Object.keys(pendingAppStars).length > 0
+ ? 'Saving changes…'
+ : 'Tip: Drag starred items in the sidebar to rearrange them.'}
+ </div>
+ <LemonButton
+ type="primary"
+ data-attr="configure-starred-done"
+ onClick={() => setCustomizeSidebarOpen(false)}
+ >
Done
</LemonButton>
</div>
}
>
- <div className="flex flex-col gap-6">
- <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>
+ <section className="flex flex-col gap-2 mb-6">
+ <div>
+ <LemonLabel>Homepage</LemonLabel>
+ <p className="text-xs text-secondary mb-0">The page that opens when you select Home.</p>
+ </div>
+ <HomepageConfiguration />
+ </section>
+ <div className="mb-2">
+ <LemonLabel>Starred</LemonLabel>
+ <p className="text-xs text-secondary mb-0">Starred products appear below Home in the sidebar.</p>
+ </div>
+ {appRecommendationsEnabled && (
+ <div className="flex flex-col gap-2 mb-4">
+ <LemonTextArea
+ value={appRecommendationQuery}
+ onChange={setAppRecommendationQuery}
+ aria-label="Filter by jev"
+ data-attr="configure-starred-jev-query"
+ placeholder="Filter by jev. Tell us what you want to use PostHog for, and we'll suggest apps to use."
+ minRows={2}
+ maxRows={8}
+ maxLength={2000}
+ />
+ <div className="flex flex-wrap items-center gap-1">
+ <span className="text-xs text-secondary mr-1">For example</span>
+ {['Track website visitors', 'Query databases', 'Debug errors', 'Run A/B tests'].map(
+ (example) => (
+ <LemonButton
+ key={example}
+ size="xsmall"
+ type="secondary"
+ data-attr="configure-starred-jev-example"
+ loading={appRankingsLoading && appRecommendationQuery === example}
+ onClick={() => setAppRecommendationQuery(example)}
+ >
+ {example}
+ </LemonButton>
+ )
+ )}
</div>
- <HomepageConfiguration />
- </section>
- <section className="flex flex-col gap-2 group/colorful-product-icons colorful-product-icons-true">
- <div>
- <LemonLabel>Starred</LemonLabel>
- <p className="text-xs text-secondary mb-0">
- Starred products appear below Home in the sidebar.
- </p>
+ <div className="text-xs text-secondary flex items-center gap-2" role="status">
+ {appRankingsLoading && appRecommendationQuery.trim() ? (
+ <>
+ <Spinner className="text-sm" />
+ <span>Finding apps for you…</span>
+ </>
+ ) : (
+ <span>All apps stay in the list. Suggestions appear first.</span>
+ )}
+ {appRecommendationQuery && (
+ <LemonButton
+ size="xsmall"
+ data-attr="configure-starred-jev-clear"
+ onClick={() => setAppRecommendationQuery('')}
+ >
+ Clear
+ </LemonButton>
+ )}
</div>
- {!shortcutDataHasLoaded ? (
- <Spinner />
- ) : (
- configurableProducts.map((item) => {
- const { description, docsHref } = sidebarProductMeta(item)
- const label = productsItemName(item)
- return (
- <LemonSwitch
- key={item.path}
- className="py-2"
- checked={!!starredProductIds[item.path]}
- onChange={(starred) => setProductStarred(item.path, starred)}
- loading={shortcutDataLoading}
- aria-label={label}
- bordered
- fullWidth
- label={
- <span className="flex items-center gap-2">
- <span className="text-lg shrink-0 flex items-center">
- {iconForType(item.iconType, item.iconColor)}
- </span>
- <span className="flex flex-col">
+ {appRankingError && <LemonBanner type="warning">{appRankingError}</LemonBanner>}
+ </div>
+ )}
+ {starSaveError && (
+ <LemonBanner type="error" className="mb-3">
+ {starSaveError}
+ </LemonBanner>
+ )}
+ <div className="flex flex-col gap-2 group/colorful-product-icons colorful-product-icons-true">
+ {!shortcutDataHasLoaded ? (
+ <Spinner />
+ ) : (
+ [
+ { matching: true, items: appMatchGroups?.matching ?? rankedConfigurableApps },
+ { matching: false, items: appMatchGroups?.other ?? [] },
+ ]
+ .filter((group) => group.matching || group.items.length > 0)
+ .map((group) => (
+ <section
+ key={String(group.matching)}
+ aria-label={
+ appMatchGroups ? (group.matching ? 'Matching apps' : 'Other apps') : 'All apps'
+ }
+ className={cn('flex flex-col gap-2', !group.matching && 'mt-8 border-t pt-4')}
+ >
+ {appMatchGroups &&
+ (group.matching ? (
+ <h3 className="text-sm font-semibold mb-0">Matching apps</h3>
+ ) : (
+ <div>
+ <h3 className="text-sm font-semibold mb-1">Other apps</h3>
+ <p className="text-xs text-secondary mb-2">
+ These apps are below the match threshold. You can still star them.
+ </p>
+ </div>
+ ))}
+ {appMatchGroups && group.matching && group.items.length === 0 && (
+ <p className="text-sm text-secondary mb-0">
+ No apps meet the match threshold. Try another description or choose from the
+ apps below.
+ </p>
+ )}
+ {group.items.map((item) => {
+ const { description, docsHref } = sidebarProductMeta(item)
+ const label = productsItemName(item)
+ return (
+ <LemonSwitch
+ key={item.path}
+ className={cn(
+ 'py-2',
+ !group.matching &&
+ 'opacity-60 hover:opacity-100 focus-within:opacity-100'
+ )}
+ checked={!!selectedAppStars[item.path]}
+ onChange={(starred) => setProductStarred(item.path, starred)}
+ data-attr="configure-starred-app-toggle"
+ aria-label={label}
+ bordered
+ fullWidth
+ label={
<span className="flex items-center gap-2">
- {label}
- {docsHref && (
- <Link
- to={docsHref}
- target="_blank"
- className="text-xs font-normal"
- onClick={(event) => event.stopPropagation()}
- >
- Docs
- </Link>
- )}
- </span>
- {description && (
- <span className="text-xs font-normal text-secondary">
- {description}
+ <span className="text-lg shrink-0 flex items-center">
+ {iconForType(item.iconType, item.iconColor)}
</span>
- )}
- </span>
- </span>
- }
- />
- )
- })
- )}
- </section>
+ <span className="flex flex-col">
+ <span className="flex items-center gap-2">
+ {label}
+ {docsHref && (
+ <Link
+ to={docsHref}
+ target="_blank"
+ className="text-xs font-normal"
+ onClick={(event) => event.stopPropagation()}
+ >
+ Docs
+ </Link>
+ )}
+ </span>
+ {description && (
+ <span className="text-xs font-normal text-secondary">
+ {description}
+ </span>
+ )}
+ </span>
+ </span>
+ }
+ />
+ )
+ })}
+ </section>
+ ))
+ )}
</div>
</LemonModal>
)
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavProductTooltip.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavProductTooltip.tsx
index 06656a39d55e..33741a682df8 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/NavProductTooltip.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavProductTooltip.tsx
@@ -3,100 +3,18 @@ import { FileSystemImport } from '~/queries/schema/schema-general'
import { sidebarProductMeta } from '../../sidebarProductMeta'
import { productsItemName } from './productsCatalog'
-const examples: Record<string, string> = {
- Home: 'Return to a dashboard you were investigating yesterday.',
- Activity: 'Check which properties arrive with a signup event.',
- 'SQL editor': 'Join signup events with billing data to compare activation by plan.',
- 'Product analytics': 'Find the step where new users drop out of onboarding.',
- Dashboards: 'Keep activation, retention, and revenue on a weekly team dashboard.',
- 'Session replay': 'Watch a failed checkout to see what got in the way.',
- 'Feature flags': 'Try a new navigation with your team before rolling it out to everyone.',
- Experiments: 'Test whether a shorter signup flow improves activation.',
- 'Web analytics': 'Find which referral sources bring visitors who sign up.',
- 'Error tracking': 'Investigate an exception that appeared after a release.',
- Surveys: 'Ask people who abandon a flow what they were trying to do.',
- Heatmaps: 'Check whether visitors reach your pricing call to action.',
- Notebooks: 'Share a funnel drop-off alongside recordings that explain it.',
- 'LLM analytics': 'Find the model calls making an assistant slow or expensive.',
- Persons: 'Review a user’s recent events while investigating a support question.',
- Cohorts: 'Compare people who tried a feature with those who have not.',
- 'AI gateway': 'Compare model usage across projects through a shared API.',
- Apps: 'Build an internal Python dashboard using your project data.',
- Broadcasts: 'Send an announcement to a cohort of beta testers.',
- 'Business knowledge': 'Give your AI assistant context about how your business works.',
- Clusters: 'Discover common themes in conversations with your AI assistant.',
- 'Code review': 'Review automated findings on a pull request before it merges.',
- 'Customer analytics': 'Explore activity across the accounts that use your product.',
- 'Data catalog': 'Find the agreed definition of a metric before using it.',
- 'Data warehouse': 'Manage the shared data your team uses for analysis.',
- Datasets: 'Keep representative prompts and expected answers for testing.',
- 'Early access features': 'Let interested users opt into a public beta.',
- Endpoints: 'Serve a saved query to your application and track its usage.',
- 'Engineering analytics': 'Find workflows that slow down pull requests.',
- Evaluations: 'Check whether AI responses meet your quality criteria.',
- 'Identity matching': 'Review how identities connect across your data.',
- Inbox: 'Review a report about friction discovered in user sessions.',
- Links: 'Create a trackable link for a new campaign.',
- 'Live Debugger': 'Inspect the state of running code when a breakpoint fires.',
- Logs: 'Search application logs around the time an error occurred.',
- 'MCP analytics': 'See which tools AI users call and what they are trying to achieve.',
- 'MCP servers': 'Find a server that gives your agent the tools it needs.',
- 'Marketing analytics': 'Compare campaign performance alongside your product data.',
- Metrics: 'Investigate a change in application performance over time.',
- Playground: 'Try a revised prompt before using it in your application.',
- 'Product tours': 'Guide new users through their first useful action.',
- Prompts: 'Keep track of changes to the prompts your application uses.',
- Pulse: 'Follow what is happening across your project.',
- 'Replay vision': 'Explore patterns found in session recordings.',
- Skills: 'Share reusable instructions with the agents your team uses.',
- Support: 'Investigate and respond to a customer’s support request.',
- Taggers: 'Label AI generations so you can compare different kinds of requests.',
- Tasks: 'Ask an agent to investigate an issue and prepare a code change.',
- Toolbar: 'Inspect elements on your website while setting up tracking.',
- Tracing: 'Follow a slow request across services to find the bottleneck.',
- 'User research': 'Run a voice research campaign about a recent product experience.',
- 'Visual review': 'Review visual changes before they reach users.',
- 'Web scripts': 'Add a website tag without changing your application code.',
- Wizard: 'Review the code changes an agent prepares to set up PostHog.',
- Workflows: 'Send a follow-up when someone completes an onboarding step.',
- Actions: 'Combine related clicks into a single event for analysis.',
- Annotations: 'Mark a release date to help explain a change in a chart.',
- 'Core events': 'Define the events that represent meaningful product usage.',
- Destinations: 'Send captured events to another tool your team uses.',
- 'Event definitions': 'Check what an event means before adding it to an insight.',
- 'Event ingestion filtering': 'Filter unwanted events before they enter your project.',
- 'Managed migrations': 'Bring historical events into PostHog.',
- 'Managed viewsets': 'Set up a collection of warehouse views for analysis.',
- Models: 'Save a reusable query as a view for other analyses.',
- 'Property definitions': 'Check the meaning and format of an event property.',
- 'Property groups': 'Organize related properties so they are easier to find.',
- 'Revenue definitions': 'Choose the events and properties that represent revenue.',
- 'SQL variables': 'Reuse the same date boundary across several queries.',
- Sources: 'Connect billing or support data to your product analytics.',
- Transformations: 'Clean or reshape incoming data before you analyze it.',
- 'Warehouse destinations': 'Choose where a warehouse source sends its synced rows.',
- 'Warehouse properties': 'Add account attributes from a warehouse table to your groups.',
-}
-
export function NavProductTooltip({ item }: { item: FileSystemImport }): JSX.Element {
- const { description } = sidebarProductMeta(item)
- const example = examples[item.path]
- const isGroup = item.iconType === 'group' || item.iconType?.startsWith('group_') || item.type?.startsWith('group_')
+ const { description, example } = sidebarProductMeta(item)
return (
<div className="w-72 max-w-full p-1 text-left whitespace-normal">
<div className="text-sm font-semibold mb-2">{productsItemName(item)}</div>
<div className="text-xs leading-relaxed">
- {description ??
- (isGroup
- ? 'Explore the organizations, accounts, or other groups behind your events. Understand usage at the group level.'
- : `Explore ${productsItemName(item).toLowerCase()} in your project.`)}
+ {description ?? `Explore ${productsItemName(item).toLowerCase()} in your project.`}
</div>
- {(example || isGroup) && (
+ {example && (
<div className="mt-3 border-t border-current/20 pt-2">
<div className="text-xs font-semibold mb-1">For example</div>
- <div className="text-xs leading-relaxed text-secondary">
- {example ?? 'Compare activity across customer accounts.'}
- </div>
+ <div className="text-xs leading-relaxed text-secondary">{example}</div>
</div>
)}
</div>
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/appRanking.ts b/frontend/src/layout/panel-layout/navbar/tabs/appRanking.ts
new file mode 100644
index 000000000000..58a0cc92a4e0
--- /dev/null
+++ b/frontend/src/layout/panel-layout/navbar/tabs/appRanking.ts
@@ -0,0 +1,42 @@
+import { FileSystemImport } from '~/queries/schema/schema-general'
+
+import { DecideRequestApiQuestions, DecideResponseApi } from 'products/ml_inference/frontend/generated/api.schemas'
+
+import { sidebarProductMeta } from '../../sidebarProductMeta'
+import { productsItemName } from './productsCatalog'
+
+export const APP_MATCH_THRESHOLD = 0.5
+
+export interface AppMatchGroups {
+ matching: FileSystemImport[]
+ other: FileSystemImport[]
+}
+
+export function buildAppRankingQuestions(items: FileSystemImport[]): DecideRequestApiQuestions[] {
+ const batches: DecideRequestApiQuestions[] = []
+ for (let offset = 0; offset < items.length; offset += 32) {
+ batches.push(
+ Object.fromEntries(
+ items.slice(offset, offset + 32).map((item, index) => [
+ `app_${offset + index}`,
+ {
+ type: 'noul',
+ instructions: `Would this PostHog app help with the user's goal? Interpret partial words and unfinished descriptions as intent. App: ${productsItemName(item)}. Category: ${item.category ?? ''}. ${sidebarProductMeta(item).description ?? ''} Example: ${sidebarProductMeta(item).example ?? ''}`,
+ },
+ ])
+ )
+ )
+ }
+ return batches
+}
+
+export function readAppRankings(result: DecideResponseApi, items: FileSystemImport[]): Record<string, number> {
+ const scores: Record<string, number> = {}
+ for (const [index, item] of items.entries()) {
+ const answer = result.answers[`app_${index}`]
+ if (answer?.type === 'noul' && typeof answer.probability === 'number' && Number.isFinite(answer.probability)) {
+ scores[item.path] = Math.max(0, Math.min(1, answer.probability))
+ }
+ }
+ return scores
+}
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 cbf6049d53a9..d0d1270505c7 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts
@@ -1,7 +1,15 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
@@ -9,6 +17,8 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ActivityTab } from '~/types'
+import { DecideRequestApi } from 'products/ml_inference/frontend/generated/api.schemas'
+
import { getDefaultTreeData, getDefaultTreeProducts } from '../../ProjectTree/defaultTree'
import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'
@@ -136,8 +146,8 @@ describe('navProductsTabLogic', () => {
const create = jest.fn(() => [201, app])
const remove = jest.fn(() => [204])
useMocks({
- post: { '/api/environments/:team_id/file_system_shortcut/': create },
- delete: { '/api/environments/:team_id/file_system_shortcut/app-star/': remove },
+ post: { '/api/projects/:team_id/file_system_shortcut/': create },
+ delete: { '/api/projects/:team_id/file_system_shortcut/app-star/': remove },
})
await expectLogic(projectTreeDataLogic).toFinishAllListeners()
const existing = [
@@ -153,41 +163,78 @@ describe('navProductsTabLogic', () => {
await expectLogic(navProductsTabLogic, () => {
navProductsTabLogic.actions.setProductStarred('Feature flags', true)
navProductsTabLogic.actions.setProductStarred('Feature flags', true)
- }).toDispatchActions([projectTreeDataLogic.actionTypes.addShortcutItemSuccess])
+ }).toDispatchActions([navProductsTabLogic.actionTypes.saveAppStarsSuccess])
expect(create).toHaveBeenCalledTimes(1)
expect(projectTreeDataLogic.values.shortcutData).toEqual([...existing, app])
expect(navProductsTabLogic.values.starredProductIds['Feature flags']).toBe('app-star')
+ expect(navProductsTabLogic.values.starSaveError).toBeNull()
+ expect(posthog.capture).toHaveBeenCalledWith('navbar starred item added', {
+ item_type: 'feature_flag',
+ item_name: 'Feature flags',
+ })
await expectLogic(navProductsTabLogic, () => {
navProductsTabLogic.actions.setProductStarred('Feature flags', false)
navProductsTabLogic.actions.setProductStarred('Feature flags', false)
- }).toDispatchActions([projectTreeDataLogic.actionTypes.deleteShortcutSuccess])
+ }).toDispatchActions([navProductsTabLogic.actionTypes.saveAppStarsSuccess])
expect(remove).toHaveBeenCalledTimes(1)
expect(projectTreeDataLogic.values.shortcutData).toEqual(existing)
+ expect(navProductsTabLogic.values.starSaveError).toBeNull()
+ expect(posthog.capture).toHaveBeenCalledWith('navbar starred item removed', {
+ item_type: 'feature_flag',
+ item_name: 'Feature flags',
+ })
})
- it('keeps a star after a failed removal and allows a retry', async () => {
- const remove = jest
- .fn()
- .mockReturnValueOnce([500, { detail: 'Try again' }])
- .mockReturnValueOnce([204])
- useMocks({ delete: { '/api/environments/:team_id/file_system_shortcut/app-star/': remove } })
- await expectLogic(projectTreeDataLogic).toFinishAllListeners()
- projectTreeDataLogic.actions.loadShortcutsSuccess([
- { id: 'app-star', path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' },
- ])
+ it.each(['before', 'after'])(
+ 'reports a failed removal when the modal closes %s the failure and allows a retry',
+ async (closed) => {
+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('save-error')
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)
+ const remove = jest
+ .fn()
+ .mockReturnValueOnce([500, { detail: 'Try again' }])
+ .mockReturnValueOnce([204])
+ useMocks({ delete: { '/api/projects/:team_id/file_system_shortcut/app-star/': remove } })
+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()
+ projectTreeDataLogic.actions.loadShortcutsSuccess([
+ { id: 'app-star', path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' },
+ ])
- await expectLogic(navProductsTabLogic, () =>
- navProductsTabLogic.actions.setProductStarred('Feature flags', false)
- )
- .toDispatchActions([projectTreeDataLogic.actionTypes.deleteShortcutFailure])
- .toMatchValues({ starredProductIds: { 'Feature flags': 'app-star' }, shortcutDataLoading: false })
- await expectLogic(navProductsTabLogic, () =>
- navProductsTabLogic.actions.setProductStarred('Feature flags', false)
- )
- .toDispatchActions([projectTreeDataLogic.actionTypes.deleteShortcutSuccess])
- .toMatchValues({ starredProductIds: {}, shortcutDataLoading: false })
- })
+ await expectLogic(navProductsTabLogic, () => {
+ navProductsTabLogic.actions.setProductStarred('Feature flags', false)
+ if (closed === 'before') {
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(false)
+ }
+ })
+ .toDispatchActions([navProductsTabLogic.actionTypes.saveAppStarsSuccess])
+ .toMatchValues({
+ starredProductIds: { 'Feature flags': 'app-star' },
+ starSaveResultLoading: false,
+ starSaveError: expect.any(String),
+ })
+ if (closed === 'after') {
+ expect(errorToast).not.toHaveBeenCalled()
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(false)
+ }
+ expect(errorToast).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ toastId: 'configure-starred-save-error',
+ autoClose: false,
+ button: { label: 'Customize sidebar', action: expect.any(Function) },
+ })
+ )
+ errorToast.mock.calls[0][1]?.button?.action()
+ expect(navProductsTabLogic.values.customizeSidebarOpen).toBe(true)
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setProductStarred('Feature flags', false)
+ )
+ .toDispatchActions([navProductsTabLogic.actionTypes.saveAppStarsSuccess])
+ .toMatchValues({ starredProductIds: {}, starSaveResultLoading: false, starSaveError: null })
+ errorToast.mockRestore()
+ }
+ )
it.each([
['products', ['Product analytics']],
['files', ['Overview', 'Research']],
@@ -206,4 +253,250 @@ describe('navProductsTabLogic', () => {
shortcutScope === 'files' ? [] : ['Product analytics']
)
})
+ it('keeps edits responsive while saving, preserves the latest intent, and finishes after the modal closes', async () => {
+ let releaseCreate!: () => void
+ const held = new Promise<void>((resolve) => {
+ releaseCreate = resolve
+ })
+ const create = jest.fn(async () => {
+ await held
+ return [201, { id: 'new-star', path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' }]
+ })
+ const remove = jest.fn(() => [204])
+ useMocks({
+ post: { '/api/projects/:team_id/file_system_shortcut/': create },
+ delete: { '/api/projects/:team_id/file_system_shortcut/:id/': remove },
+ })
+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()
+ projectTreeDataLogic.actions.loadShortcutsSuccess([
+ { id: 'analytics', path: 'Product analytics', type: 'product_analytics', href: '/insights' },
+ ])
+ navProductsTabLogic.actions.setProductStarred('Feature flags', true)
+ await expectLogic(navProductsTabLogic).toDispatchActions(['saveAppStars'])
+ expect(navProductsTabLogic.values.selectedAppStars['Feature flags']).toBe(true)
+ navProductsTabLogic.actions.setProductStarred('Product analytics', false)
+ navProductsTabLogic.actions.setProductStarred('Feature flags', false)
+ expect(navProductsTabLogic.values.selectedAppStars).toMatchObject({
+ 'Feature flags': false,
+ 'Product analytics': false,
+ })
+ navProductsTabLogic.actions.setCustomizeSidebarOpen(false)
+ releaseCreate()
+ await expectLogic(navProductsTabLogic).toDispatchActions(['saveAppStarsSuccess'])
+ expect(create).toHaveBeenCalledTimes(1)
+ expect(remove).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([201, 500])(
+ 'isolates queued saves when the project changes during a request returning %s',
+ async (status) => {
+ let release!: () => void
+ const held = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const oldTeamId = teamLogic.values.currentTeamId!
+ const newTeamId = oldTeamId + 1
+ const create = jest.fn(async ({ request }) => {
+ const oldProject = new URL(request.url).pathname.includes(`/projects/${oldTeamId}/`)
+ if (oldProject) {
+ await held
+ }
+ return [
+ oldProject ? status : 201,
+ {
+ id: oldProject ? 'old-project-star' : 'new-project-star',
+ path: 'Feature flags',
+ type: 'feature_flag',
+ href: '/feature_flags',
+ },
+ ]
+ })
+ const remove = jest.fn(() => [204])
+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('project-change')
+ useMocks({
+ post: { '/api/projects/:team_id/file_system_shortcut/': create },
+ delete: { '/api/projects/:team_id/file_system_shortcut/:id/': remove },
+ })
+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()
+ projectTreeDataLogic.actions.loadShortcutsSuccess([
+ { id: 'old-analytics', path: 'Product analytics', type: 'product_analytics', href: '/insights' },
+ ])
+ navProductsTabLogic.actions.setProductStarred('Feature flags', true)
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1))
+ navProductsTabLogic.actions.setProductStarred('Product analytics', false)
+ teamLogic.actions.loadCurrentTeamSuccess({ ...teamLogic.values.currentTeam!, id: newTeamId })
+ projectTreeDataLogic.actions.loadShortcutsSuccess([])
+ expect(navProductsTabLogic.values.pendingAppStars).toEqual({})
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setProductStarred('Feature flags', true)
+ ).toDispatchActions(['saveAppStarsSuccess'])
+ release()
+ await expectLogic(navProductsTabLogic).toFinishAllListeners()
+ expect(create).toHaveBeenCalledTimes(2)
+ expect(remove).not.toHaveBeenCalled()
+ expect(projectTreeDataLogic.values.shortcutData.map(({ id }) => id)).toEqual(['new-project-star'])
+ expect(navProductsTabLogic.values.starSaveError).toBeNull()
+ expect(errorToast).toHaveBeenCalledTimes(1)
+ errorToast.mockRestore()
+ }
+ )
+
+ it('splits the full ranked catalog at the threshold and clears the grouping', async () => {
+ const requests: DecideRequestApi[] = []
+ const decide = jest.fn(async ({ request }) => {
+ const body: DecideRequestApi = await request.json()
+ requests.push(body)
+ return [
+ 200,
+ {
+ model: 'test',
+ input_tokens: 1,
+ latency_ms: 1,
+ answers: Object.fromEntries(
+ Object.entries(body.questions).map(([key, question]: [string, { instructions: string }]) => [
+ key,
+ {
+ type: 'noul',
+ probability: question.instructions.includes('App: Web analytics.')
+ ? 0.99
+ : question.instructions.includes('App: SQL editor.')
+ ? 0.5
+ : question.instructions.includes('App: Feature flags.')
+ ? 0.499
+ : 0,
+ },
+ ])
+ ),
+ },
+ ]
+ })
+ useMocks({
+ post: {
+ '/api/projects/:team_id/ml_inference/decisions/decide/': decide,
+ },
+ })
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.ML_INFERENCE_DECISIONS]: true })
+ const allApps = navProductsTabLogic.values.configurableProducts
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery('Track website visitors')
+ ).toDispatchActions(['rankAppsSuccess'])
+ expect(navProductsTabLogic.values.appRankingError).toBeNull()
+ expect(navProductsTabLogic.values.rankedConfigurableApps[0].path).toBe('Web analytics')
+ expect(new Set(navProductsTabLogic.values.rankedConfigurableApps)).toEqual(new Set(allApps))
+ expect(decide.mock.calls.length).toBe(Math.ceil(allApps.length / 32))
+ const questions = requests.flatMap(({ questions }) => Object.values(questions))
+ expect(questions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ instructions: expect.stringContaining('Find which referral sources bring visitors who sign up.'),
+ }),
+ ])
+ )
+ expect(navProductsTabLogic.values.appMatchGroups?.matching.map((item) => item.path)).toEqual([
+ 'Web analytics',
+ 'SQL editor',
+ ])
+ expect(navProductsTabLogic.values.appMatchGroups?.other.map((item) => item.path)).toContain('Feature flags')
+ expect(
+ (navProductsTabLogic.values.appMatchGroups?.matching.length ?? 0) +
+ (navProductsTabLogic.values.appMatchGroups?.other.length ?? 0)
+ ).toBe(allApps.length)
+ navProductsTabLogic.actions.setAppRecommendationQuery('Debug errors')
+ expect(navProductsTabLogic.values.appRankings).toBeNull()
+ expect(navProductsTabLogic.values.appMatchGroups).toBeNull()
+ expect(navProductsTabLogic.values.rankedConfigurableApps).toEqual(allApps)
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery('')
+ ).toDispatchActions(['rankAppsSuccess'])
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery(' Track website visitors ')
+ ).toDispatchActions(['rankAppsSuccess'])
+ expect(decide.mock.calls.length).toBe(Math.ceil(allApps.length / 32))
+ expect(navProductsTabLogic.values.appMatchGroups?.matching.map((item) => item.path)).toEqual([
+ 'Web analytics',
+ 'SQL editor',
+ ])
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: false,
+ })
+ expect(navProductsTabLogic.values.appRecommendationsEnabled).toBe(false)
+ expect(navProductsTabLogic.values.rankedConfigurableApps).toEqual(allApps)
+ expect(navProductsTabLogic.values.appMatchGroups).toBeNull()
+ navProductsTabLogic.actions.setAppRecommendationQuery('')
+ expect(navProductsTabLogic.values.rankedConfigurableApps).toEqual(allApps)
+ expect(navProductsTabLogic.values.appMatchGroups).toBeNull()
+ })
+
+ it.each(['not approved', 'not loaded', 'revoked during debounce'])(
+ 'does not send app recommendations without consent, including debug mode: %s',
+ async (consent) => {
+ const decide = jest.fn(() => [503, { detail: 'Unavailable' }])
+ useMocks({ post: { '/api/projects/:team_id/ml_inference/decisions/decide/': decide } })
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.ML_INFERENCE_DECISIONS]: true })
+ preflightLogic.actions.loadPreflightSuccess({ ...preflightLogic.values.preflight!, is_debug: true })
+ await expectLogic(navProductsTabLogic, () => {
+ if (consent === 'revoked during debounce') {
+ navProductsTabLogic.actions.setAppRecommendationQuery('Debug errors')
+ }
+ organizationLogic.actions.loadCurrentOrganizationSuccess(
+ consent === 'not loaded'
+ ? null
+ : { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: false }
+ )
+ if (consent !== 'revoked during debounce') {
+ navProductsTabLogic.actions.setAppRecommendationQuery('Debug errors')
+ }
+ }).toFinishAllListeners()
+ expect(decide).not.toHaveBeenCalled()
+ expect(navProductsTabLogic.values.appRecommendationsEnabled).toBe(false)
+ expect(navProductsTabLogic.values.appMatchGroups).toBeNull()
+ expect(navProductsTabLogic.values.rankedConfigurableApps).toEqual(
+ navProductsTabLogic.values.configurableProducts
+ )
+ }
+ )
+
+ it('leaves every app available when ranking fails and does not call Jev without enrollment', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.ML_INFERENCE_DECISIONS]: false })
+ const decide = jest.fn(() => [503, { detail: 'Unavailable' }])
+ useMocks({ post: { '/api/projects/:team_id/ml_inference/decisions/decide/': decide } })
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery('Debug errors')
+ ).toDispatchActions(['rankAppsSuccess'])
+ expect(decide).not.toHaveBeenCalled()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.ML_INFERENCE_DECISIONS]: true })
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery('Debug errors')
+ ).toDispatchActions(['rankAppsSuccess'])
+ expect(decide).toHaveBeenCalled()
+ expect(navProductsTabLogic.values.appRankingError).toEqual(expect.any(String))
+ expect(navProductsTabLogic.values.rankedConfigurableApps).toEqual(
+ navProductsTabLogic.values.configurableProducts
+ )
+ expect(navProductsTabLogic.values.appMatchGroups).toBeNull()
+ })
+
+ it('discards ranking responses after the query is cleared', async () => {
+ let release!: () => void
+ const held = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const decide = jest.fn(async () => {
+ await held
+ return [200, { model: 'test', answers: { app_0: { type: 'noul', probability: 1 } }, input_tokens: 1 }]
+ })
+ useMocks({ post: { '/api/projects/:team_id/ml_inference/decisions/decide/': decide } })
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.ML_INFERENCE_DECISIONS]: true })
+ navProductsTabLogic.actions.setAppRecommendationQuery('Watch user sessions')
+ await waitFor(() => expect(decide).toHaveBeenCalled())
+ await expectLogic(navProductsTabLogic, () =>
+ navProductsTabLogic.actions.setAppRecommendationQuery('')
+ ).toDispatchActions(['rankAppsSuccess'])
+ release()
+ await expectLogic(navProductsTabLogic).toFinishAllListeners()
+ expect(navProductsTabLogic.values.appRankings).toBeNull()
+ expect(navProductsTabLogic.values.appRankingError).toBeNull()
+ })
})
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
index ace825eadfe9..351f301d4d01 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
@@ -1,18 +1,31 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { withTimeout } from 'lib/utils/async'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { DEFINITIONS_TABS } from 'scenes/data-management/definitionsSceneTabsLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import * as coreApi from '~/generated/core/api'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
import { ActivityTab } from '~/types'
+import type { PreflightStatus } from '~/types'
+
+import * as decisionsApi from 'products/ml_inference/frontend/generated/api'
import { getDefaultTreeData, getDefaultTreeProducts } from '../../ProjectTree/defaultTree'
import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'
import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'
-import { findProductShortcut } from '../../ProjectTree/utils'
+import { findProductShortcut, joinPath, splitPath } from '../../ProjectTree/utils'
+import { APP_MATCH_THRESHOLD, AppMatchGroups, buildAppRankingQuestions, readAppRankings } from './appRanking'
import {
POPULAR_CATEGORY,
POPULAR_PRODUCT_PATHS,
@@ -33,30 +46,39 @@ const PINNED_CATEGORY = 'Project'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navProductsTabLogicValues {
+ dataProcessingAccepted: boolean // aiConsentLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
+ preflight: PreflightStatus | null // preflightLogic
shortcutData: FileSystemEntry[] // projectTreeDataLogic
shortcutDataHasLoaded: boolean // projectTreeDataLogic
shortcutDataLoading: boolean // projectTreeDataLogic
+ currentTeamId: number | null // teamLogic
allItems: FileSystemImport[]
allProductsCollapsible: boolean
allProductsOpen: boolean
allProductsVisible: boolean
+ appMatchGroups: AppMatchGroups | null
+ appRankingError: string | null
+ appRankings: Record<string, number> | null
+ appRankingsLoading: boolean
+ appRecommendationQuery: string
+ appRecommendationsEnabled: boolean
configurableProducts: FileSystemImport[]
customizeSidebarOpen: boolean
groupedItems: ProductsItemGroup[]
+ pendingAppStars: Record<string, boolean>
pinnedItems: FileSystemImport[]
+ rankedConfigurableApps: FileSystemImport[]
search: string
+ selectedAppStars: Record<string, boolean>
+ starSaveError: string | null
+ starSaveResult: null
+ starSaveResultLoading: boolean
starredProductIds: Record<string, string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navProductsTabLogicActions {
- addShortcutItem: (item: FileSystemEntry) => {
- item: FileSystemEntry
- } // projectTreeDataLogic
- deleteShortcut: (id: string) => {
- id: string
- } // projectTreeDataLogic
deleteShortcutSuccess: (
shortcutData: FileSystemEntry[],
payload?:
@@ -90,9 +112,75 @@ export interface navProductsTabLogicActions {
}
shortcutData: FileSystemEntry[]
} // projectTreeDataLogic
+ loadCurrentTeamSuccess: (
+ currentTeam: null | import('~/types').TeamPublicType,
+ payload?: any
+ ) => {
+ currentTeam: null | import('~/types').TeamPublicType
+ payload?: any
+ } // teamLogic
+ finishAppStar: (
+ productPath: string,
+ starred: boolean
+ ) => {
+ productPath: string
+ starred: boolean
+ }
+ queueAppStar: (
+ productPath: string,
+ starred: boolean
+ ) => {
+ productPath: string
+ starred: boolean
+ }
+ rankApps: ({ query }: { query: string }) => {
+ query: string
+ }
+ rankAppsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ rankAppsSuccess: (
+ appRankings: Record<string, number> | null,
+ payload?: {
+ query: string
+ }
+ ) => {
+ appRankings: Record<string, number> | null
+ payload?: {
+ query: string
+ }
+ }
+ resetAppConfiguration: () => {
+ value: true
+ }
+ saveAppStars: (_: void) => void
+ saveAppStarsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveAppStarsSuccess: (
+ starSaveResult: null,
+ payload?: void
+ ) => {
+ starSaveResult: null
+ payload?: void
+ }
setAllProductsOpen: (open: boolean) => {
open: boolean
}
+ setAppRankingError: (error: string | null) => {
+ error: string | null
+ }
+ setAppRecommendationQuery: (query: string) => {
+ query: string
+ }
setCustomizeSidebarOpen: (open: boolean) => {
open: boolean
}
@@ -106,11 +194,35 @@ export interface navProductsTabLogicActions {
setSearch: (search: string) => {
search: string
}
+ setStarSaveError: (error: string | null) => {
+ error: string | null
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface navProductsTabLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ appRecommendationsEnabled: (
+ featureFlags: FeatureFlagsSet,
+ preflight: PreflightStatus | null,
+ dataProcessingAccepted: boolean
+ ) => boolean
+ rankedConfigurableApps: (
+ configurableProducts: FileSystemImport[],
+ appRankings: Record<string, number> | null,
+ appRecommendationQuery: string,
+ appRecommendationsEnabled: boolean
+ ) => FileSystemImport[]
+ appMatchGroups: (
+ rankedConfigurableApps: FileSystemImport[],
+ appRankings: Record<string, number> | null,
+ appRecommendationQuery: string,
+ appRecommendationsEnabled: boolean
+ ) => AppMatchGroups | null
+ selectedAppStars: (
+ starredProductIds: Record<string, string>,
+ pendingAppStars: Record<string, boolean>
+ ) => Record<string, boolean>
allItems: (featureFlags: FeatureFlagsSet) => FileSystemImport[]
pinnedItems: (allItems: FileSystemImport[], search: string) => FileSystemImport[]
groupedItems: (allItems: FileSystemImport[], search: string) => ProductsItemGroup[]
@@ -137,32 +249,198 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
path(['layout', 'panel-layout', 'navbar', 'tabs', 'navProductsTabLogic']),
connect(() => ({
values: [
+ teamLogic,
+ ['currentTeamId'],
+ preflightLogic,
+ ['preflight'],
featureFlagLogic,
['featureFlags'],
+ aiConsentLogic,
+ ['dataProcessingAccepted'],
projectTreeDataLogic,
['shortcutData', 'shortcutDataHasLoaded', 'shortcutDataLoading'],
],
actions: [
projectTreeDataLogic,
- [
- 'addShortcutItem',
- 'deleteShortcut',
- 'deleteShortcutSuccess',
- 'loadShortcutsFailure',
- 'loadShortcutsSuccess',
- ],
+ ['deleteShortcutSuccess', 'loadShortcutsFailure', 'loadShortcutsSuccess'],
+ teamLogic,
+ ['loadCurrentTeamSuccess'],
],
logic: [projectTreeLogic({ key: PRODUCTS_STARRED_TREE_KEY, root: 'shortcuts://', shortcutScope: 'products' })],
})),
actions({
+ resetAppConfiguration: true,
setSearch: (search: string) => ({ search }),
+ setAppRecommendationQuery: (query: string) => ({ query }),
+ queueAppStar: (productPath: string, starred: boolean) => ({ productPath, starred }),
+ finishAppStar: (productPath: string, starred: boolean) => ({ productPath, starred }),
+ setStarSaveError: (error: string | null) => ({ error }),
+ setAppRankingError: (error: string | null) => ({ error }),
setCustomizeSidebarOpen: (open: boolean) => ({ open }),
setAllProductsOpen: (open: boolean) => ({ open }),
setProductStarred: (productPath: string, starred: boolean) => ({ productPath, starred }),
}),
+ loaders(({ actions, values, cache }) => ({
+ starSaveResult: [
+ null as null,
+ {
+ saveAppStars: async (_: void, breakpoint) => {
+ const teamId = values.currentTeamId
+ while (Object.keys(values.pendingAppStars).length > 0) {
+ const [productPath, starred] = Object.entries(values.pendingAppStars)[0]
+ const item = values.configurableProducts.find((app) => app.path === productPath)
+ const shortcutId = values.starredProductIds[productPath]
+ try {
+ if (!item || teamId === null) {
+ actions.setStarSaveError(
+ 'Some changes could not be saved. Toggle those apps again to retry.'
+ )
+ } else {
+ const shortcutPath = joinPath(splitPath(item.path).slice(-1))
+ if (starred && !shortcutId) {
+ const entry = await coreApi.fileSystemShortcutCreate(String(teamId), {
+ path: shortcutPath,
+ type: item.iconType || item.type,
+ href: item.href,
+ })
+ breakpoint()
+ actions.loadShortcutsSuccess([
+ ...values.shortcutData,
+ {
+ id: entry.id,
+ path: entry.path,
+ type: entry.type,
+ href: entry.href ?? undefined,
+ },
+ ])
+ posthog.capture('navbar starred item added', {
+ item_type: item.iconType || item.type || 'unknown',
+ item_name: shortcutPath,
+ })
+ } else if (!starred && shortcutId) {
+ await coreApi.fileSystemShortcutDestroy(String(teamId), shortcutId)
+ breakpoint()
+ actions.loadShortcutsSuccess(
+ values.shortcutData.filter((entry) => entry.id !== shortcutId)
+ )
+ posthog.capture('navbar starred item removed', {
+ item_type: item.iconType || item.type || 'unknown',
+ item_name: shortcutPath,
+ })
+ }
+ }
+ } catch {
+ breakpoint()
+ actions.setStarSaveError(
+ 'Some changes could not be saved. Toggle those apps again to retry.'
+ )
+ }
+ actions.finishAppStar(productPath, starred)
+ }
+ return null
+ },
+ },
+ ],
+ appRankings: [
+ null as Record<string, number> | null,
+ {
+ rankApps: async ({ query }: { query: string }, breakpoint) => {
+ cache.disposables.dispose('appRankingRequest')
+ actions.setAppRankingError(null)
+ if (!query.trim() || !values.appRecommendationsEnabled || values.currentTeamId === null) {
+ return null
+ }
+ await breakpoint(500)
+ if (!values.appRecommendationsEnabled) {
+ return null
+ }
+ const items = values.configurableProducts
+ const rankingCache: Map<string, Record<string, number>> = (cache.appRankingCache ??= new Map())
+ const cacheKey = JSON.stringify([
+ values.currentTeamId,
+ query.trim(),
+ items.map((item) => item.path),
+ ])
+ const cachedRankings = rankingCache.get(cacheKey)
+ if (cachedRankings) {
+ return cachedRankings
+ }
+ const controller = new AbortController()
+ cache.disposables.add(() => () => controller.abort(), 'appRankingRequest', {
+ pauseOnPageHidden: false,
+ })
+ try {
+ const scores = await Promise.all(
+ buildAppRankingQuestions(items).map(async (questions) => {
+ const result = await withTimeout(
+ decisionsApi.mlInferenceDecisionsDecideCreate(
+ String(values.currentTeamId),
+ {
+ state: query.trim(),
+ questions,
+ },
+ { signal: controller.signal }
+ ),
+ 10000
+ )
+ return readAppRankings(result, items)
+ })
+ )
+ breakpoint()
+ if (!values.appRecommendationsEnabled) {
+ return null
+ }
+ const rankings = Object.assign({}, ...scores)
+ rankingCache.set(cacheKey, rankings)
+ if (rankingCache.size > 10) {
+ rankingCache.delete(rankingCache.keys().next().value!)
+ }
+ return rankings
+ } catch {
+ breakpoint()
+ actions.setAppRankingError(
+ 'Jev could not suggest apps. Edit your description to try again, or choose from all apps below.'
+ )
+ return null
+ } finally {
+ controller.abort()
+ }
+ },
+ },
+ ],
+ })),
reducers({
+ appRankings: [null as Record<string, number> | null, { setAppRecommendationQuery: () => null }],
+ appRecommendationQuery: ['', { setAppRecommendationQuery: (_, { query }) => query }],
+ appRankingError: [null as string | null, { setAppRankingError: (_, { error }) => error }],
+ starSaveError: [
+ null as string | null,
+ {
+ setStarSaveError: (_, { error }) => error,
+ queueAppStar: () => null,
+ resetAppConfiguration: () => null,
+ },
+ ],
+ pendingAppStars: [
+ {} as Record<string, boolean>,
+ {
+ resetAppConfiguration: () => ({}),
+ queueAppStar: (state, { productPath, starred }) => ({ ...state, [productPath]: starred }),
+ finishAppStar: (state, { productPath, starred }) => {
+ if (state[productPath] !== starred) {
+ return state
+ }
+ const remaining = { ...state }
+ delete remaining[productPath]
+ return remaining
+ },
+ },
+ ],
search: ['', { setSearch: (_, { search }) => search }],
- customizeSidebarOpen: [false, { setCustomizeSidebarOpen: (_, { open }) => open }],
+ customizeSidebarOpen: [
+ false,
+ { setCustomizeSidebarOpen: (_, { open }) => open, resetAppConfiguration: () => false },
+ ],
// pinned: persisted under this logic's path, so renaming the reducer resets everyone's choice.
// Storybook starts open so visual snapshots cover the full list.
allProductsOpen: [
@@ -172,6 +450,49 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
],
}),
selectors({
+ appRecommendationsEnabled: [
+ (s) => [s.featureFlags, s.preflight, s.dataProcessingAccepted],
+ (
+ featureFlags: FeatureFlagsSet,
+ preflight: PreflightStatus | null,
+ dataProcessingAccepted: boolean
+ ): boolean =>
+ dataProcessingAccepted && !!(preflight?.is_debug || featureFlags[FEATURE_FLAGS.ML_INFERENCE_DECISIONS]),
+ ],
+ rankedConfigurableApps: [
+ (s) => [s.configurableProducts, s.appRankings, s.appRecommendationQuery, s.appRecommendationsEnabled],
+ (
+ items: FileSystemImport[],
+ rankings: Record<string, number> | null,
+ query: string,
+ enabled: boolean
+ ): FileSystemImport[] =>
+ enabled && query.trim() && rankings
+ ? [...items].sort((a, b) => (rankings[b.path] ?? 0) - (rankings[a.path] ?? 0))
+ : items,
+ ],
+ appMatchGroups: [
+ (s) => [s.rankedConfigurableApps, s.appRankings, s.appRecommendationQuery, s.appRecommendationsEnabled],
+ (
+ items: FileSystemImport[],
+ rankings: Record<string, number> | null,
+ query: string,
+ enabled: boolean
+ ): AppMatchGroups | null =>
+ enabled && query.trim() && rankings
+ ? {
+ matching: items.filter((item) => (rankings[item.path] ?? 0) >= APP_MATCH_THRESHOLD),
+ other: items.filter((item) => (rankings[item.path] ?? 0) < APP_MATCH_THRESHOLD),
+ }
+ : null,
+ ],
+ selectedAppStars: [
+ (s) => [s.starredProductIds, s.pendingAppStars],
+ (ids: Record<string, string>, pending: Record<string, boolean>): Record<string, boolean> => ({
+ ...Object.fromEntries(Object.keys(ids).map((path) => [path, true])),
+ ...pending,
+ }),
+ ],
allItems: [
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): FileSystemImport[] => {
@@ -275,7 +596,7 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
): boolean => allProductsOpen || !!search.trim() || (shortcutDataHasLoaded && !allProductsCollapsible),
],
}),
- listeners(({ actions, values }) => {
+ listeners(({ actions, values, cache }) => {
// A sidebar shown open because nothing was starred stays open after the first star.
const keepAllProductsOpenWithoutStars = (): void => {
if (values.shortcutDataHasLoaded && !values.allProductsCollapsible && !values.allProductsOpen) {
@@ -286,19 +607,48 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
loadShortcutsSuccess: keepAllProductsOpenWithoutStars,
loadShortcutsFailure: keepAllProductsOpenWithoutStars,
deleteShortcutSuccess: keepAllProductsOpenWithoutStars,
- setProductStarred: ({ productPath, starred }) => {
- if (values.shortcutDataLoading) {
- return
+ loadCurrentTeamSuccess: () => {
+ if (cache.appConfigurationTeamId !== values.currentTeamId) {
+ cache.appConfigurationTeamId = values.currentTeamId
+ const hadPendingChanges = Object.keys(values.pendingAppStars).length > 0
+ actions.resetAppConfiguration()
+ if (hadPendingChanges) {
+ lemonToast.error(
+ 'Your project changed before all starred apps were saved. Return to the previous project to review your starred apps.',
+ { toastId: 'configure-starred-project-changed', autoClose: false }
+ )
+ }
}
- const item = values.configurableProducts.find((product) => product.path === productPath)
- if (!item) {
+ },
+ resetAppConfiguration: () => {
+ actions.setAppRecommendationQuery('')
+ actions.saveAppStars()
+ },
+ setStarSaveError: ({ error }) => {
+ if (error && !values.customizeSidebarOpen) {
+ lemonToast.error(error, {
+ toastId: 'configure-starred-save-error',
+ autoClose: false,
+ button: { label: 'Customize sidebar', action: () => actions.setCustomizeSidebarOpen(true) },
+ })
+ }
+ },
+ setCustomizeSidebarOpen: ({ open }) => {
+ if (!open && values.starSaveError) {
+ actions.setStarSaveError(values.starSaveError)
+ }
+ },
+ setAppRecommendationQuery: ({ query }) => actions.rankApps({ query }),
+ setProductStarred: ({ productPath, starred }) => {
+ if (!values.configurableProducts.some((app) => app.path === productPath)) {
return
}
- const shortcutId = values.starredProductIds[productPath]
- if (starred && !shortcutId) {
- actions.addShortcutItem(item as FileSystemEntry)
- } else if (!starred && shortcutId) {
- actions.deleteShortcut(shortcutId)
+ actions.queueAppStar(productPath, starred)
+ },
+ queueAppStar: async (_, breakpoint) => {
+ await breakpoint(250)
+ if (!values.starSaveResultLoading) {
+ actions.saveAppStars()
}
},
setSearch: ({ search }) => {
@@ -310,4 +660,7 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([
},
}
}),
+ afterMount(({ cache, values }) => {
+ cache.appConfigurationTeamId = values.currentTeamId
+ }),
])
diff --git a/frontend/src/layout/panel-layout/sidebarProductMeta.ts b/frontend/src/layout/panel-layout/sidebarProductMeta.ts
index 0f3a31d07bf4..63e74007f0d3 100644
--- a/frontend/src/layout/panel-layout/sidebarProductMeta.ts
+++ b/frontend/src/layout/panel-layout/sidebarProductMeta.ts
@@ -80,7 +80,84 @@ export const SIDEBAR_PRODUCTS_WITHOUT_DOCS = new Set<string>([
'Wizard',
])
+const examples: Record<string, string> = {
+ Home: 'Return to a dashboard you were investigating yesterday.',
+ Activity: 'Check which properties arrive with a signup event.',
+ 'SQL editor': 'Join signup events with billing data to compare activation by plan.',
+ 'Product analytics': 'Find the step where new users drop out of onboarding.',
+ Dashboards: 'Keep activation, retention, and revenue on a weekly team dashboard.',
+ 'Session replay': 'Watch a failed checkout to see what got in the way.',
+ 'Feature flags': 'Try a new navigation with your team before rolling it out to everyone.',
+ Experiments: 'Test whether a shorter signup flow improves activation.',
+ 'Web analytics': 'Find which referral sources bring visitors who sign up.',
+ 'Error tracking': 'Investigate an exception that appeared after a release.',
+ Surveys: 'Ask people who abandon a flow what they were trying to do.',
+ Heatmaps: 'Check whether visitors reach your pricing call to action.',
+ Notebooks: 'Share a funnel drop-off alongside recordings that explain it.',
+ 'LLM analytics': 'Find the model calls making an assistant slow or expensive.',
+ Persons: 'Review a user’s recent events while investigating a support question.',
+ Cohorts: 'Compare people who tried a feature with those who have not.',
+ 'AI gateway': 'Compare model usage across projects through a shared API.',
+ Apps: 'Build an internal Python dashboard using your project data.',
+ Broadcasts: 'Send an announcement to a cohort of beta testers.',
+ 'Business knowledge': 'Give your AI assistant context about how your business works.',
+ Clusters: 'Discover common themes in conversations with your AI assistant.',
+ 'Code review': 'Review automated findings on a pull request before it merges.',
+ 'Customer analytics': 'Explore activity across the accounts that use your product.',
+ 'Data catalog': 'Find the agreed definition of a metric before using it.',
+ 'Data warehouse': 'Manage the shared data your team uses for analysis.',
+ Datasets: 'Keep representative prompts and expected answers for testing.',
+ 'Early access features': 'Let interested users opt into a public beta.',
+ Endpoints: 'Serve a saved query to your application and track its usage.',
+ 'Engineering analytics': 'Find workflows that slow down pull requests.',
+ Evaluations: 'Check whether AI responses meet your quality criteria.',
+ 'Identity matching': 'Review how identities connect across your data.',
+ Inbox: 'Review a report about friction discovered in user sessions.',
+ Links: 'Create a trackable link for a new campaign.',
+ 'Live Debugger': 'Inspect the state of running code when a breakpoint fires.',
+ Logs: 'Search application logs around the time an error occurred.',
+ 'MCP analytics': 'See which tools AI users call and what they are trying to achieve.',
+ 'MCP servers': 'Find a server that gives your agent the tools it needs.',
+ 'Marketing analytics': 'Compare campaign performance alongside your product data.',
+ Metrics: 'Investigate a change in application performance over time.',
+ Playground: 'Try a revised prompt before using it in your application.',
+ 'Product tours': 'Guide new users through their first useful action.',
+ Prompts: 'Keep track of changes to the prompts your application uses.',
+ Pulse: 'Follow what is happening across your project.',
+ 'Replay vision': 'Explore patterns found in session recordings.',
+ Skills: 'Share reusable instructions with the agents your team uses.',
+ Support: 'Investigate and respond to a customer’s support request.',
+ Taggers: 'Label AI generations so you can compare different kinds of requests.',
+ Tasks: 'Ask an agent to investigate an issue and prepare a code change.',
+ Toolbar: 'Inspect elements on your website while setting up tracking.',
+ Tracing: 'Follow a slow request across services to find the bottleneck.',
+ 'User research': 'Run a voice research campaign about a recent product experience.',
+ 'Visual review': 'Review visual changes before they reach users.',
+ 'Web scripts': 'Add a website tag without changing your application code.',
+ Wizard: 'Review the code changes an agent prepares to set up PostHog.',
+ Workflows: 'Send a follow-up when someone completes an onboarding step.',
+ Actions: 'Combine related clicks into a single event for analysis.',
+ Annotations: 'Mark a release date to help explain a change in a chart.',
+ 'Core events': 'Define the events that represent meaningful product usage.',
+ Destinations: 'Send captured events to another tool your team uses.',
+ 'Event definitions': 'Check what an event means before adding it to an insight.',
+ 'Event ingestion filtering': 'Filter unwanted events before they enter your project.',
+ 'Event ingestion warnings': 'Investigate events that were not ingested as expected.',
+ 'Managed migrations': 'Bring historical events into PostHog.',
+ 'Managed viewsets': 'Set up a collection of warehouse views for analysis.',
+ Models: 'Save a reusable query as a view for other analyses.',
+ 'Property definitions': 'Check the meaning and format of an event property.',
+ 'Property groups': 'Organize related properties so they are easier to find.',
+ 'Revenue definitions': 'Choose the events and properties that represent revenue.',
+ 'SQL variables': 'Reuse the same date boundary across several queries.',
+ Sources: 'Connect billing or support data to your product analytics.',
+ Transformations: 'Clean or reshape incoming data before you analyze it.',
+ 'Warehouse destinations': 'Choose where a warehouse source sends its synced rows.',
+ 'Warehouse properties': 'Add account attributes from a warehouse table to your groups.',
+}
+
export interface SidebarProductMeta {
+ example?: string
description?: string
docsHref?: string
}
@@ -97,6 +174,7 @@ export function sidebarProductMeta(product: FileSystemImport): SidebarProductMet
description: isGroup
? 'Explore the organizations, accounts, or other groups behind your events. Understand usage at the group level.'
: (descriptions[product.path] ?? sceneConfig?.description),
+ example: isGroup ? 'Compare activity across customer accounts.' : examples[product.path],
docsHref: sceneConfig?.docsHref,
}
}
diff --git a/products/ml_inference/backend/logic/decisions.py b/products/ml_inference/backend/logic/decisions.py
index 1c3291c30806..ef469b23e226 100644
--- a/products/ml_inference/backend/logic/decisions.py
+++ b/products/ml_inference/backend/logic/decisions.py
@@ -36,18 +36,24 @@ DEFAULT_TIMEOUT_SECONDS = 30.0
def decisions_available_here() -> bool:
- """Dark launch: local development and the US cloud only, so no flag or setting can bring it up in the EU."""
- return bool(settings.DEBUG) or (settings.CLOUD_DEPLOYMENT or "").upper() == "US"
+ """Decisions are available in local development and the supported cloud regions."""
+ return bool(settings.DEBUG) or (settings.CLOUD_DEPLOYMENT or "").upper() in {"US", "EU"}
def decisions_enabled(team_id: int) -> bool:
"""DEBUG bypasses the flag: the analytics SDK is disabled in local dev, where the surface has to be exercisable."""
if not decisions_available_here():
return False
- if settings.DEBUG:
- return True
try:
- team = Team.objects.only("uuid", "organization_id").get(id=team_id)
+ team = (
+ Team.objects.select_related("organization")
+ .only("uuid", "organization_id", "organization__is_ai_data_processing_approved")
+ .get(id=team_id)
+ )
+ if not team.organization.is_ai_data_processing_approved:
+ return False
+ if settings.DEBUG:
+ return True
return bool(
posthoganalytics.feature_enabled(
DECISIONS_FEATURE_FLAG,
diff --git a/products/ml_inference/backend/tests/test_logic.py b/products/ml_inference/backend/tests/test_logic.py
index aab8cba5bc87..d9c6eeca7e15 100644
--- a/products/ml_inference/backend/tests/test_logic.py
+++ b/products/ml_inference/backend/tests/test_logic.py
@@ -211,8 +211,7 @@ class TestDecisionsEnabled:
@pytest.mark.parametrize(
"debug,deployment,expected",
[
- (True, "EU", True),
- (False, "EU", False),
+ (False, "unsupported", False),
(False, None, False),
],
)
@@ -224,3 +223,20 @@ class TestDecisionsEnabled:
assert decisions.decisions_enabled(team_id=1) is expected
flag.assert_not_called()
+
+ @pytest.mark.parametrize("deployment", ["US", "EU"])
+ @pytest.mark.parametrize("enabled", [False, True])
+ def test_cloud_regions_require_enrollment(self, deployment: str, enabled: bool) -> None:
+ with (
+ override_settings(DEBUG=False, CLOUD_DEPLOYMENT=deployment),
+ patch("products.ml_inference.backend.logic.decisions.Team") as team_model,
+ patch(
+ "products.ml_inference.backend.logic.decisions.posthoganalytics.feature_enabled", return_value=enabled
+ ) as flag,
+ ):
+ team = team_model.objects.select_related.return_value.only.return_value.get.return_value
+ team.uuid = "test-team"
+ team.organization_id = "test-organization"
+ team.organization.is_ai_data_processing_approved = True
+ assert decisions.decisions_enabled(team_id=1) is enabled
+ flag.assert_called_once()
diff --git a/products/ml_inference/backend/tests/test_presentation.py b/products/ml_inference/backend/tests/test_presentation.py
index bdd441cacd33..b0af7a812f55 100644
--- a/products/ml_inference/backend/tests/test_presentation.py
+++ b/products/ml_inference/backend/tests/test_presentation.py
@@ -1,7 +1,7 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
@@ -95,6 +95,28 @@ class TestDecideEndpoint(APIBaseTest):
def _url(self) -> str:
return f"/api/projects/{self.team.id}/ml_inference/decisions/decide/"
+ @parameterized.expand([(False, "US"), (False, "EU"), (True, None)])
+ def test_requires_current_organization_consent_before_calling_the_model(
+ self, debug: bool, deployment: str | None
+ ) -> None:
+ with (
+ override_settings(DEBUG=debug, CLOUD_DEPLOYMENT=deployment),
+ patch("products.ml_inference.backend.logic.decisions.posthoganalytics.feature_enabled", return_value=True),
+ patch("products.ml_inference.backend.logic.decisions.decide") as decide,
+ ):
+ decide.return_value = DecisionResult(
+ model="test", answers={"urgent": NoulAnswer(probability=0.9)}, input_tokens=1
+ )
+ for consent in (None, False, True, False):
+ self.organization.is_ai_data_processing_approved = consent
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ decide.reset_mock()
+
+ response = self.client.post(self._url(), {"state": "text", "questions": QUESTIONS}, format="json")
+
+ assert response.status_code == (status.HTTP_200_OK if consent else status.HTTP_404_NOT_FOUND)
+ assert decide.call_count == int(bool(consent))
+
@patch("products.ml_inference.backend.presentation.views.api.decide")
def test_returns_typed_answers(self, decide) -> None:
decide.return_value = DecisionResult(
diff --git a/services/mcp/tests/hono/integration-harness.test.ts b/services/mcp/tests/hono/integration-harness.test.ts
new file mode 100644
index 000000000000..231cccc09136
--- /dev/null
+++ b/services/mcp/tests/hono/integration-harness.test.ts
@@ -0,0 +1,82 @@
+import { createServer } from 'node:net'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { startHonoHarness } from '../integration/harness/hono'
+
+const { warmup } = vi.hoisted(() => ({ warmup: vi.fn() }))
+
+vi.mock('ioredis', () => ({
+ default: class {
+ async connect(): Promise<void> {}
+ async flushdb(): Promise<void> {}
+ async quit(): Promise<void> {}
+ },
+}))
+
+vi.mock('@/hono/app', () => ({
+ createApp: () => ({
+ app: { fetch: () => new Response('ready') },
+ warmup,
+ }),
+}))
+
+vi.mock('../integration/harness/skill-archive', () => ({
+ startSkillArchiveServer: async () => ({ url: 'http://127.0.0.1/skills.zip', stop: async () => {} }),
+}))
+
+describe('Hono integration harness', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ vi.clearAllMocks()
+ })
+
+ it.each([false, true])(
+ 'holds its port throughout warmup and releases it on shutdown (warmup fails: %s)',
+ async (fails) => {
+ vi.stubEnv('MCP_APPS_BASE_URL', '')
+ vi.stubEnv('POSTHOG_API_BASE_URL', '')
+ vi.stubEnv('POSTHOG_MCP_SKILLS_URL', '')
+ let port = 0
+ warmup.mockImplementationOnce(async () => {
+ port = Number(new URL(process.env.MCP_APPS_BASE_URL!).port)
+ const competitor = createServer()
+ const error = await new Promise<NodeJS.ErrnoException | null>((resolve) => {
+ competitor.once('error', resolve)
+ competitor.listen(port, '127.0.0.1', () => competitor.close(() => resolve(null)))
+ })
+ expect(error?.code).toBe('EADDRINUSE')
+ if (fails) {
+ throw new Error('warmup failed')
+ }
+ })
+
+ const started = startHonoHarness({
+ apiBaseUrl: 'http://127.0.0.1:8010',
+ apiToken: 'test-token',
+ orgId: 'test-org',
+ projectId: '1',
+ })
+ if (fails) {
+ await expect(started).rejects.toThrow('warmup failed')
+ } else {
+ const harness = await started
+ try {
+ expect(harness.baseUrl.port).toBe(String(port))
+ expect(await (await fetch(harness.baseUrl)).text()).toBe('ready')
+ } finally {
+ await harness.stop()
+ }
+ }
+
+ const next = createServer()
+ try {
+ await new Promise<void>((resolve, reject) => {
+ next.once('error', reject)
+ next.listen(port, '127.0.0.1', resolve)
+ })
+ } finally {
+ await new Promise<void>((resolve) => next.close(() => resolve()))
+ }
+ }
+ )
+})
diff --git a/services/mcp/tests/integration/harness/hono.ts b/services/mcp/tests/integration/harness/hono.ts
index abab36cab156..1648f7f842bf 100644
--- a/services/mcp/tests/integration/harness/hono.ts
+++ b/services/mcp/tests/integration/harness/hono.ts
@@ -1,10 +1,11 @@
import { serve } from '@hono/node-server'
import Redis from 'ioredis'
+import { once } from 'node:events'
import type { AddressInfo } from 'node:net'
import { createApp } from '@/hono/app'
-import { startSkillArchiveServer } from './skill-archive'
+import { startSkillArchiveServer, type SkillArchiveServer } from './skill-archive'
import type { IntegrationEnv, IntegrationHarness } from './types'
// Pinned test DB so we don't collide with the dev Redis (DB 0). Must be in
@@ -39,42 +40,34 @@ async function startTestRedis(): Promise<InstanceType<typeof Redis>> {
export async function startHonoHarness(env: IntegrationEnv): Promise<IntegrationHarness> {
process.env.POSTHOG_API_BASE_URL = env.apiBaseUrl
- // Start a temporary listener on port 0 to discover a free port, then
- // set MCP_APPS_BASE_URL before creating the app so the ResourceCatalog
- // (which snapshots env at construction time) sees the correct URL.
- const probe = serve({ fetch: () => new Response(), port: 0 })
- const probePort = (probe.address() as AddressInfo).port
- await new Promise<void>((resolve) => probe.close(() => resolve()))
-
- const baseUrl = new URL(`http://127.0.0.1:${probePort}`)
+ // ResourceCatalog snapshots this URL at construction. Keep the listener
+ // bound during warmup so another process cannot claim its port.
+ let fetchHandler: Parameters<typeof serve>[0]['fetch'] = () => new Response(null, { status: 503 })
+ const server = serve({ fetch: (...args) => fetchHandler(...args), port: 0, hostname: '127.0.0.1' })
+ await once(server, 'listening')
+ const baseUrl = new URL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`)
process.env.MCP_APPS_BASE_URL = baseUrl.toString().replace(/\/$/, '')
- const redis = await startTestRedis()
-
- // The dispatcher reads this when `createApp` constructs it.
- const skillArchive = await startSkillArchiveServer().catch(async (err: unknown) => {
- await redis.quit().catch(() => undefined)
- throw err
- })
- process.env.POSTHOG_MCP_SKILLS_URL = skillArchive.url
+ let redis: Awaited<ReturnType<typeof startTestRedis>> | undefined
+ let skillArchive: SkillArchiveServer | undefined
+ const stop = async (): Promise<void> => {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await skillArchive?.stop().catch(() => undefined)
+ await redis?.quit().catch(() => undefined)
+ }
- const { app, warmup } = createApp(redis as unknown as Parameters<typeof createApp>[0])
try {
+ redis = await startTestRedis()
+ skillArchive = await startSkillArchiveServer()
+ // The dispatcher reads this when `createApp` constructs it.
+ process.env.POSTHOG_MCP_SKILLS_URL = skillArchive.url
+ const { app, warmup } = createApp(redis as unknown as Parameters<typeof createApp>[0])
await warmup()
+ fetchHandler = app.fetch
} catch (err) {
- await skillArchive.stop().catch(() => undefined)
- await redis.quit().catch(() => undefined)
+ await stop()
throw err
}
- const server = serve({ fetch: app.fetch, port: probePort })
-
- return {
- baseUrl,
- stop: async () => {
- await new Promise<void>((resolve) => server.close(() => resolve()))
- await skillArchive.stop().catch(() => undefined)
- await redis.quit().catch(() => undefined)
- },
- }
+ return { baseUrl, stop }
}