:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(navigation): move custom products to starred products (#108057)
Rafael Audibertc006603dba80
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4cfc9d9d0509..662eaa416574 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3841,37 +3841,37 @@ snapshots:layout-products-and-files--collapsed--light:hash: v1.k794b7964.de50a58a262adfe7c5541fcf12dcc6733ff6126028ce8444bffb111820a90acf.ZB3fLSm9GPnhA7f33FtGRfW8_h3eC9WOzNSLd-4Kjsglayout-products-and-files--customize-sidebar--dark:- hash: v1.k794b7964.ba386568444c8128c9dc9c89606cc07ff8296cd748c00ac4ceb13b5794bb89d6.Ewwl0IMTkp4_QZnkLgj7NwkPDAuKncordj5g9aizGTE+ hash: v1.k794b7964.0a7fd2051cc61d7492d1e0e6533540f21f0dec1ffe7a40b56867615f5fa33b94.ESj62eIkDiAZVAFAwkSxb0_x7iQYp9iEFlO-uC_EGn4layout-products-and-files--customize-sidebar--light:- hash: v1.k794b7964.2b61977cf11469207ebd96735cd81721ddbceb593b8c9472e2190af077502a7d.Aoq03isSW-qEs2jjQOzo6AxS3P2Y-b6vdchYE2Idrgw+ hash: v1.k794b7964.035593039ac454c4cc86c49e961c05f9f0e8b597a3baf743a256022408bfc940.EIOdG057OBdfa303raKP_p1ny1b5C9oYS5m4sqwrPT8layout-products-and-files--customize-sidebar-dark--dark:- hash: v1.k794b7964.bb358f73d7c9b35492ecadddf8ac9d064620fd676e4e9a76e7c43a6d6b4382d4.QbzfKM_bz-qpIxNoJ38A94-6qbswotTUavKobpZggIQ+ hash: v1.k794b7964.be428ebe12675bc1aaa840ca32819b24b862b8d1c0393fc8bf971bee10fa1899.XH5ffyXzeeSn7Op_6fCbRiXLyItl0QpiZoT4kdVbF2clayout-products-and-files--customize-sidebar-dark--light:- hash: v1.k794b7964.69f11e720076e6fcbf135fdc4f7a2509ccfd4f7f0b8d37df18b6dab0306cb8d0.NwbiEClfGRcNOU3Pe-vnfZH74M-uaXYtubyqs7V-8rs+ hash: v1.k794b7964.5e9ed202f948ebc05c82a1d6d03f3861e669e1863c44741cba9eaf14d0a297d5.8wGUeu2RWDCRXe75c9Bn8TUvVU9Be3U-z8eK_rCK7KQlayout-products-and-files--customize-sidebar-narrow--dark:- hash: v1.k794b7964.345106e6ab9a1e227b1d295779fbed8c49f75caef7b70dbdbd127d0ddbeedf8b.ozDtVp-hB4gNYYuHQZysI3HraHWHfoE5gCn8y4fVcbA+ hash: v1.k794b7964.03fdf5b2c7111b59b92d6226ebdb86ead32b5ae5ad0fa2bc7f69a5487a1ad960.EcgsPdxwzVO3JJme_oTdx18PvMEAXDpEdWLo6_fen8Ulayout-products-and-files--customize-sidebar-narrow--light:- hash: v1.k794b7964.b7d41bdc7007f2c6b9f6c4c7e44f52ebb57c8e25497e6a53f9c881e976ed79eb.8QXqFUC3rpF-_h0_e5PNKYCNV3a-1-i1KgvujP6zdLI+ hash: v1.k794b7964.df82aa5d6b7cbd7aa11ea68f1a51624ae397c4fca8ac18debe5159bb5cb0ebe7.SKqP1uJdUmbV07W0ASLB0dWSOY3Uko-l-zbyEBR_0C8layout-products-and-files--customize-sidebar-no-matches--dark:- hash: v1.k794b7964.8aa9413397031c8e63bc83eb396d43b31248edc49c7218c1c03a82b295d5f490.CSpG6vMo7pzJUD75svw9wQwFV9Sts0QSrQcj_6mWfus+ hash: v1.k794b7964.c2437aaacbcfacf40e62977d084708b8554568e63482f69d10c7080d8431ff01.DhA-sIXjnf1F_FoNE4hlN5uFrFcWhK12dk1sLrPOTLklayout-products-and-files--customize-sidebar-no-matches--light:- hash: v1.k794b7964.8efddda496d3af4770934a9e8ae9c1baf142677074568a2003d78ab35febdae1.-9JzOg0lLY6YoBFsikuKCJ2_FpgStMUFfBgNzbmE9Yw+ hash: v1.k794b7964.53942ea9a8c5c098870004d4f39d9c363bc1e840998344fe606fdb108f48df9c.PfIJndONX7dB7UKXFIFDw_xOWgJZHwvXX0NaqhoudNIlayout-products-and-files--customize-sidebar-ranked--dark:- hash: v1.k794b7964.bb358f73d7c9b35492ecadddf8ac9d064620fd676e4e9a76e7c43a6d6b4382d4.YLXyeKzb6ECjsKhPcUQSmiMaX4jOrQKJ4unhyGC9fk8+ hash: v1.k794b7964.be428ebe12675bc1aaa840ca32819b24b862b8d1c0393fc8bf971bee10fa1899.Bc3vl4Jq9Vw85SzBZlpLyiERXhBmIb075yva2QuFVL0layout-products-and-files--customize-sidebar-ranked--light:- hash: v1.k794b7964.632713b24e51987863a2482fd1d0b6e1a380cb6b64745b7f810ae5be7150f0b3.vJxMIcUse6be2QLTo3i1QCnA8zo1VRgihxo6b-V0HeQ+ hash: v1.k794b7964.99480a84fec9120166ec1eb9c71a81af3677fb991de2a14aac860bef12674878.wZtg7UkhqmBcwiOC0MphwhQDOiT7K75H60QmpUA_WxQlayout-products-and-files--customize-sidebar-save-failure--dark:- hash: v1.k794b7964.41be78b3a9c33e82adabe0eaab129b5617abd01f8fc6b1f80a216b6a0b07566b.bGBglS54yBD9RLxrnWPfwacyEOkl_fr2nWV3goY1WGQ+ hash: v1.k794b7964.8f3c0c24769c2f181b86e1707c9927ca92a867a3990186198a04e7edda693280.et6WGrpUdhTl9muz_5wwjKCKPPeHR-NFdPLNEOU5cS4layout-products-and-files--customize-sidebar-save-failure--light:- hash: v1.k794b7964.a2671c42338cceed092aad650eee3e3293b1ab9af58a8413eccff04b5e810ddb.EZAWZZwQ92xVtNtYvWqna7_em3pL7d29kxAhe4PyiMw+ hash: v1.k794b7964.cef048a34c318e0bb4b34518ce55f7230c55596d69ae19638dc34b1e4fbd17b0.Qzwwa-ft2Sqk9ORq-Qg9FmF-pa6byIEvkwLGkMQDRU8layout-products-and-files--customize-sidebar-unavailable--dark:- hash: v1.k794b7964.a8cd6bbd4b8edf50b27521ef72d5188a5e34addb80a55a1862fe311a107d5e5f.yZ1_On_Jb1ruiOYJ2Z3UivuhlipLNsKj0asRxnTA2uA+ hash: v1.k794b7964.0f3a9904f597bcfec4f8090610c4c1c81bf339c48e40f6285ea2040c325577ea.iJcdet_5JMcIe7LNCbPQGsxgM-hr4oibceAtJTdhk9Ilayout-products-and-files--customize-sidebar-unavailable--light:- hash: v1.k794b7964.5588b34f45bf004c1601cf1085df17fb8fe4b58eb294bba03ffd3d17b0e2dcf2.WoJgvcrY8L0prtgVnOFSgoseQhR18eeSZNhB9vsQORU+ hash: v1.k794b7964.23841c5af1c1f0a5904a08e36bb13def8dcd9011cc65ba07bcbebb88e0837b53.liImgckbz4V6JmAVGEtRjH3M93vXVQ4xQG8_qk_hhcQlayout-products-and-files--customize-sidebar-without-ai-consent--dark:- hash: v1.k794b7964.b8adab6cd52c6a19937f310691612554a5bce00e4bbd4440659cceacd4bac101.6f3k0BFKcfH0t6wpe92iP5IMxk2v3T6Vl20JnIwnuUo+ hash: v1.k794b7964.d71535b71e6689fc77b72bfae63fa2e670920ca47704b94ad954a2ece39e4035.g8QxlmPmwoQ4ZQTVjD5MXNOV3SJ-_3h8ucGNx_XTVewlayout-products-and-files--customize-sidebar-without-ai-consent--light:- hash: v1.k794b7964.c4432c04067b3c1db614a5d1f220c25f65086cf78669cd385698e4543eeb1262.3ZcK7EOqYHscuccbdriVqZplt7a8UK2foFr4R4GbFU8+ hash: v1.k794b7964.35e11b76019a9bac24923604e52a8ac3237bfc41ee0c110284a15a853bac8428.FeDsIbkamD4F5NTX4p-cAsqFmC2I0BWuvhFYlL9ICFwlayout-products-and-files--dark--dark:hash: v1.k794b7964.867a5800935d5afb1cdb9f19635d5f9cca718a7978dc4b0d693ed8f51e9ab05a.NXsEwnZE4rZYHkWv8-8R_5bUxmiBwjSDN_uPXs0QKAMlayout-products-and-files--dark--light:@@ -3976,6 +3976,14 @@ snapshots:hash: v1.k794b7964.3dfd174f9729cdf5cd39d4acd2be988c2fce03e802f1f4ea1cd0b199219f660f.hUZctYTqUbL3HF38oMxNAPbTLfzMXhRC4hTH6wMhUv4layout-products-and-files--search--light:hash: v1.k794b7964.8093bc6d0caedf2a56e01f9b26ed54d6eab9261ba36aa1894352f6364266d48c.ea1x2-DAGwW2Hk3GLzc2lRAP9R9TP3H1wCZJ460h2Qo+ layout-products-and-files--starred-setup--dark:+ hash: v1.k794b7964.7acf9f0e2c160d6380940d496ddd321cf337b21bfcc095e83123c6fcf410313c.Ufmg8l4-RO9yoflVafY_QSA6Z5ZLunkQEQREaTycVzI+ layout-products-and-files--starred-setup--light:+ hash: v1.k794b7964.b85cdb6c937c85cfd20014cbbb4ea480738bed06ffdb6571bb56464ba81fdd26.j11Rr3YBswFEvZZfyqH8f-kFhrAuR1Zqe6OrR16klNE+ layout-products-and-files--starred-setup-prompt--dark:+ hash: v1.k794b7964.4623b28472ddc8a2f6a4b10be77ba052b8d168bdb26b1712feb58af7656063ab.88dhrKBxD4A-7AQ6XrpFGDnpz8f4fWbSl9G7KsI3gYQ+ layout-products-and-files--starred-setup-prompt--light:+ hash: v1.k794b7964.b261547d8635ae95925e702f6cc1e8a46982b6fbb1247ca7d6890188aa261668.KOuoEVczBgnjMeI8HtO-XnkXh0lxdLzxRfVgkQB6Ruclayout-products-product-tooltip--dark--dark:hash: v1.k794b7964.52ba01b050e579d7c600df08497a2dfab2dba9cf670553e032afce3819d6d00d.PNNtTamfHv5qRTsFnRwxhlFEaIteMOgYQgAab2QRRj0layout-products-product-tooltip--dark--light:@@ -11669,17 +11677,17 @@ snapshots:scenes-app-settings-user--settings-user-backup-codes-modal-generated--light:hash: v1.k794b7964.9c51bd1bd794659c4b6fdf9a5612dbf375e08f30375778c77cd79caff47c5aa7.s_2QKaTg7Wc2fBiUbAXjD4TG43A37T9Bpbrj3XFCN_Qscenes-app-settings-user--settings-user-customization--dark:- hash: v1.k794b7964.ab59d62e60f86b23dfd690ebd3b26a2d2eaafbd5353129f9a78ab7f04794a074.QZF8sgZklhlulBKAOHiiOGEJwdVkLoVLsG03a-6p7PA+ hash: v1.k794b7964.3045408e193e8e615527308d22dc413de653dda5d6c43805e7132e9f3840f4cb.b9QA2XgUqj92RL5nj3twT9YKKhCeCzTsVLAGPdQ6-msscenes-app-settings-user--settings-user-customization--light:- hash: v1.k794b7964.51dcc716a0fd3c9f171d6f43bbbe6f9be563f0aeabc8374c00f7cd6bd053138d.C6rHQBzKgHnAhxx1XVHnbB9icLiyWu5ig1KJ-jSc9Wk+ hash: v1.k794b7964.060094abba224302a994668db661b12e8ae212196475ee499484f20f761b3d79.K4YyuPaBVOOQte4OrQrTtPBXeBhyknd6nyC6x4ztaIoscenes-app-settings-user--settings-user-danger-zone--dark:hash: v1.k794b7964.4fa6c4238b06ef1c1dd0c749ef72a6e8d12e0a8d73f233bbf6ee15afe13f4c37.gqVHsXRhQu5FMrVIQCU_1b7zyTXlYVcJQAu3h4jJcFMscenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.588b1d5390399d7d71e55ed023f0af6576e5b37c8fa491b6d6ccbf123f48732b.M6r-NkphdCHOZ7CToPy_CTgIHFn4L1QP8YO2NLs-DW8scenes-app-settings-user--settings-user-navigation--dark:- hash: v1.k794b7964.11aba9d7916374b8dd99656cb775ce5cde26d92e06fd2317d3ec2d48b7880d20.Pp4n4D2ChDbY726Rr2iTX33o-Bk6paxlJeGonZxgYfA+ hash: v1.k794b7964.8dd30d75f10b3f85822b3112314e290a388d0f4dbb6d1e9ba9a81fc28597cd48.sQAtho9f7Yt0I3JriLx4Ig_HTzp6pFZZ2foD9_3r8bYscenes-app-settings-user--settings-user-navigation--light:- hash: v1.k794b7964.b3457d6baf1d908da2872a9252dd07b779a933e25e92d7723d9638023de1cc6f.JuvVhKdHTcJvvXyeK4CiNBe9o_Rvm4WQqaX-jg1nY9M+ hash: v1.k794b7964.ee8b6cb54e1187aa157a2bbeadd7fe04d4c5f1f25324a14d99e3db29cc57b451.sQdEM5dOgggHj23fURR3CQ9CM9-EZBHbFJiKoUpfczYscenes-app-settings-user--settings-user-notifications--dark:hash: v1.k794b7964.1fc4163c567f18057b929328e07459c13277805442523070136233c17d5e633a.Tbp1Kb6RmIhrzsmp7CWml5LEnFyy9iY9-A-lTK-h76cscenes-app-settings-user--settings-user-notifications--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex a095cfcbce78..bfdf52b4e32e 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4168,6 +4168,40 @@ export interface PatchedFileSystemShortcutApi {readonly user_access_level?: string | null}+export interface FileSystemShortcutBulkItemApi {+ /** Display path of the shortcut in the sidebar. */+ path: string+ /**+ * Type of the linked item (e.g. 'folder', 'insight'), or blank.+ * @maxLength 100+ */+ type?: string+ /**+ * Reference to the linked item, scoped to its type. Null for href-only shortcuts.+ * @maxLength 4000+ * @nullable+ */+ ref?: string | null+ /**+ * Destination URL the shortcut opens. Null when the shortcut points at an item by ref.+ * @nullable+ */+ href?: string | null+}++export interface FileSystemShortcutBulkUpdateApi {+ /**+ * Shortcuts to create, appended to the end of the current order in the given sequence. An item identical to a shortcut the user already has is skipped.+ * @maxItems 500+ */+ add?: FileSystemShortcutBulkItemApi[]+ /**+ * IDs of the current user's shortcuts to delete.+ * @maxItems 500+ */+ remove_ids?: string[]+}+export interface FileSystemShortcutReorderApi {/** IDs of the current user's shortcuts in the desired display order. */ordered_ids: string[]@@ -4891,7 +4925,7 @@ export interface UserApi {passkeys_enabled_for_2fa?: boolean | null/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */hide_mcp_hints?: boolean- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. */+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */ui_configuration?: unknown/** @nullable */readonly onboarding_skipped_at: string | null@@ -5007,7 +5041,7 @@ export interface PatchedUserApi {passkeys_enabled_for_2fa?: boolean | null/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */hide_mcp_hints?: boolean- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. */+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */ui_configuration?: unknown/** @nullable */readonly onboarding_skipped_at?: string | nulldiff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 0737ef35f7f5..f738f1382b8b 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -36,6 +36,7 @@ import type {FileSystemHomeFolderApi,FileSystemListParams,FileSystemShortcutApi,+ FileSystemShortcutBulkUpdateApi,FileSystemShortcutListParams,FileSystemShortcutReorderApi,GitHubBranchesResponseApi,@@ -2047,6 +2048,26 @@ export const fileSystemShortcutDestroy = async (})}+export const getFileSystemShortcutBulkUpdateCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/file_system_shortcut/bulk_update/`+}++/**+ * Create and delete several of the current user's shortcuts in one transaction, then return the full shortcut list in display order. Any unknown ID in `remove_ids` rejects the whole request.+ */+export const fileSystemShortcutBulkUpdateCreate = async (+ projectId: string,+ fileSystemShortcutBulkUpdateApi?: FileSystemShortcutBulkUpdateApi,+ options?: RequestInit+): Promise<FileSystemShortcutApi[]> => {+ return apiMutator<FileSystemShortcutApi[]>(getFileSystemShortcutBulkUpdateCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(fileSystemShortcutBulkUpdateApi),+ })+}+export const getFileSystemShortcutReorderCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/file_system_shortcut/reorder/`}diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 5c3d062665e2..b3fd3c6d9405 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -943,6 +943,51 @@ export const FileSystemShortcutPartialUpdateBody = /* @__PURE__ */ zod.object({.describe("Display order within the user's shortcut list, ascending."),})+/**+ * Create and delete several of the current user's shortcuts in one transaction, then return the full shortcut list in display order. Any unknown ID in `remove_ids` rejects the whole request.+ */+export const fileSystemShortcutBulkUpdateCreateBodyAddItemTypeDefault = ``+export const fileSystemShortcutBulkUpdateCreateBodyAddItemTypeMax = 100++export const fileSystemShortcutBulkUpdateCreateBodyAddItemRefMax = 4000++export const fileSystemShortcutBulkUpdateCreateBodyAddMax = 500++export const fileSystemShortcutBulkUpdateCreateBodyRemoveIdsMax = 500++export const FileSystemShortcutBulkUpdateCreateBody = /* @__PURE__ */ zod.object({+ add: zod+ .array(+ zod.object({+ path: zod.string().describe('Display path of the shortcut in the sidebar.'),+ type: zod+ .string()+ .max(fileSystemShortcutBulkUpdateCreateBodyAddItemTypeMax)+ .default(fileSystemShortcutBulkUpdateCreateBodyAddItemTypeDefault)+ .describe("Type of the linked item (e.g. 'folder', 'insight'), or blank."),+ ref: zod+ .string()+ .max(fileSystemShortcutBulkUpdateCreateBodyAddItemRefMax)+ .nullish()+ .describe('Reference to the linked item, scoped to its type. Null for href-only shortcuts.'),+ href: zod+ .string()+ .nullish()+ .describe('Destination URL the shortcut opens. Null when the shortcut points at an item by ref.'),+ })+ )+ .max(fileSystemShortcutBulkUpdateCreateBodyAddMax)+ .optional()+ .describe(+ 'Shortcuts to create, appended to the end of the current order in the given sequence. An item identical to a shortcut the user already has is skipped.'+ ),+ remove_ids: zod+ .array(zod.uuid())+ .max(fileSystemShortcutBulkUpdateCreateBodyRemoveIdsMax)+ .optional()+ .describe("IDs of the current user's shortcuts to delete."),+})+/*** Set the display order of the current user's shortcuts. `ordered_ids` becomes the new top-to-bottom order; any unknown IDs are rejected.*/@@ -1324,7 +1369,7 @@ export const UsersUpdateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -1415,7 +1460,7 @@ export const UsersPartialUpdateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -1503,7 +1548,7 @@ export const UsersHedgehogConfigPartialUpdateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -1779,7 +1824,7 @@ export const UsersScenePersonalisationCreateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -1870,7 +1915,7 @@ export const UsersTwoFactorBackupCodesCreateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -1961,7 +2006,7 @@ export const UsersTwoFactorDisableCreateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -2049,7 +2094,7 @@ export const UsersTwoFactorValidateCreateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -2137,7 +2182,7 @@ export const UsersValidate2faCreateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -2225,7 +2270,7 @@ export const UsersCancelEmailChangeRequestPartialUpdateBody = /* @__PURE__ */ zo.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})@@ -2313,7 +2358,7 @@ export const UsersRequestEmailVerificationCreateBody = /* @__PURE__ */ zod.objec.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsxindex 0aab941296e3..a98e42410661 100644--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx@@ -74,6 +74,8 @@ interface ProjectTreeBaseProps {onItemClicked?: (item: TreeDataItem | undefined) => void/** Replaces the tree's own tooltip, so a caller can match the tooltips of the rows around the tree. */renderItemTooltip?: (item: TreeDataItem) => ReactNode | undefined+ /** A docs link under the item's tooltip, for callers whose rows link to a product's docs. */+ renderItemTooltipDocLink?: (item: TreeDataItem) => string | undefined/** True while this tree's nav panel is active — refocuses search on panel re-activation. */isActiveInPanel?: boolean}@@ -498,6 +500,7 @@ export function ProjectTree(props: ProjectTreeProps): JSX.Element {</ContextMenuGroup>)}}+ renderItemTooltipDocLink={props.renderItemTooltipDocLink}renderItemTooltip={(item) => {if (props.renderItemTooltip) {return props.renderItemTooltip(item)diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex 1ab6f43b92d0..45f0189c07d4 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -103,7 +103,7 @@ import {getTreeItemsNew,getTreeItemsProducts,} from '~/products'-import { FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-general'+import { FileSystemEntry, FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-general'import { FileSystemIconColor } from '~/types'const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: FileSystemIconColor }> = {@@ -624,6 +624,26 @@ export function getSidebarProduct(href: string | undefined): FileSystemImport |return sidebarProductsByHref.get(href)}+let sidebarProductHrefsByName: Map<string, string> | undefined++// Stars created by the backend carry no href, because product URLs exist only in the frontend.+export function withProductShortcutHref(entry: FileSystemEntry): FileSystemEntry {+ if (entry.href || entry.ref || entry.type === 'folder') {+ return entry+ }+ if (!sidebarProductHrefsByName) {+ sidebarProductHrefsByName = new Map()+ for (const item of [...getDefaultTreeProducts(), ...getDefaultTreeData()]) {+ const name = item.path.split('/').pop()+ if (item.href && name && !sidebarProductHrefsByName.has(name)) {+ sidebarProductHrefsByName.set(name, item.href)+ }+ }+ }+ const href = sidebarProductHrefsByName.get(entry.path)+ return href ? { ...entry, href } : entry+}+export const getDefaultTreeGames = (): FileSystemImport[] =>[...getTreeItemsGames()].sort((a, b) => a.path.localeCompare(b.path, undefined, { sensitivity: 'accent' }))diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex cfd5a1d12cb2..845cf1a8189a 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -30,6 +30,7 @@ import {getDefaultTreeNew,getDefaultTreePersons,getDefaultTreeProducts,+ withProductShortcutHref,} from '~/layout/panel-layout/ProjectTree/defaultTree'import { RecentResults, SearchResults, projectTreeLogic } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { FolderState, ProjectTreeAction } from '~/layout/panel-layout/ProjectTree/types'@@ -40,11 +41,11 @@ import {formatUrlAsName,isGroupViewShortcut,isPathUnder,- joinPath,matchesRefType,parentPath,refTypeParams,reparentPath,+ shortcutFromEntry,sortFilesAndFolders,splitPath,} from '~/layout/panel-layout/ProjectTree/utils'@@ -1047,28 +1048,14 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([SHORTCUTS_LOADER_TIMEOUT_MS,'loadShortcuts timed out')- return response.results+ return response.results.map(withProductShortcutHref)},addShortcutItem: async ({ item }) => {- const shortcutPath = joinPath([splitPath(item.path).pop() ?? 'Unnamed'])-- const shortcutItem =- item.type === 'folder'- ? {- path: shortcutPath,- type: 'folder',- ref: item.path,- }- : {- path: shortcutPath,- type: (item as FileSystemImport).iconType || item.type,- ref: item.ref,- href: item.href,- }+ const shortcutItem = shortcutFromEntry(item)const response = await api.fileSystemShortcuts.create(shortcutItem)posthog.capture('navbar starred item added', {item_type: shortcutItem.type ?? 'unknown',- item_name: shortcutPath,+ item_name: shortcutItem.path,})lemonToast.success('Added to starred')return [...values.shortcutData, response]diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx b/frontend/src/layout/panel-layout/ProjectTree/utils.tsxindex d1b007256975..9db74f7b2dce 100644--- a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.tsx@@ -481,6 +481,21 @@ export function joinPath(path: string[]): string {return path.map(escapePath).join('/')}+export interface ShortcutInput {+ path: string+ type?: string+ ref?: string+ href?: string+}++// The shortcut row that stars an entry: a folder is linked by its path, anything else by its ref or href.+export function shortcutFromEntry(item: FileSystemEntry | FileSystemImport): ShortcutInput {+ const path = joinPath([splitPath(item.path).pop() ?? 'Unnamed'])+ return item.type === 'folder'+ ? { path, type: 'folder', ref: item.path }+ : { path, type: (item as FileSystemImport).iconType || item.type, ref: item.ref, href: item.href }+}+// A product shortcut keeps the path it had when starred, so a renamed product only matches it by href.export function findProductShortcut(item: Pick<FileSystemImport, 'path' | 'href'>,diff --git a/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsx b/frontend/src/layout/panel-layout/navbar/ProductsAndFiles.stories.tsxindex a737d268ce5e..df2f7c89af53 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 } from 'lib/api.mock'+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'import type { Meta, StoryObj } from '@storybook/react'import { within, waitFor } from '@testing-library/dom'@@ -239,16 +239,18 @@ export const CustomizeSidebarSaveFailure: Story = {</>),mswDecorator({- post: { '/api/projects/:team_id/file_system_shortcut/': [500, { detail: 'Unavailable' }] },+ post: {+ '/api/projects/:team_id/file_system_shortcut/bulk_update/': [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.')+ await userEvent.click(dialog.getByText('Actions', { exact: true }))+ await userEvent.click(dialog.getByText('Save', { exact: true }))+ await body.findByText('Could not save your starred products. Try again.')},}export const CustomizeSidebarRanked: Story = {@@ -256,9 +258,9 @@ export const CustomizeSidebarRanked: Story = {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' }))+ const matches = within(await body.findByRole('region', { name: 'Suggested' }))await waitFor(() => {- if (matches.getAllByRole('switch')[0] !== matches.getByRole('switch', { name: 'Web analytics' })) {+ if (!matches.getAllByRole('button')[0]?.textContent?.includes('Web analytics')) {throw new Error('Waiting for Web analytics to be the first rendered match')}})@@ -289,9 +291,7 @@ export const CustomizeSidebarNoMatches: Story = {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.'- )+ await body.findByText('No apps meet the match threshold. Try another description or choose from the list.')},}export const CustomizeSidebarUnavailable: Story = {@@ -314,6 +314,20 @@ 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.tsxindex c8e3b50c886e..9b96840b5ea7 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/CustomizeSidebarModal.tsx@@ -1,217 +1,83 @@import { useActions, useValues } from 'kea'-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 { LemonButton, LemonLabel, LemonModal } from '@posthog/lemon-ui'import { HomepageConfiguration } from '~/layout/scenes/HomepageConfiguration'-import { iconForType } from '../../ProjectTree/defaultTree'import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'-import { sidebarProductMeta } from '../../sidebarProductMeta'import { navProductsTabLogic } from './navProductsTabLogic'-import { productsItemName } from './productsCatalog'+import { StarredProductsPicker } from './StarredProductsPicker'+import { StarredSetupIntro } from './StarredSetupIntro'export function CustomizeSidebarModal(): JSX.Element {- const {- customizeSidebarOpen,- rankedConfigurableApps,- appMatchGroups,- selectedAppStars,- pendingAppStars,- starSaveError,- appRecommendationQuery,- appRecommendationsEnabled,- appRankingsLoading,- appRankingError,- } = useValues(navProductsTabLogic)- const { setCustomizeSidebarOpen, setProductStarred, setAppRecommendationQuery } = useActions(navProductsTabLogic)+ const { customizeSidebarOpen, customizeSidebarMode, starredProductsSaving } = useValues(navProductsTabLogic)+ const { setCustomizeSidebarOpen, saveStarredProducts, confirmCleanSlate } = useActions(navProductsTabLogic)const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)+ const isStarredSetup = customizeSidebarMode === 'starred-setup'return (<LemonModal- title="Customize sidebar"- description="Changes save automatically."+ title={isStarredSetup ? 'Set up your new sidebar' : 'Customize sidebar'}isOpen={customizeSidebarOpen}onClose={() => setCustomizeSidebarOpen(false)}- width={640}+ width={720}footer={- <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 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>+ )}</div><LemonButton- type="primary"- data-attr="configure-starred-done"+ type="secondary"onClick={() => setCustomizeSidebarOpen(false)}+ disabledReason={starredProductsSaving ? 'Saving your starred products' : undefined}+ data-attr="customize-sidebar-cancel"+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={saveStarredProducts}+ loading={starredProductsSaving}+ disabledReason={!shortcutDataHasLoaded ? 'Loading your starred products' : undefined}+ data-attr={isStarredSetup ? 'starred-setup-save' : 'customize-sidebar-save'}>- Done+ Save</LemonButton></div>}>- <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>- <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>- {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 />+ <div className="flex flex-col gap-6">+ {isStarredSetup ? (+ <StarredSetupIntro />) : (- [- { 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">- <span className="text-lg shrink-0 flex items-center">- {iconForType(item.iconType, item.iconColor)}- </span>- <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>- ))+ <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>)}+ <StarredProductsPicker /></div></LemonModal>)diff --git a/frontend/src/layout/panel-layout/navbar/tabs/JevProductSuggestions.tsx b/frontend/src/layout/panel-layout/navbar/tabs/JevProductSuggestions.tsxnew file mode 100644index 000000000000..f1344eac921b--- /dev/null+++ b/frontend/src/layout/panel-layout/navbar/tabs/JevProductSuggestions.tsx@@ -0,0 +1,65 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonTextArea, Spinner } from '@posthog/lemon-ui'++import { navProductsTabLogic } from './navProductsTabLogic'++const EXAMPLE_QUERIES = ['Track website visitors', 'Query databases', 'Debug errors', 'Run A/B tests']++export function JevProductSuggestions(): JSX.Element {+ const { appRecommendationQuery, appRankingsLoading, appRankingError, appMatchGroups } =+ useValues(navProductsTabLogic)+ const { setAppRecommendationQuery } = useActions(navProductsTabLogic)++ return (+ <div className="flex flex-col gap-2">+ <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>+ {EXAMPLE_QUERIES.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>+ <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>+ </>+ ) : appMatchGroups && appMatchGroups.matching.length === 0 ? (+ <span>No apps meet the match threshold. Try another description or choose from the list.</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>+ {appRankingError && <LemonBanner type="warning">{appRankingError}</LemonBanner>}+ </div>+ )+}diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavProductIcon.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavProductIcon.tsxnew file mode 100644index 000000000000..cbf17253ea38--- /dev/null+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavProductIcon.tsx@@ -0,0 +1,16 @@+import { FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-general'++import { getCustomIcon } from '../../ProjectTree/customIconRegistry'+import { ProductIconWrapper, iconForType } from '../../ProjectTree/defaultTree'++export function NavProductIcon({ item }: { item: FileSystemImport }): JSX.Element {+ const CustomIcon = getCustomIcon(item.type, item.href)+ const iconType = item.iconType ?? (item.type as FileSystemIconType | undefined)+ return CustomIcon ? (+ <ProductIconWrapper type={iconType} colorOverride={item.iconColor}>+ <CustomIcon />+ </ProductIconWrapper>+ ) : (+ iconForType(iconType, item.iconColor)+ )+}diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavProductRow.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavProductRow.tsxindex 635e19d32696..28d1350a99bc 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavProductRow.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavProductRow.tsx@@ -13,13 +13,13 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { urls } from 'scenes/urls'-import { FileSystemEntry, FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-general'+import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'import { panelLayoutLogic } from '../../panelLayoutLogic'-import { getCustomIcon } from '../../ProjectTree/customIconRegistry'-import { ProductIconWrapper, iconForType } from '../../ProjectTree/defaultTree'import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'import { findProductShortcut } from '../../ProjectTree/utils'+import { sidebarProductMeta } from '../../sidebarProductMeta'+import { NavProductIcon } from './NavProductIcon'import { NavProductMenu } from './NavProductMenu'import { navProductsTabLogic } from './navProductsTabLogic'import { NavProductTooltip } from './NavProductTooltip'@@ -42,8 +42,6 @@ export function NavProductRow({ item, pinned = false }: { item: FileSystemImport(href === urls.projectRoot() && currentPath === urls.projectHomepage()) ||(item.path === 'Session replay' && currentPath.startsWith('/replay/'))const disabledReason = getProductAccessDisabledReason(item)- const CustomIcon = getCustomIcon(item.type, item.href)- const iconType = item.iconType ?? (item.type as FileSystemIconType | undefined)const isHome = item.path === 'Home'const hasProductMenu = ['Product analytics', 'Dashboards', 'Session replay'].includes(item.path)@@ -79,7 +77,11 @@ export function NavProductRow({ item, pinned = false }: { item: FileSystemImportreturn (<div className="group/product-row relative flex items-center gap-px min-w-0">- <Tooltip title={disabledReason || <NavProductTooltip item={item} />} placement="right">+ <Tooltip+ title={disabledReason || <NavProductTooltip item={item} />}+ docLink={disabledReason ? undefined : sidebarProductMeta(item).docsHref}+ placement="right"+ ><Linkto={disabledReason ? undefined : href}disabledReason={disabledReason}@@ -100,13 +102,7 @@ export function NavProductRow({ item, pinned = false }: { item: FileSystemImport}}><span className="size-4 shrink-0">- {CustomIcon ? (- <ProductIconWrapper type={iconType} colorOverride={item.iconColor}>- <CustomIcon />- </ProductIconWrapper>- ) : (- iconForType(iconType, item.iconColor)- )}+ <NavProductIcon item={item} /></span><span className="flex-1 truncate">{label}</span>{item.tags?.[0] && <ProductTag tag={item.tags[0]} />}diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabProducts.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavTabProducts.tsxindex 002f409bcf6d..61751769f30b 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabProducts.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabProducts.tsx@@ -9,6 +9,7 @@ import { getSidebarProduct } from '../../ProjectTree/defaultTree'import { ProjectTree } from '../../ProjectTree/ProjectTree'import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'+import { sidebarProductMeta } from '../../sidebarProductMeta'import { CustomizeSidebarModal } from './CustomizeSidebarModal'import { NavProductRow } from './NavProductRow'import { PRODUCTS_STARRED_TREE_KEY, navProductsTabLogic } from './navProductsTabLogic'@@ -16,7 +17,7 @@ import { NavProductTooltip } from './NavProductTooltip'export function NavTabProducts(): JSX.Element {const { pinnedItems, groupedItems, allProductsVisible, allProductsCollapsible } = useValues(navProductsTabLogic)- const { setAllProductsOpen } = useActions(navProductsTabLogic)+ const { setAllProductsOpen, revealAllProductsForFind } = useActions(navProductsTabLogic)// Fade only on a toggle the user makes, not on the first render after starred items load. A height// slide over the whole product list moves too far to read, so the panel opens in place.const [animatePanel, setAnimatePanel] = useState(false)@@ -60,6 +61,10 @@ export function NavTabProducts(): JSX.Element {const product = getSidebarProduct(treeItem.record?.href)return product ? <NavProductTooltip item={product} /> : undefined}}+ renderItemTooltipDocLink={(treeItem) => {+ const product = getSidebarProduct(treeItem.record?.href)+ return product ? sidebarProductMeta(product).docsHref : undefined+ }}/></div></section>@@ -67,7 +72,12 @@ export function NavTabProducts(): JSX.Element {{groupedItems.length > 0 ? (<Collapsibleopen={allProductsVisible}- onOpenChange={(open) => {+ onOpenChange={(open, eventDetails) => {+ // A find-in-page match opens the list for this visit only.+ if (open && eventDetails.event?.type === 'beforematch') {+ revealAllProductsForFind()+ return+ }setAnimatePanel(true)setAllProductsOpen(open)}}@@ -83,6 +93,7 @@ export function NavTabProducts(): JSX.Element {</Collapsible.Trigger>)}<Collapsible.Panel+ hiddenUntilFoundclassName={cn('gap-3 transition-opacity duration-150 ease-out data-[starting-style]:opacity-0 data-[ending-style]:opacity-0',!animatePanel && 'transition-none',diff --git a/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx b/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsxnew file mode 100644index 000000000000..944b5387ef6b--- /dev/null+++ b/frontend/src/layout/panel-layout/navbar/tabs/StarredProductsPicker.tsx@@ -0,0 +1,109 @@+import { useActions, useValues } from 'kea'++import { IconStar, IconStarFilled } from '@posthog/icons'+import { LemonButton, LemonInput, LemonLabel, Spinner } from '@posthog/lemon-ui'++import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'+import { sidebarProductMeta } from '../../sidebarProductMeta'+import { JevProductSuggestions } from './JevProductSuggestions'+import { NavProductIcon } from './NavProductIcon'+import { navProductsTabLogic } from './navProductsTabLogic'+import { NavProductTooltip } from './NavProductTooltip'+import { productsItemName } from './productsCatalog'++export function StarredProductsPicker(): JSX.Element {+ const {+ customizeProductGroups,+ draftStarredPaths,+ customizeSearch,+ customizeSidebarMode,+ customProducts,+ appRecommendationsEnabled,+ } = useValues(navProductsTabLogic)+ const { setDraftStarred, setCustomizeSearch, unselectAllStarred } = useActions(navProductsTabLogic)+ const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)++ return (+ <section className="@container flex flex-col gap-3 group/colorful-product-icons colorful-product-icons-true">+ <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>+ </div>+ {shortcutDataHasLoaded && (+ <div className="flex items-center gap-2">+ <span className="text-xs text-secondary">{`${draftStarredPaths.size} starred`}</span>+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={unselectAllStarred}+ disabledReason={draftStarredPaths.size === 0 ? 'Nothing is starred' : undefined}+ data-attr="customize-sidebar-unselect-all"+ >+ Unselect all+ </LemonButton>+ </div>+ )}+ </div>+ {customizeSidebarMode === 'customize' && appRecommendationsEnabled && <JevProductSuggestions />}+ <LemonInput+ type="search"+ size="small"+ placeholder="Search products"+ value={customizeSearch}+ onChange={setCustomizeSearch}+ fullWidth+ data-attr="customize-sidebar-search"+ />+ {!shortcutDataHasLoaded ? (+ <Spinner />+ ) : customizeProductGroups.length === 0 ? (+ <p className="text-xs text-secondary mb-0">No products match your search. Try a different name.</p>+ ) : (+ customizeProductGroups.map((group) => (+ <section key={group.label} aria-label={group.label} className="flex flex-col gap-1">+ <h4 className="text-xs font-semibold text-secondary mb-0">{group.label}</h4>+ <div className="grid gap-1 @md:grid-cols-2">+ {group.items.map((item) => {+ const starred = draftStarredPaths.has(item.path)+ return (+ <LemonButton+ key={item.path}+ type="tertiary"+ size="small"+ fullWidth+ active={starred}+ aria-pressed={starred}+ icon={+ <span className="size-4 flex items-center">+ <NavProductIcon item={item} />+ </span>+ }+ sideIcon={+ starred ? (+ <IconStarFilled className="text-warning" />+ ) : (+ <IconStar className="text-tertiary" />+ )+ }+ tooltip={<NavProductTooltip item={item} />}+ tooltipDocLink={sidebarProductMeta(item).docsHref}+ tooltipPlacement="top"+ onClick={() => setDraftStarred(item.path, !starred)}+ data-attr="configure-starred-app-toggle"+ >+ <span className="truncate">{productsItemName(item)}</span>+ </LemonButton>+ )+ })}+ </div>+ </section>+ ))+ )}+ </section>+ )+}diff --git a/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsx b/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsxnew file mode 100644index 000000000000..571d83ca7db9--- /dev/null+++ b/frontend/src/layout/panel-layout/navbar/tabs/StarredSetupIntro.tsx@@ -0,0 +1,51 @@+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.tsindex 9db818d0fe48..37f9e9a33b29 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.test.ts@@ -1,16 +1,16 @@-import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'import { waitFor } from '@testing-library/react'+import { router } from 'kea-router'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 { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { FileSystemEntry } from '~/queries/schema/schema-general'@@ -19,10 +19,11 @@ 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'-import { PRODUCTS_STARRED_TREE_KEY, navProductsTabLogic } from './navProductsTabLogic'+import { PRODUCTS_STARRED_TREE_KEY, SUGGESTED_GROUP_LABEL, navProductsTabLogic } from './navProductsTabLogic'import { productsItemName, groupProducts } from './productsCatalog'describe('navProductsTabLogic', () => {@@ -124,6 +125,11 @@ describe('navProductsTabLogic', () => {expect(navProductsTabLogic.values.allProductsVisible).toBe(true)navProductsTabLogic.actions.setSearch('')+ navProductsTabLogic.actions.revealAllProductsForFind()+ expect(navProductsTabLogic.values).toMatchObject({ allProductsVisible: true, allProductsOpen: false })+ router.actions.push(urls.dashboards())+ expect(navProductsTabLogic.values.allProductsVisible).toBe(false)+projectTreeDataLogic.actions.loadShortcutsSuccess([])expect(navProductsTabLogic.values).toMatchObject({ allProductsCollapsible: false, allProductsVisible: true })@@ -131,6 +137,45 @@ describe('navProductsTabLogic', () => {expect(navProductsTabLogic.values).toMatchObject({ allProductsCollapsible: true, allProductsVisible: true })})+ it.each([+ [true, 1],+ [false, 0],+ ])('reloads stars after custom products reload with the simple sidebar %s', async (enabled, expectedLoads) => {+ const list = jest.fn(() => [200, { results: [] }])+ useMocks({ get: { '/api/projects/:team_id/file_system_shortcut/': list } })+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SIMPLE_SIDEPANEL]: enabled })+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()+ list.mockClear()++ await expectLogic(navProductsTabLogic, () =>+ customProductsLogic.actions.loadCustomProductsSuccess([])+ ).toFinishAllListeners()+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()++ expect(list).toHaveBeenCalledTimes(expectedLoads)+ })++ 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' },+ { id: 'folder', path: 'Research', type: 'folder', ref: 'Research' },+ ]+ useMocks({+ get: {+ '/api/environments/:team_id/file_system_shortcut/': { results },+ '/api/projects/:team_id/file_system_shortcut/': { results },+ },+ })+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()+ await expectLogic(projectTreeDataLogic, () =>+ projectTreeDataLogic.actions.loadShortcuts()+ ).toFinishAllListeners()+ expect(projectTreeDataLogic.values.shortcutData).toEqual([+ { id: 'backend-star', path: 'Session replay', type: 'session_replay', href: urls.replay() },+ { id: 'folder', path: 'Research', type: 'folder', ref: 'Research' },+ ])+ })+it('filters starred products with the product search', async () => {const starredTree = projectTreeLogic({key: PRODUCTS_STARRED_TREE_KEY,@@ -143,100 +188,150 @@ describe('navProductsTabLogic', () => {expect(starredTree.values.searchTerm).toEqual('onboarding')})- it('configures product stars without changing files, folders, or existing order', async () => {- const app = { id: 'app-star', path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' }- const create = jest.fn(() => [201, app])- const remove = jest.fn(() => [204])- useMocks({- post: { '/api/projects/:team_id/file_system_shortcut/': create },- delete: { '/api/projects/:team_id/file_system_shortcut/app-star/': remove },- })+ it('saves staged stars in one request without touching files, folders, or other shortcuts', async () => {+ const saved = [+ { id: 'folder', path: 'Feature flags', type: 'folder', ref: 'Feature flags' },+ { id: 'app-star', path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' },+ ]+ const bulkUpdate = jest.fn(async ({ request }: { request: Request }) => {+ bulkUpdate.body = await request.json()+ return [200, saved]+ }) as jest.Mock & { body?: unknown }+ useMocks({ post: { '/api/projects/:team_id/file_system_shortcut/bulk_update/': bulkUpdate } })await expectLogic(projectTreeDataLogic).toFinishAllListeners()- const existing = [+ projectTreeDataLogic.actions.loadShortcutsSuccess([{ id: 'folder', path: 'Feature flags', type: 'folder', ref: 'Feature flags' },{ id: 'file', path: 'Feature flags', type: 'insight', ref: 'insight-1', href: '/insights/insight-1' },{ id: 'analytics', path: 'Insights', type: 'product_analytics', href: '/insights' },- ]- projectTreeDataLogic.actions.loadShortcutsSuccess(existing)- navProductsTabLogic.actions.setSearch('no matches')- expect(navProductsTabLogic.values.starredProductIds['Feature flags']).toBeUndefined()+ ])++ navProductsTabLogic.actions.setAllProductsOpen(true)+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)+ navProductsTabLogic.actions.setDraftStarred('Product analytics', false)+ expect(navProductsTabLogic.values.allProductsOpen).toBe(true)+ navProductsTabLogic.actions.setDraftStarred('Feature flags', true)+ expect(navProductsTabLogic.values.allProductsOpen).toBe(false)expect(navProductsTabLogic.values.starredProductIds['Product analytics']).toBe('analytics')- await expectLogic(navProductsTabLogic, () => {- navProductsTabLogic.actions.setProductStarred('Feature flags', true)- navProductsTabLogic.actions.setProductStarred('Feature flags', true)- }).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.saveStarredProducts())+ .toDispatchActions(['saveStarredProductsSuccess'])+ .toMatchValues({ customizeSidebarOpen: false, starredProductsSaving: false })+ expect(bulkUpdate).toHaveBeenCalledTimes(1)+ expect(bulkUpdate.body).toEqual({+ add: [{ path: 'Feature flags', type: 'feature_flag', href: '/feature_flags' }],+ remove_ids: ['analytics'],})+ expect(projectTreeDataLogic.values.shortcutData).toEqual(saved)+ })- await expectLogic(navProductsTabLogic, () => {- navProductsTabLogic.actions.setProductStarred('Feature flags', false)- navProductsTabLogic.actions.setProductStarred('Feature flags', false)- }).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.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) => {+ 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 },})+ 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: '' },+ { id: '2', product_path: 'Removed product', enabled: true, created_at: '', updated_at: '' },+ ])++ navProductsTabLogic.actions.openStarredSetup()+ expect([...navProductsTabLogic.values.draftStarredPaths].sort()).toEqual([+ 'Product analytics',+ 'Session replay',+ ])+ 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 () => {+ 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 })+ await expectLogic(projectTreeDataLogic).toFinishAllListeners()+ projectTreeDataLogic.actions.loadShortcutsSuccess([+ { id: 'folder', path: 'Research', type: 'folder', ref: 'Research' },+ { id: 'analytics', path: 'Product analytics', type: 'product_analytics', href: '/insights' },+ // 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()- 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.startWithCleanSlate())+ .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 () => {+ 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.unselectAllStarred()+ navProductsTabLogic.actions.setDraftStarred('Logs', true)+ expect([...navProductsTabLogic.values.draftStarredPaths]).toEqual(['Logs'])++ navProductsTabLogic.actions.setCustomizeSidebarOpen(false)+ navProductsTabLogic.actions.openStarredSetup()+ expect([...navProductsTabLogic.values.draftStarredPaths].sort()).toEqual([+ 'Product analytics',+ 'Session replay',+ ])+ })- 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']],@@ -255,93 +350,52 @@ 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+ it('ignores a save response that arrives after the project changed', async () => {+ let release!: () => voidconst 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' }]+ release = resolve})- 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 },+ post: {+ '/api/projects/:team_id/file_system_shortcut/bulk_update/': async () => {+ await held+ return [200, [{ id: 'old-project-star', path: 'Logs', type: 'logs', href: '/logs' }]]+ },+ },})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,+ projectTreeDataLogic.actions.loadShortcutsSuccess([])+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)+ navProductsTabLogic.actions.setDraftStarred('Logs', true)+ navProductsTabLogic.actions.saveStarredProducts()++ teamLogic.actions.loadCurrentTeamSuccess({+ ...teamLogic.values.currentTeam!,+ id: teamLogic.values.currentTeamId! + 1,})- navProductsTabLogic.actions.setCustomizeSidebarOpen(false)- releaseCreate()- await expectLogic(navProductsTabLogic).toDispatchActions(['saveAppStarsSuccess'])- expect(create).toHaveBeenCalledTimes(1)- expect(remove).toHaveBeenCalledTimes(2)+ const newProjectStars = [{ id: 'new-project-star', path: 'Dashboards', type: 'dashboard', href: '/dashboard' }]+ projectTreeDataLogic.actions.loadShortcutsSuccess(newProjectStars)+ release()++ await expectLogic(navProductsTabLogic)+ .toDispatchActions(['saveStarredProductsFailure'])+ .toMatchValues({ starredProductsSaving: false })+ expect(projectTreeDataLogic.values.shortcutData).toEqual(newProjectStars)})- 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('closes the dialog and drops the unsaved draft when the project changes', () => {+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)+ navProductsTabLogic.actions.setDraftStarred('Feature flags', true)++ teamLogic.actions.loadCurrentTeamSuccess({+ ...teamLogic.values.currentTeam!,+ id: teamLogic.values.currentTeamId! + 1,+ })++ expect(navProductsTabLogic.values.customizeSidebarOpen).toBe(false)+ navProductsTabLogic.actions.setCustomizeSidebarOpen(true)+ expect(navProductsTabLogic.values.draftStarredPaths.has('Feature flags')).toBe(false)+ })it('splits the full ranked catalog at the threshold and clears the grouping', async () => {const requests: DecideRequestApi[] = []@@ -400,6 +454,15 @@ describe('navProductsTabLogic', () => {'SQL editor',])expect(navProductsTabLogic.values.appMatchGroups?.other.map((item) => item.path)).toContain('Feature flags')+ expect(navProductsTabLogic.values.customizeProductGroups[0]).toMatchObject({ label: SUGGESTED_GROUP_LABEL })+ expect(navProductsTabLogic.values.customizeProductGroups[0].items.map((item) => item.path)).toEqual([+ '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.tsindex 876647c09421..ba8923e02f94 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts@@ -1,9 +1,12 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+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 { 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'@@ -14,17 +17,19 @@ 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 { fileSystemShortcutBulkUpdateCreate } from '~/generated/core/api'+import { uiCustomizationLogic } from '~/layout/uiCustomizationLogic'+import { FileSystemEntry, FileSystemImport, UserProductListItem } 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 { customProductsLogic } from '../../ProjectTree/customProductsLogic'+import { getDefaultTreeData, getDefaultTreeProducts, withProductShortcutHref } from '../../ProjectTree/defaultTree'import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'-import { findProductShortcut, joinPath, splitPath } from '../../ProjectTree/utils'+import { findProductShortcut, shortcutFromEntry } from '../../ProjectTree/utils'import { APP_MATCH_THRESHOLD, AppMatchGroups, buildAppRankingQuestions, readAppRankings } from './appRanking'import {POPULAR_CATEGORY,@@ -44,9 +49,15 @@ const DEFINITIONS_TAB_HREFS = new Set(DEFINITIONS_TABS.filter((tab) => tab.key !// Items in this category sit above Starred and All products, so they are never starred or grouped.const PINNED_CATEGORY = 'Project'+// `starred-setup` moves a user's custom products to starred products when they switch to the simple sidebar.+export type CustomizeSidebarMode = 'customize' | 'starred-setup'++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[] // customProductsLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicpreflight: PreflightStatus | null // preflightLogicshortcutData: FileSystemEntry[] // projectTreeDataLogic@@ -56,6 +67,7 @@ export interface navProductsTabLogicValues {allItems: FileSystemImport[]allProductsCollapsible: booleanallProductsOpen: boolean+ allProductsRevealedByFind: booleanallProductsVisible: booleanappMatchGroups: AppMatchGroups | nullappRankingError: string | null@@ -64,21 +76,31 @@ export interface navProductsTabLogicValues {appRecommendationQuery: stringappRecommendationsEnabled: booleanconfigurableProducts: FileSystemImport[]+ customizeProductGroups: ProductsItemGroup[]+ customizeSearch: string+ customizeSidebarMode: CustomizeSidebarModecustomizeSidebarOpen: boolean+ draftStarredChanges: Record<string, boolean>+ draftStarredPaths: Set<string>+ draftStartsEmpty: booleangroupedItems: ProductsItemGroup[]- pendingAppStars: Record<string, boolean>+ initialStarredPaths: string[]pinnedItems: FileSystemImport[]rankedConfigurableApps: FileSystemImport[]search: string- selectedAppStars: Record<string, boolean>- starSaveError: string | null- starSaveResult: null- starSaveResultLoading: booleanstarredProductIds: Record<string, string>+ starredProductsSaving: boolean}// 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+ } // customProductsLogicdeleteShortcutSuccess: (shortcutData: FileSystemEntry[],payload?:@@ -92,6 +114,9 @@ export interface navProductsTabLogicActions {}shortcutData: FileSystemEntry[]} // projectTreeDataLogic+ loadShortcuts: () => {+ value: true+ } // projectTreeDataLogicloadShortcutsFailure: (error: string,errorObject?: any@@ -112,6 +137,27 @@ export interface navProductsTabLogicActions {}shortcutData: FileSystemEntry[]} // projectTreeDataLogic+ locationChanged: ({+ method,+ pathname,+ search,+ searchParams,+ hash,+ hashParams,+ initial,+ url,+ routerState,+ }: LocationChangedPayload) => {+ hash: string+ hashParams: Record<string, any>+ initial: boolean+ method: 'POP' | 'PUSH' | 'REPLACE'+ pathname: string+ routerState: Record<string, any>+ search: string+ searchParams: Record<string, any>+ url: string+ } // routerloadCurrentTeamSuccess: (currentTeam: null | import('~/types').TeamPublicType,payload?: any@@ -119,19 +165,17 @@ export interface navProductsTabLogicActions {currentTeam: null | import('~/types').TeamPublicTypepayload?: any} // teamLogic- finishAppStar: (- productPath: string,- starred: boolean- ) => {- productPath: string- starred: boolean+ completeStarredProductsSetup: () => {+ value: true+ } // uiCustomizationLogic+ confirmCleanSlate: () => {+ value: true}- queueAppStar: (- productPath: string,- starred: boolean- ) => {- productPath: string- starred: boolean+ dismissStarredSetup: () => {+ value: true+ }+ openStarredSetup: () => {+ value: true}rankApps: ({ query }: { query: string }) => {query: string@@ -157,20 +201,17 @@ export interface navProductsTabLogicActions {resetAppConfiguration: () => {value: true}- saveAppStars: (_: void) => void- saveAppStarsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any+ revealAllProductsForFind: () => {+ value: true}- saveAppStarsSuccess: (- starSaveResult: null,- payload?: void- ) => {- starSaveResult: null- payload?: void+ saveStarredProducts: () => {+ value: true+ }+ saveStarredProductsFailure: () => {+ value: true+ }+ saveStarredProductsSuccess: () => {+ value: true}setAllProductsOpen: (open: boolean) => {open: boolean@@ -181,10 +222,13 @@ export interface navProductsTabLogicActions {setAppRecommendationQuery: (query: string) => {query: string}+ setCustomizeSearch: (search: string) => {+ search: string+ }setCustomizeSidebarOpen: (open: boolean) => {open: boolean}- setProductStarred: (+ setDraftStarred: (productPath: string,starred: boolean) => {@@ -194,8 +238,11 @@ export interface navProductsTabLogicActions {setSearch: (search: string) => {search: string}- setStarSaveError: (error: string | null) => {- error: string | null+ startWithCleanSlate: () => {+ value: true+ }+ unselectAllStarred: () => {+ value: true}}@@ -219,18 +266,33 @@ export interface navProductsTabLogicMeta {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[]configurableProducts: (allItems: FileSystemImport[]) => FileSystemImport[]starredProductIds: (allItems: FileSystemImport[], shortcutData: FileSystemEntry[]) => Record<string, string>+ customizeProductGroups: (+ configurableProducts: FileSystemImport[],+ customizeSearch: string,+ appMatchGroups: AppMatchGroups | null,+ customizeSidebarMode: CustomizeSidebarMode+ ) => ProductsItemGroup[]+ initialStarredPaths: (+ configurableProducts: FileSystemImport[],+ starredProductIds: Record<string, string>,+ customizeSidebarMode: CustomizeSidebarMode,+ customProducts: UserProductListItem[]+ ) => string[]+ draftStarredPaths: (+ configurableProducts: FileSystemImport[],+ initialStarredPaths: string[],+ draftStarredChanges: Record<string, boolean>,+ draftStartsEmpty: boolean+ ) => Set<string>allProductsCollapsible: (shortcutDataHasLoaded: boolean, starredProductIds: Record<string, string>) => booleanallProductsVisible: (allProductsOpen: boolean,+ allProductsRevealedByFind: boolean,allProductsCollapsible: boolean,search: string,shortcutDataHasLoaded: boolean@@ -259,12 +321,20 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([['dataProcessingAccepted'],projectTreeDataLogic,['shortcutData', 'shortcutDataHasLoaded', 'shortcutDataLoading'],+ customProductsLogic,+ ['customProducts'],],actions: [projectTreeDataLogic,- ['deleteShortcutSuccess', 'loadShortcutsFailure', 'loadShortcutsSuccess'],+ ['deleteShortcutSuccess', 'loadShortcuts', 'loadShortcutsFailure', 'loadShortcutsSuccess'],+ customProductsLogic,+ ['loadCustomProductsSuccess'],+ router,+ ['locationChanged'],teamLogic,['loadCurrentTeamSuccess'],+ uiCustomizationLogic,+ ['completeStarredProductsSetup'],],logic: [projectTreeLogic({ key: PRODUCTS_STARRED_TREE_KEY, root: 'shortcuts://', shortcutScope: 'products' })],})),@@ -272,75 +342,22 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([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 }),+ 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,+ saveStarredProductsFailure: true,}),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,{@@ -413,33 +430,58 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([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,+ search: ['', { setSearch: (_, { search }) => search }],+ customizeSidebarOpen: [+ 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,{- setStarSaveError: (_, { error }) => error,- queueAppStar: () => null,- resetAppConfiguration: () => null,+ setCustomizeSidebarOpen: (state, { open }) => (open ? 'customize' : state),+ openStarredSetup: () => 'starred-setup',},],- pendingAppStars: [+ // Choices made in the dialog, applied over the starting selection. Nothing is saved until Save.+ draftStarredChanges: [{} 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- },+ setDraftStarred: (state, { productPath, starred }) => ({ ...state, [productPath]: starred }),+ unselectAllStarred: () => ({}),+ setCustomizeSidebarOpen: (state, { open }) => (open ? {} : state),+ openStarredSetup: () => ({}),},],- search: ['', { setSearch: (_, { search }) => search }],- customizeSidebarOpen: [+ // After "Unselect all", the draft starts from nothing instead of the current stars.+ draftStartsEmpty: [+ false,+ {+ unselectAllStarred: () => true,+ setCustomizeSidebarOpen: (state, { open }) => (open ? false : state),+ openStarredSetup: () => false,+ },+ ],+ customizeSearch: [+ '',+ {+ setCustomizeSearch: (_, { search }) => search,+ setCustomizeSidebarOpen: (state, { open }) => (open ? '' : state),+ openStarredSetup: () => '',+ },+ ],+ starredProductsSaving: [false,- { setCustomizeSidebarOpen: (_, { open }) => open, resetAppConfiguration: () => false },+ {+ saveStarredProducts: () => true,+ saveStarredProductsSuccess: () => false,+ saveStarredProductsFailure: () => 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.@@ -448,6 +490,16 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([{ persist: true },{ setAllProductsOpen: (_, { open }) => open },],+ // The browser's find-in-page opened the list to show a match. Not persisted, so the list+ // closes again on the next navigation instead of staying open for good.+ allProductsRevealedByFind: [+ false,+ {+ revealAllProductsForFind: () => true,+ setAllProductsOpen: () => false,+ locationChanged: () => false,+ },+ ],}),selectors({appRecommendationsEnabled: [@@ -486,13 +538,6 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([}: 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[] => {@@ -585,6 +630,58 @@ 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') {+ return groupProducts(items, search)+ }+ const suggested = appMatchGroups.matching.filter((item) => productMatchesSearch(item, search))+ const rest = groupProducts(appMatchGroups.other, search)+ 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)+ },+ ],+ draftStarredPaths: [+ (s) => [s.configurableProducts, s.initialStarredPaths, s.draftStarredChanges, s.draftStartsEmpty],+ (+ items: FileSystemImport[],+ initialStarredPaths: string[],+ draftStarredChanges: Record<string, boolean>,+ draftStartsEmpty: boolean+ ): Set<string> => {+ const initial = new Set(draftStartsEmpty ? [] : initialStarredPaths)+ return new Set(+ items+ .filter((item) => draftStarredChanges[item.path] ?? initial.has(item.path))+ .map((item) => item.path)+ )+ },+ ],// Only a sidebar with starred products has something to show above the list, so only then can it close.allProductsCollapsible: [(s) => [s.shortcutDataHasLoaded, s.starredProductIds],@@ -593,13 +690,24 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([],// A search always shows its matches, even when the list is closed.allProductsVisible: [- (s) => [s.allProductsOpen, s.allProductsCollapsible, s.search, s.shortcutDataHasLoaded],+ (s) => [+ s.allProductsOpen,+ s.allProductsRevealedByFind,+ s.allProductsCollapsible,+ s.search,+ s.shortcutDataHasLoaded,+ ],(allProductsOpen: boolean,+ allProductsRevealedByFind: boolean,allProductsCollapsible: boolean,search: string,shortcutDataHasLoaded: boolean- ): boolean => allProductsOpen || !!search.trim() || (shortcutDataHasLoaded && !allProductsCollapsible),+ ): boolean =>+ allProductsOpen ||+ allProductsRevealedByFind ||+ !!search.trim() ||+ (shortcutDataHasLoaded && !allProductsCollapsible),],}),listeners(({ actions, values, cache }) => {@@ -610,52 +718,142 @@ export const navProductsTabLogic = kea<navProductsTabLogicType>([}}return {- loadShortcutsSuccess: keepAllProductsOpenWithoutStars,- loadShortcutsFailure: keepAllProductsOpenWithoutStars,- deleteShortcutSuccess: keepAllProductsOpenWithoutStars,loadCurrentTeamSuccess: () => {if (cache.appConfigurationTeamId !== values.currentTeamId) {cache.appConfigurationTeamId = values.currentTeamId- const hadPendingChanges = Object.keys(values.pendingAppStars).length > 0actions.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 }- )- }}},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) },- })+ setAppRecommendationQuery: ({ query }) => actions.rankApps({ query }),+ loadShortcutsSuccess: keepAllProductsOpenWithoutStars,+ loadShortcutsFailure: keepAllProductsOpenWithoutStars,+ deleteShortcutSuccess: keepAllProductsOpenWithoutStars,+ // A product intent can add custom products, and the backend stars them for simple sidebar+ // users in the same request. Custom products reload after that write, so shortcuts follow.+ loadCustomProductsSuccess: () => {+ if (values.featureFlags[FEATURE_FLAGS.SIMPLE_SIDEPANEL]) {+ 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 }) => {- if (!open && values.starSaveError) {- actions.setStarSaveError(values.starSaveError)+ if (!open && values.customizeSidebarMode === 'starred-setup') {+ posthog.capture('sidebar starred setup cancelled')}},- setAppRecommendationQuery: ({ query }) => actions.rankApps({ query }),- setProductStarred: ({ productPath, starred }) => {- if (!values.configurableProducts.some((app) => app.path === productPath)) {+ saveStarredProducts: async () => {+ // The footer buttons are disabled in these states, but the intro link and repeated+ // dispatches reach this listener directly.+ if (cache.starredSaveInFlight) {return}- actions.queueAppStar(productPath, starred)- },- queueAppStar: async (_, breakpoint) => {- await breakpoint(250)- if (!values.starSaveResultLoading) {- actions.saveAppStars()+ const teamId = values.currentTeamId+ if (teamId === null || !values.shortcutDataHasLoaded) {+ actions.saveStarredProductsFailure()+ return+ }+ const { draftStarredPaths, starredProductIds, customizeSidebarMode, 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))+ const add = orderedProducts+ .filter((item) => draftStarredPaths.has(item.path) && !starredProductIds[item.path])+ .map(shortcutFromEntry)+ const removeIds = [+ ...orderedProducts+ .filter((item) => !draftStarredPaths.has(item.path) && starredProductIds[item.path])+ .map((item) => starredProductIds[item.path]),+ // "Unselect all" and the clean slate also clear stars the dialog cannot list,+ // such as a product the user has since lost access to.+ ...(draftStartsEmpty+ ? Object.entries(starredProductIds)+ .filter(([path]) => !configurablePaths.has(path))+ .map(([, id]) => id)+ : []),+ ]++ if (add.length > 0 || removeIds.length > 0) {+ cache.starredSaveInFlight = true+ try {+ const shortcuts = await fileSystemShortcutBulkUpdateCreate(String(teamId), {+ add,+ remove_ids: removeIds,+ })+ // A response for a project the user already left would overwrite the new project's stars.+ if (values.currentTeamId !== teamId) {+ actions.saveStarredProductsFailure()+ return+ }+ actions.loadShortcutsSuccess((shortcuts as FileSystemEntry[]).map(withProductShortcutHref))+ } catch (error) {+ console.error('Failed to save starred products:', error)+ lemonToast.error('Could not save your starred products. Try again.')+ actions.saveStarredProductsFailure()+ return+ } finally {+ 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,+ added_count: add.length,+ removed_count: removeIds.length,+ starred_count: draftStarredPaths.size,+ custom_products_count: values.customProducts.length,+ })+ actions.saveStarredProductsSuccess()},setSearch: ({ search }) => {projectTreeLogic({diff --git a/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx b/frontend/src/layout/scenes/ConfigureHomeModalContent.tsxindex 0e321141d22f..879105e2dfd2 100644--- a/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx+++ b/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import posthog from 'posthog-js'import { useEffect, useState } from 'react'-import { LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'+import { LemonSegmentedButton } from '@posthog/lemon-ui'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { dashboardsModel } from '~/models/dashboardsModel'@@ -117,14 +117,7 @@ export function ConfigureHomeModalContent(): JSX.Element {options={[{value: 'launchpad' as const,- label: (- <>- Launchpad{' '}- <LemonTag size="small" type="highlight" className="ml-1">- New- </LemonTag>- </>- ),+ label: 'Launchpad','data-attr': 'configure-home-modal-set-launchpad',tooltip: 'An AI-powered home with quick actions and recent items',},diff --git a/frontend/src/layout/scenes/HomepageConfiguration.tsx b/frontend/src/layout/scenes/HomepageConfiguration.tsxindex 7f98822aa091..4bf6ca27429f 100644--- a/frontend/src/layout/scenes/HomepageConfiguration.tsx+++ b/frontend/src/layout/scenes/HomepageConfiguration.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import posthog from 'posthog-js'import { useEffect, useState } from 'react'-import { LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'+import { LemonSegmentedButton } from '@posthog/lemon-ui'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { dashboardsModel } from '~/models/dashboardsModel'@@ -129,14 +129,7 @@ export function HomepageConfiguration(): JSX.Element {options={[{value: 'launchpad' as const,- label: (- <>- Launchpad{' '}- <LemonTag size="small" type="highlight" className="ml-1">- New- </LemonTag>- </>- ),+ label: 'Launchpad','data-attr': 'configure-home-modal-set-launchpad',tooltip: 'An AI-powered home with quick actions and recent items',},diff --git a/frontend/src/layout/uiCustomizationLogic.ts b/frontend/src/layout/uiCustomizationLogic.tsindex 24f9a1135a80..d5baa93480e7 100644--- a/frontend/src/layout/uiCustomizationLogic.ts+++ b/frontend/src/layout/uiCustomizationLogic.ts@@ -76,6 +76,7 @@ export interface uiCustomizationLogicValues {isSidebarSectionShown: (section: keyof SidebarSectionsConfiguration) => booleanpendingUiConfiguration: UserUIConfiguration | nullsidebarDensity: SidebarDensity+ starredProductsSetupCompleted: booleanuiConfiguration: UserUIConfiguration | nulluiCustomizationEnabled: boolean}@@ -111,6 +112,9 @@ export interface uiCustomizationLogicActions {}user: UserType} // userLogic+ completeStarredProductsSetup: () => {+ value: true+ }setPendingUiConfiguration: (configuration: UserUIConfiguration | null) => {configuration: UserUIConfiguration | null}@@ -149,6 +153,7 @@ export interface uiCustomizationLogicMeta {uiConfiguration: UserUIConfiguration | null,uiCustomizationEnabled: boolean) => (item: keyof SidebarItemsConfiguration) => boolean+ starredProductsSetupCompleted: (uiConfiguration: UserUIConfiguration | null) => booleansidebarDensity: (uiConfiguration: UserUIConfiguration | null, uiCustomizationEnabled: boolean) => SidebarDensity}}@@ -176,6 +181,7 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([setSidebarDensity: (density: SidebarDensity) => ({ density }),setSidebarItemShown: (item: SidebarItemKey, shown: boolean) => ({ item, shown }),setPendingUiConfiguration: (configuration: UserUIConfiguration | null) => ({ configuration }),+ completeStarredProductsSetup: true,}),reducers({// Optimistic copy held while the user PATCH is in flight, so toggles apply instantly.@@ -209,6 +215,12 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([(item: SidebarItemKey): boolean =>!uiCustomizationEnabled || uiConfiguration?.sidebar?.items?.[item]?.visible !== false,],+ // Unlike the visibility settings, this is read whether or not UI customization is on.+ starredProductsSetupCompleted: [+ (s) => [s.uiConfiguration],+ (uiConfiguration: UserUIConfiguration | null): boolean =>+ !!uiConfiguration?.sidebar?.starred_products_setup_completed,+ ],sidebarDensity: [(s) => [s.uiConfiguration, s.uiCustomizationEnabled],(uiConfiguration: UserUIConfiguration | null, uiCustomizationEnabled: boolean): SidebarDensity =>@@ -245,6 +257,11 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([element_key: density,})},+ completeStarredProductsSetup: () => {+ const configuration = withSidebarPatch(values.uiConfiguration, { starred_products_setup_completed: true })+ actions.setPendingUiConfiguration(configuration)+ actions.updateUser({ ui_configuration: configuration })+ },updateUserSuccess: () => {actions.setPendingUiConfiguration(null)},diff --git a/frontend/src/lib/api.mock.ts b/frontend/src/lib/api.mock.tsindex 61d32cb57827..b7ff4b29adac 100644--- a/frontend/src/lib/api.mock.ts+++ b/frontend/src/lib/api.mock.ts@@ -261,6 +261,8 @@ export const MOCK_DEFAULT_USER: UserType = {has_social_auth: false,has_sso_enforcement: false,shortcut_position: 'above',+ // Most stories show a settled sidebar. Stories of the starred products setup override this.+ ui_configuration: { version: 1, sidebar: { starred_products_setup_completed: true } },sensitive_session_expires_at: dayjs().add(1, 'hour').toISOString(),theme_mode: null,team: MOCK_DEFAULT_TEAM,diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsxindex b4ca9f6da35e..78361b220e5b 100644--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx@@ -1,22 +1,29 @@import { useValues } from 'kea'import { FEATURE_FLAGS } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'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 isSimpleSidepanelEnabled = useFeatureFlag('SIMPLE_SIDEPANEL')+ const { starredProductsSetupCompleted } = useValues(uiCustomizationLogic)+ const { customProducts } = useValues(customProductsLogic)const broadcastPayload = getFeatureFlagPayload(FEATURE_FLAGS.NAV_PANEL_BROADCAST) as BroadcastPayload | undefined@@ -24,6 +31,13 @@ export function NavPanelAdvertisement(): JSX.Element | null {return null}+ // A one-time setup for everyone moving to the simple sidebar, so it outranks promotional cards.+ // Users without custom products have nothing to move, which includes brand new users before+ // their defaults are seeded.+ if (isSimpleSidepanelEnabled && 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.tsxnew file mode 100644index 000000000000..9dabf9d42075--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelStarredSetupAd.tsx@@ -0,0 +1,73 @@+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.tsxindex a62822ccc254..1e66c55a36ad 100644--- a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx@@ -19,6 +19,7 @@ import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'export const NAV_PANEL_CARD_TYPE = {BROADCAST: 'broadcast',PRODUCT_PUSH: 'product_push',+ STARRED_SETUP: 'starred_setup',} as constexport interface BroadcastPayload {diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsxindex 32a92aca9c02..09a04aa19c4e 100644--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx@@ -144,6 +144,8 @@ type LemonTreeBaseProps = Omit</** The render function for the item. */renderItem?: (item: TreeDataItem, children: React.ReactNode) => React.ReactNoderenderItemTooltip?: (item: TreeDataItem) => React.ReactNode | undefined+ /** A docs link shown under the item's tooltip. It makes the tooltip interactive so the link can be clicked. */+ renderItemTooltipDocLink?: (item: TreeDataItem) => string | undefinedrenderItemIcon?: (item: TreeDataItem) => React.ReactNode | undefined/** Set the IDs of the expanded items. */onSetExpandedItemIds?: (ids: string[]) => void@@ -266,6 +268,7 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(handleClick,renderItem,renderItemTooltip,+ renderItemTooltipDocLink,renderItemIcon,expandedItemIds,defaultNodeIcon,@@ -377,6 +380,9 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(aria-roledescription="tree item"aria-label={ariaLabel}tooltip={isDragging || isEmptyFolder ? undefined : (item.disabledReason ?? renderItemTooltip?.(item))}+ tooltipDocLink={+ isDragging || isEmptyFolder || item.disabledReason ? undefined : renderItemTooltipDocLink?.(item)+ }tooltipPlacement="right">{size === 'default' && (diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 058ac6a33221..5792591c119e 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -52055,6 +52055,10 @@},"sections": {"$ref": "#/definitions/SidebarSectionsConfiguration"+ },+ "starred_products_setup_completed": {+ "description": "True once the user saved or dismissed the setup that moves their custom products to starred products in the simple sidebar.",+ "type": "boolean"}},"type": "object"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 44c7995ef0af..16610fd764d2 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8960,6 +8960,8 @@ export interface SidebarConfiguration {items?: SidebarItemsConfiguration/** Row density of the sidebar. */density?: SidebarDensity+ /** True once the user saved or dismissed the setup that moves their custom products to starred products in the simple sidebar. */+ starred_products_setup_completed?: boolean[key: string]: unknown}diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 04767a0a0a2b..0456c3066350 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -2355,6 +2355,8 @@ export const SETTINGS_MAP: SettingSection[] = [description:"When we detect you are using a new product, we'll automatically add it to your sidebar as a suggestion. We might also suggest products that are related to the ones you are using when we launch a new one.",component: <SidebarAutoSuggestSetting />,+ // Suggestions land in custom products, which the simple sidebar does not show.+ flag: '!SIMPLE_SIDEPANEL',keywords: ['sidebar', 'suggest', 'products', 'apps', 'tools', 'auto'],},{@@ -2400,7 +2402,8 @@ export const SETTINGS_MAP: SettingSection[] = [level: 'user',id: 'user-navigation',title: 'Navigation',- flag: 'UI_CUSTOMIZATION',+ // The simple sidebar edits these inline, from its own customize dialog.+ flag: ['UI_CUSTOMIZATION', '!SIMPLE_SIDEPANEL'],settings: [{id: 'homepage',diff --git a/posthog/api/file_system/file_system_shortcut.py b/posthog/api/file_system/file_system_shortcut.pyindex d57aaeb8aefc..a86fde2ce33d 100644--- a/posthog/api/file_system/file_system_shortcut.py+++ b/posthog/api/file_system/file_system_shortcut.py@@ -14,7 +14,7 @@ from posthog.api.file_system.access_levels import FileSystemAccessLevelSerializefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models import Userfrom posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q-from posthog.models.file_system.file_system_shortcut import FileSystemShortcut+from posthog.models.file_system.file_system_shortcut import FileSystemShortcut, lock_user_shortcutsclass FileSystemShortcutSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):@@ -53,21 +53,24 @@ class FileSystemShortcutSerializer(FileSystemAccessLevelSerializerMixin, serialidef create(self, validated_data: dict[str, Any], *args: Any, **kwargs: Any) -> FileSystemShortcut:request = self.context["request"]team = self.context["get_team"]()- # Place new shortcuts at the end of the user's current order so they don't jump- # ahead of items the user has explicitly reordered.- last_order = (- FileSystemShortcut.objects.filter(team=team, user=request.user)- .order_by("-order")- .values_list("order", flat=True)- .first()- )- validated_data.setdefault("order", (last_order or 0) + 1)- file_system_shortcut = FileSystemShortcut.objects.create(- team=team,- user=request.user,- surface=self.context.get("file_system_surface", DEFAULT_SURFACE),- **validated_data,- )+ with transaction.atomic():+ # Two stars added at once would otherwise read the same last order and share it.+ lock_user_shortcuts(team.pk, request.user.pk)+ # Place new shortcuts at the end of the user's current order so they don't jump+ # ahead of items the user has explicitly reordered.+ last_order = (+ FileSystemShortcut.objects.filter(team=team, user=request.user)+ .order_by("-order")+ .values_list("order", flat=True)+ .first()+ )+ validated_data.setdefault("order", (last_order or 0) + 1)+ file_system_shortcut = FileSystemShortcut.objects.create(+ team=team,+ user=request.user,+ surface=self.context.get("file_system_surface", DEFAULT_SURFACE),+ **validated_data,+ )return file_system_shortcut@@ -79,6 +82,48 @@ class FileSystemShortcutReorderSerializer(serializers.Serializer):)+class FileSystemShortcutBulkItemSerializer(serializers.Serializer):+ path = serializers.CharField(help_text="Display path of the shortcut in the sidebar.")+ type = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=100,+ help_text="Type of the linked item (e.g. 'folder', 'insight'), or blank.",+ )+ ref = serializers.CharField(+ required=False,+ allow_null=True,+ default=None,+ max_length=4000,+ help_text="Reference to the linked item, scoped to its type. Null for href-only shortcuts.",+ )+ href = serializers.CharField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Destination URL the shortcut opens. Null when the shortcut points at an item by ref.",+ )+++class FileSystemShortcutBulkUpdateSerializer(serializers.Serializer):+ add = serializers.ListField(+ child=FileSystemShortcutBulkItemSerializer(),+ required=False,+ default=list,+ max_length=500,+ help_text="Shortcuts to create, appended to the end of the current order in the given sequence. "+ "An item identical to a shortcut the user already has is skipped.",+ )+ remove_ids = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ default=list,+ max_length=500,+ help_text="IDs of the current user's shortcuts to delete.",+ )++@extend_schema(extensions={"x-product": "core"})class FileSystemShortcutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = FileSystemShortcut.objects.all()@@ -147,3 +192,57 @@ class FileSystemShortcutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):refreshed = self.filter_queryset(self.get_queryset())return Response(self.get_serializer(refreshed, many=True).data)++ @extend_schema(+ request=FileSystemShortcutBulkUpdateSerializer,+ responses={200: OpenApiResponse(response=FileSystemShortcutSerializer(many=True))},+ description="Create and delete several of the current user's shortcuts in one transaction, then return "+ "the full shortcut list in display order. Any unknown ID in `remove_ids` rejects the whole request.",+ )+ @action(detail=False, methods=["post"], url_path="bulk_update", pagination_class=None)+ def bulk_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = FileSystemShortcutBulkUpdateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ items: list[dict[str, Any]] = serializer.validated_data["add"]+ remove_ids = {str(uuid) for uuid in serializer.validated_data["remove_ids"]}++ user = cast(User, request.user)+ user_shortcuts_qs = FileSystemShortcut.objects.filter(+ surface_q(self.file_system_surface), team=self.team, user=user+ )+ with transaction.atomic():+ # Overlapping saves would otherwise read the same list and add duplicates or reuse an order.+ lock_user_shortcuts(self.team.pk, user.pk)+ existing = list(user_shortcuts_qs.values_list("id", "path", "type", "ref", "href", "order"))+ unknown = sorted(remove_ids - {str(row[0]) for row in existing})+ if unknown:+ return Response(+ {"detail": "Unknown shortcut ids", "unknown_ids": unknown},+ status=status.HTTP_400_BAD_REQUEST,+ )++ kept = [row for row in existing if str(row[0]) not in remove_ids]+ seen = {(path, kind or "", ref, href) for _, path, kind, ref, href, _ in kept}+ next_order = max((row[5] for row in kept), default=0) + 1+ to_create: list[FileSystemShortcut] = []+ for item in items:+ key = (item["path"], item["type"], item["ref"], item["href"])+ if key in seen:+ continue+ seen.add(key)+ to_create.append(+ FileSystemShortcut(+ team=self.team,+ user=user,+ surface=self.file_system_surface,+ order=next_order + len(to_create),+ **item,+ )+ )++ if remove_ids:+ user_shortcuts_qs.filter(id__in=remove_ids).delete()+ FileSystemShortcut.objects.bulk_create(to_create)++ refreshed = self.filter_queryset(self.get_queryset())+ return Response(self.get_serializer(refreshed, many=True).data)diff --git a/posthog/api/file_system/test/test_file_system_shortcut.py b/posthog/api/file_system/test/test_file_system_shortcut.pyindex 1625705654be..7dc2a916a561 100644--- a/posthog/api/file_system/test/test_file_system_shortcut.py+++ b/posthog/api/file_system/test/test_file_system_shortcut.py@@ -152,19 +152,56 @@ class TestFileSystemShortcutAPI(APIBaseTest):shortcut.refresh_from_db()self.assertEqual(shortcut.order, expected_order)- def test_reorder_rejects_foreign_user_shortcuts(self):+ @parameterized.expand(+ [+ ("reorder", "reorder", "ordered_ids"),+ ("bulk_update", "bulk_update", "remove_ids"),+ ]+ )+ def test_rejects_foreign_user_shortcuts(self, _name: str, url_path: str, ids_field: str):other_user = self._create_user("other")foreign = FileSystemShortcut.objects.create(team=self.team, path="Foreign", type="t", user=other_user)response = self.client.post(- f"/api/projects/{self.team.id}/file_system_shortcut/reorder/",- {"ordered_ids": [str(foreign.id)]},+ f"/api/projects/{self.team.id}/file_system_shortcut/{url_path}/",+ {ids_field: [str(foreign.id)], "add": [{"path": "Logs", "type": "logs", "href": "/logs"}]},format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())self.assertIn(str(foreign.id), response.json()["unknown_ids"])foreign.refresh_from_db()self.assertEqual(foreign.order, 0)+ self.assertFalse(FileSystemShortcut.objects.filter(user=self.user).exists())++ def test_bulk_update_adds_removes_and_skips_duplicates(self):+ kept = FileSystemShortcut.objects.create(+ team=self.team, path="Dashboards", type="dashboard", href="/dashboard", user=self.user, order=3+ )+ removed = FileSystemShortcut.objects.create(+ team=self.team, path="Logs", type="logs", href="/logs", user=self.user, order=4+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/file_system_shortcut/bulk_update/",+ {+ "add": [+ {"path": "Session replay", "type": "session_replay", "href": "/replay"},+ {"path": "Dashboards", "type": "dashboard", "href": "/dashboard"},+ {"path": "Feature flags", "type": "feature_flag", "href": "/feature_flags"},+ {"path": "Feature flags", "type": "feature_flag", "href": "/feature_flags"},+ ],+ "remove_ids": [str(removed.id)],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(+ [(row["path"], row["order"]) for row in response.json()],+ [("Dashboards", 3), ("Session replay", 4), ("Feature flags", 5)],+ )+ self.assertEqual(response.json()[0]["id"], str(kept.id))+ self.assertFalse(FileSystemShortcut.objects.filter(id=removed.id).exists())def test_reorder_rejects_empty_list(self):response = self.client.post(diff --git a/posthog/api/file_system/user_product_list.py b/posthog/api/file_system/user_product_list.pyindex ebe89f4630d5..73b15b9f311c 100644--- a/posthog/api/file_system/user_product_list.py+++ b/posthog/api/file_system/user_product_list.py@@ -11,7 +11,8 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models import User-from posthog.models.file_system.user_product_list import UserProductList+from posthog.models.file_system.starred_products import star_custom_products+from posthog.models.file_system.user_product_list import UserProductList, user_has_custom_productsclass UserProductListSerializer(serializers.ModelSerializer):@@ -35,11 +36,15 @@ class UserProductListSerializer(serializers.ModelSerializer):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=request.user,+ 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@@ -61,7 +66,9 @@ class UserProductListViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)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")@@ -69,16 +76,20 @@ class UserProductListViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not product_path or enabled is None:continue- existing_item, _created = UserProductList.objects.get_or_create(+ 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 createdserializer = 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/test/test_user.py b/posthog/api/test/test_user.pyindex dc02e250c9ad..977ec8db2295 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2831,6 +2831,37 @@ class TestUserUIConfigurationValidation(SimpleTestCase):self.assertTrue(serializer.is_valid(), serializer.errors)self.assertEqual(serializer.validated_data["ui_configuration"], value)+ @parameterized.expand(+ [+ (+ "omitted_key_is_kept",+ True,+ {"version": 1, "sidebar": {"density": "compact"}},+ {"version": 1, "sidebar": {"density": "compact", "starred_products_setup_completed": True}},+ ),+ (+ "omitted_sidebar_is_kept",+ True,+ {"version": 1},+ {"version": 1, "sidebar": {"starred_products_setup_completed": True}},+ ),+ ("reset_is_kept", True, None, {"version": 1, "sidebar": {"starred_products_setup_completed": True}}),+ (+ "explicit_false_wins",+ True,+ {"version": 1, "sidebar": {"starred_products_setup_completed": False}},+ {"version": 1, "sidebar": {"starred_products_setup_completed": False}},+ ),+ ("not_completed_is_untouched", False, {"version": 1}, {"version": 1}),+ ]+ )+ def test_update_keeps_completed_starred_products_setup(self, _name, completed, value, expected):+ user = User(ui_configuration={"version": 1, "sidebar": {"starred_products_setup_completed": completed}})+ serializer = UserSerializer(instance=user, data={"ui_configuration": value}, partial=True)++ self.assertTrue(serializer.is_valid(), serializer.errors)+ self.assertEqual(serializer.validated_data["ui_configuration"], expected)+@pytest.mark.eeclass TestToolbarAccessControl(APIBaseTest):diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 74f2f0fb7002..1fd723ed1cc2 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -117,7 +117,13 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomainfrom posthog.models.organization_notification_lock import notification_locks_for_usersfrom posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.user import ROLE_CHOICES, Notifications, OnboardingSkippedReason, ShortcutPosition+from posthog.models.user import (+ ROLE_CHOICES,+ Notifications,+ OnboardingSkippedReason,+ ShortcutPosition,+ preserve_starred_products_setup,+)from posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import APIScopePermission, TimeSensitiveActionPermission, UserNoOrgMembershipDeletePermissionfrom posthog.rate_limit import (@@ -280,7 +286,8 @@ class UserSerializer(serializers.ModelSerializer):help_text=("Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers ""sidebar section and item visibility. Send the complete object: it replaces the stored value "- "wholesale. Null means no customization; absent keys mean the element is shown."+ "wholesale. Null means no customization; absent keys mean the element is shown. Once "+ "`sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true."),)anonymize_data = ClassicBehaviorBooleanFieldSerializer(@@ -660,6 +667,7 @@ class UserSerializer(serializers.ModelSerializer):return validate_notification_settings(cast(User, self.instance), notification_settings)def validate_ui_configuration(self, value: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:+ value = preserve_starred_products_setup(cast(Optional[User], self.instance), value)if value is None:return Nonetry:diff --git a/posthog/models/file_system/file_system_shortcut.py b/posthog/models/file_system/file_system_shortcut.pyindex d26b1c814c14..2e1053dc9516 100644--- a/posthog/models/file_system/file_system_shortcut.py+++ b/posthog/models/file_system/file_system_shortcut.py@@ -1,4 +1,4 @@-from django.db import models+from django.db import connection, modelsfrom django.db.models.expressions import Ffrom django.db.models.functions import Lowerfrom django.utils import timezone@@ -35,3 +35,14 @@ class FileSystemShortcut(models.Model):def __str__(self):return self.path+++def lock_user_shortcuts(team_id: int, user_id: int) -> None:+ """Serialize writes to one user's shortcut list, even when the list has no rows to lock yet.++ Call inside `transaction.atomic()`: the lock lasts until the transaction ends.+ """+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", [f"file-system-shortcuts:{team_id}:{user_id}"]+ )diff --git a/posthog/models/file_system/starred_products.py b/posthog/models/file_system/starred_products.pynew file mode 100644index 000000000000..3884c4d40ef0--- /dev/null+++ b/posthog/models/file_system/starred_products.py@@ -0,0 +1,107 @@+from typing import TYPE_CHECKING, Any++from django.db import transaction++import posthoganalytics++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.products import Products++if TYPE_CHECKING:+ from posthog.models.team import Team+ from posthog.models.user import User++# pinned: feature flag key, must match FEATURE_FLAGS.SIMPLE_SIDEPANEL in frontend/src/lib/constants.tsx+SIMPLE_SIDEPANEL_FLAG = "simple-sidepanel"+++def starred_products_setup_completed(user: "User") -> bool:+ configuration = user.ui_configuration+ sidebar = configuration.get("sidebar") if isinstance(configuration, dict) else None+ return isinstance(sidebar, dict) and bool(sidebar.get("starred_products_setup_completed"))+++def _simple_sidebar_enabled(user: "User", team: "Team") -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ SIMPLE_SIDEPANEL_FLAG,+ str(user.distinct_id),+ person_properties={"email": user.email},+ # Same group keys as the frontend's posthog.group() calls, so both sides get the same answer.+ groups={"organization": str(team.organization_id), "project": str(team.uuid)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+++def _mark_setup_completed(user: "User") -> None:+ # Merge into the stored value under a short row lock, so a concurrent settings change is kept.+ # NO KEY UPDATE is the lock the UPDATE takes anyway, and it does not block inserts of child rows.+ with transaction.atomic():+ stored = (+ type(user).objects.select_for_update(no_key=True).only("ui_configuration").get(pk=user.pk).ui_configuration+ )+ configuration: dict[str, Any] = stored if isinstance(stored, dict) else {}+ sidebar = configuration.get("sidebar")+ user.ui_configuration = {+ "version": 1,+ **configuration,+ "sidebar": {**(sidebar if isinstance(sidebar, dict) else {}), "starred_products_setup_completed": True},+ }+ user.save(update_fields=["ui_configuration"])+++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, for simple sidebar users.++ 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:++ - 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.+ """+ if not product_paths:+ return+ completed = starred_products_setup_completed(user)+ if not completed and had_custom_products:+ return+ if not _simple_sidebar_enabled(user, team):+ return++ products_by_path = {product.path: product for product in Products.products()}+ 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)+ user_shortcuts = FileSystemShortcut.objects.filter(surface_q(DEFAULT_SURFACE), team=team, user=user)+ starred_paths = set(+ user_shortcuts.filter(ref__isnull=True).exclude(type="folder").values_list("path", flat=True)+ )+ next_order = max(user_shortcuts.values_list("order", flat=True), default=0) + 1++ to_create: list[FileSystemShortcut] = []+ for path in product_paths:+ product = products_by_path.get(path)+ if product is None or path in starred_paths:+ continue+ starred_paths.add(path)+ # No href: product URLs live only in the frontend, which fills it in from the product list.+ to_create.append(+ FileSystemShortcut(+ team=team,+ user=user,+ path=path,+ type=product.iconType or product.type or "",+ surface=DEFAULT_SURFACE,+ order=next_order + len(to_create),+ )+ )+ FileSystemShortcut.objects.bulk_create(to_create)++ if not completed:+ _mark_setup_completed(user)diff --git a/posthog/models/file_system/test/test_user_product_list.py b/posthog/models/file_system/test/test_user_product_list.pyindex 73b2e0d5c79d..f20f325baaa7 100644--- a/posthog/models/file_system/test/test_user_product_list.py+++ b/posthog/models/file_system/test/test_user_product_list.py@@ -1,12 +1,18 @@from posthog.test.base import BaseTest+from unittest.mock import patch-from posthog.models import User+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_completedfrom 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 ProductKeyclass TestUserProductList(BaseTest):@@ -56,3 +62,76 @@ class TestUserProductList(BaseTest):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_on_flag", True, False, False, set(DEFAULT_PRODUCT_PATHS), True),+ ("brand_new_user_off_flag", False, False, False, set(), False),+ ("existing_user_mid_migration", True, True, False, set(), False),+ ("user_who_finished_setup", True, True, True, set(DEFAULT_PRODUCT_PATHS), True),+ ]+ )+ def test_default_products_are_starred_only_for_flagged_new_or_finished_users(+ self,+ _name: str,+ flag_enabled: bool,+ 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()++ with patch(+ "posthog.models.file_system.starred_products.posthoganalytics.feature_enabled", return_value=flag_enabled+ ):+ add_default_products_for_user(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")++ with patch("posthog.models.file_system.starred_products.posthoganalytics.feature_enabled", return_value=True):+ 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)++ with patch("posthog.models.file_system.starred_products.posthoganalytics.feature_enabled", return_value=True):+ UserProductList.enable_all_for_user(user, self.team)++ starred = set(self._starred(user))+ assert "Session replay" not in starred+ assert "Product analytics" in starreddiff --git a/posthog/models/file_system/user_product_list.py b/posthog/models/file_system/user_product_list.pyindex ab3b892ff918..a77e824c4978 100644--- a/posthog/models/file_system/user_product_list.py+++ b/posthog/models/file_system/user_product_list.py@@ -7,6 +7,7 @@ from django.db.models.signals import post_savefrom django.dispatch.dispatcher import receiverfrom django.utils import timezone+from posthog.models.file_system.starred_products import star_custom_productsfrom posthog.models.utils import UpdatedMetaFields, UUIDModel, uuid7from posthog.products import Productsfrom posthog.schema_enums import ProductItemCategory, ProductKey@@ -45,12 +46,20 @@ def add_default_products_for_user(user: "User", team: "Team") -> "list[UserProduif 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.- return UserProductList.objects.bulk_create(+ 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:@@ -124,6 +133,12 @@ class UserProductList(UUIDModel, UpdatedMetaFields):# `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,@@ -131,6 +146,9 @@ class UserProductList(UUIDModel, UpdatedMetaFields):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@@ -142,16 +160,21 @@ class UserProductList(UUIDModel, UpdatedMetaFields):if not products:return []+ had_custom_products = user_has_custom_products(user)user_product_lists = []+ added_paths = []for product in products:- item, _ = UserProductList.objects.get_or_create(+ 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_listsdiff --git a/posthog/models/user.py b/posthog/models/user.pyindex 3a28f4868524..8f5294191100 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -226,6 +226,31 @@ def default_ui_configuration_for_new_users() -> dict[str, Any]:}+def preserve_starred_products_setup(+ user: Optional["User"], configuration: Optional[dict[str, Any]]+) -> Optional[dict[str, Any]]:+ """Carry the completed starred products setup into a new configuration that omits it.++ Writers send the whole configuration, so a client that does not know this key (an API call,+ the MCP tool, an older frontend) would otherwise drop it and show the setup again.+ Sending the key explicitly, even as false, still wins.+ """+ stored = user.ui_configuration if user else None+ if not isinstance(stored, dict):+ return configuration+ stored_sidebar = stored.get("sidebar")+ if not (isinstance(stored_sidebar, dict) and stored_sidebar.get("starred_products_setup_completed")):+ return configuration+ if configuration is None:+ return {"version": stored.get("version", 1), "sidebar": {"starred_products_setup_completed": True}}+ sidebar = configuration.get("sidebar") if isinstance(configuration, dict) else None+ if not isinstance(configuration, dict) or not isinstance(sidebar, dict | None):+ return configuration+ if sidebar is not None and "starred_products_setup_completed" in sidebar:+ return configuration+ return {**configuration, "sidebar": {**(sidebar or {}), "starred_products_setup_completed": True}}++class ThemeMode(models.TextChoices):LIGHT = "light", "Light"DARK = "dark", "Dark"diff --git a/posthog/schema.py b/posthog/schema.pyindex a9de74b2ad12..d5eac74e50ec 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -24952,6 +24952,13 @@ class SidebarConfiguration(BaseModel):density: SidebarDensity | None = Field(default=None, description="Row density of the sidebar.")items: SidebarItemsConfiguration | None = Nonesections: SidebarSectionsConfiguration | None = None+ starred_products_setup_completed: bool | None = Field(+ default=None,+ description=(+ "True once the user saved or dismissed the setup that moves their custom"+ " products to starred products in the simple sidebar."+ ),+ )class SurveyCreationSchema(BaseModel):diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 7760d1b2700e..6737dc6115d9 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -154,6 +154,9 @@ tools:file-system-retrieve:operation: file_system_retrieveenabled: false+ file-system-shortcut-bulk-update-create:+ operation: file_system_shortcut_bulk_update_create+ enabled: falsefile-system-shortcut-create:operation: file_system_shortcut_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c682b3d8975c..985e10dc9733 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47781,6 +47781,40 @@ export namespace Schemas {readonly user_access_level: string | null;}+ export interface FileSystemShortcutBulkItem {+ /** Display path of the shortcut in the sidebar. */+ path: string;+ /**+ * Type of the linked item (e.g. 'folder', 'insight'), or blank.+ * @maxLength 100+ */+ type?: string;+ /**+ * Reference to the linked item, scoped to its type. Null for href-only shortcuts.+ * @maxLength 4000+ * @nullable+ */+ ref?: string | null;+ /**+ * Destination URL the shortcut opens. Null when the shortcut points at an item by ref.+ * @nullable+ */+ href?: string | null;+ }++ export interface FileSystemShortcutBulkUpdate {+ /**+ * Shortcuts to create, appended to the end of the current order in the given sequence. An item identical to a shortcut the user already has is skipped.+ * @maxItems 500+ */+ add?: FileSystemShortcutBulkItem[];+ /**+ * IDs of the current user's shortcuts to delete.+ * @maxItems 500+ */+ remove_ids?: string[];+ }+export interface FileSystemShortcutReorder {/** IDs of the current user's shortcuts in the desired display order. */ordered_ids: string[];@@ -70229,7 +70263,7 @@ export namespace Schemas {passkeys_enabled_for_2fa?: boolean | null;/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */hide_mcp_hints?: boolean;- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. */+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */ui_configuration?: unknown;/** @nullable */readonly onboarding_skipped_at: string | null;@@ -79667,7 +79701,7 @@ export namespace Schemas {passkeys_enabled_for_2fa?: boolean | null;/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */hide_mcp_hints?: boolean;- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. */+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */ui_configuration?: unknown;/** @nullable */readonly onboarding_skipped_at?: string | null;diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex a74df57b0433..68f35bbfb3f7 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -5524,6 +5524,6 @@ export const UsersPartialUpdateBody = () => zod.object({.unknown().optional().describe(- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.jsonindex db140c7bd8e1..a0173aeb77df 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json@@ -150,7 +150,7 @@]},"ui_configuration": {- "description": "Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown."+ "description": "Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true."},"uuid": {"description": "User UUID, or `@me` to target the authenticated user.",