:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(customer-analytics): restore current saved views (#112756)
Arthur Moreira de Deus2a72d1bf9cba
diff --git a/docs/internal/customer-analytics/accounts-table.md b/docs/internal/customer-analytics/accounts-table.mdindex 0c5fcb6a1fd8..52665a11bacb 100644--- a/docs/internal/customer-analytics/accounts-table.md+++ b/docs/internal/customer-analytics/accounts-table.md@@ -19,45 +19,63 @@ Other query types keep their existing global or scene-specific concurrency limit## Unsaved filters and views-The Accounts list keeps unsaved filters when a user opens an account and returns to the list.-The draft includes search, tags, assignment filters, account property and relationship filters, and the selected overview tile filter.+The Accounts list keeps unsaved changes in memory while the user edits the list.+Only the Back link on an account details page can restore those changes after navigation.+Other navigation, including tabs, the sidebar, browser Back, and page reloads, discards them and loads the current saved view.+Save or update a view to keep its filters, sorting, columns, column display settings, and overview tiles.+Neither browser storage nor the URL stores an unsaved view snapshot.+Column widths remain a separate browser preference.+Account property, relationship, and custom-property filters can be placed in OR groups.Filters within each group use AND, while search, tags, assignment status, and selected overview tile filters apply to every group.-Saved views and shared links keep the groups; older views without groups retain their AND behavior.-A group that filters on churned or ignored accounts includes them only in that group; other groups still exclude them by default.+Saved views keep the groups. Older views without groups retain their AND behavior.+A group that filters on churned or ignored accounts includes them only in that group. Other groups still exclude them by default.When a saved condition refers to a deleted property, the list keeps the valid conditions in that group.-It also keeps sorting, selected columns, column display settings, and overview tile settings.The toolbar keeps a Filters button with a spaced, theme-aware accent count. The button highlights while the compact groups are open in a bordered area below it.Restored filters start collapsed. Relationship pills show member names using the same member list as the value picker. Adding the first condition opens the groups, and removing the last group restores the Filter button.Empty OR groups do not affect results. Search, tags, and assignment controls remain outside the editor.-The browser stores one draft per project and user in `sessionStorage`.-Draft restoration waits for the loaded project and user IDs before deciding whether to apply a saved view.-Automatic column updates do not replace the pending draft with default URL state.-The draft survives list remounts and page reloads in the same tab.-It does not update a saved view or store account rows.-Closing the browser tab ends the draft session.--Restoration uses this order:+### Saved-view links and restoration-1. An explicit `#view` in the URL takes priority over the draft, including an empty view.-2. Without a view hash, the list restores the draft.-3. Without a draft, the list restores the last selected saved view, if available.-4. Otherwise, the list uses its defaults and the shared My accounts preference.+The Accounts URL identifies a saved view with `?view=<id>`.+A copied link loads that view's current saved configuration, not the sender's unsaved changes.+Renaming a view does not change its link.+The browser remembers only the last selected saved-view ID and name for each project and user.+The picker shows that name immediately and keeps the same button while the current saved definition loads.+Filters, columns, sorting, and tiles still come from the server, never from the name cache.+A missing saved view clears the cached selection.-On a fresh tab, restoring the My accounts preference does not create a draft or mark default columns as a restored selection.-Draft and URL writes wait while the last selected saved view loads, then store the resolved view.-Relationship definitions can load before or after saved views without replacing saved columns.+On a fresh load, restoration uses this order:-Selecting a saved view replaces the draft.-Clearing filters keeps them cleared on return, even when a saved view remains selected.-Saving or updating a view still requires an explicit action.-If browser storage is unavailable or invalid, the list uses URL state and saved views without failing.+1. An explicit `?view=<id>` selects the saved view.+2. Without an explicit selection, the list restores the remembered saved view.+3. Without an available saved view, the list uses its defaults.-`accountsLogic.viewState` supplies the shared snapshot for drafts and saved views.-`applyViewState` restores it without intermediate URL writes.-The parent scene preserves the view hash when changing date or test-account filters.+Accounts and Notes have independent My accounts filters.+Changing one does not change the other, including when switching tabs.+Removing My accounts on the Accounts list restores all assignment statuses.+Fresh Accounts loads do not restore unsaved filters or the Notes preference.+Saved-view restoration waits for the project, user, and saved configuration to resolve before issuing list and overview queries.+Relationship definitions can load before or after saved views without replacing saved columns.+A missing or inaccessible view clears the stale selection and uses defaults.+A failed view request offers a retry and does not make the default configuration appear modified.++Selecting another saved view replaces the working configuration.+Opening an account from the list prepares a one-use return link for its Back button.+The link contains the saved view ID, existing scene parameters, and an opaque `restore_view` token. It never contains filters or a view snapshot.+The token only restores an in-memory return in the same app context and is removed from the URL after use.+Copied links, reloads, and reused tokens load the current saved definition instead.+A pristine view also reloads its current saved definition on Back, so a teammate's updates do not appear as unsaved edits.+Other navigation keeps the selected view but discards unsaved changes. An explicit different view ID changes the selection.+Later background view loads do not replace unsaved changes.+Saving or updating a view requires an explicit action.++Existing `#view` snapshot links remain readable for compatibility, but the list no longer creates them.+An explicit query-string view ID takes precedence over a legacy snapshot.+Browser storage failures do not prevent URL-based selection.+`accountsLogic.viewState` supplies the snapshot for working state and explicit saves.+The parent scene preserves the selected view ID when changing date or test-account filters.## Sortingdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 58371aed2c91..01d15b0b91c4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9051,9 +9051,9 @@ snapshots:scenes-app-customer-analytics-accounts--default--light:hash: v1.k794b7964.b986d24c5b87d97314d1b6fcd605ef453d56ffef2c2f3d6408722db977cf1fb2.1CjtHSZqb1ZDLB_hE3PLlIdf4IE4oCpn_BhAJh_DsQsscenes-app-customer-analytics-accounts--empty--dark:- hash: v1.k794b7964.962ba84279119ab92e48c352b1e1b39084c5a1d267d65c54af790cd79fae2b59.oyN7WtxCxnFN2f5NJ2B2VNlAxmwQvnJcS_qUZhAPdFg+ hash: v1.k794b7964.18ac61ed7b3d137383c186f9bf6c01102450b68b6917cff3c38f333e64e558ad.IFxN4UNACbR2jEHzs_MoFffKZLp66e_dXcqmUg3bwtgscenes-app-customer-analytics-accounts--empty--light:- hash: v1.k794b7964.ed8345063a6d0a3e9a548c29f573e2e0627e0eabe1a70b0ba81fdd5ec4bf3852.G0-FgLIKE5A8w4SXzTCZR6J3snyELXCznWipjnmHz64+ hash: v1.k794b7964.a2b54f86ca89b480be11def548d44c765746bd433f8c1bc9d9d677c52dd43002.QR-p3RM4mkWRbwa5wPD9L2LN0M81xulXbEoMz-ppioIscenes-app-customer-analytics-accounts--feature-gate-off--dark:hash: v1.k794b7964.4b8d5226ee154debdf333ff93d65a90ca766bcb25951e1baf36affb8b84b548d.dWZSHssPc83RkHVE-JPJA562bJR7MUim2yfqhjfNE50scenes-app-customer-analytics-accounts--feature-gate-off--light:@@ -9075,45 +9075,45 @@ snapshots:scenes-app-customer-analytics-accounts--many-columns--light:hash: v1.k794b7964.0a2ee3a18a52f0b113c8e5630d9741677ce20e541a434b61237525987ae987c1.qhY5hAKOEmpx-dh1vti-vt7RtucjvftEc1F0DRtNR9gscenes-app-customer-analytics-accounts--row-expanded-conversations--dark:- hash: v1.k794b7964.bd5d33f06635b1fa2ac401e370dfad9e7c125e349f41bd172cafb5e38aeab721.7jRlvWfxiKE6Dp9YRZQ9MWzbZlKypIJd7WQbE-Zscjw+ hash: v1.k794b7964.3785660eec8df6446a949624f3ce5c94c78f3c904cffbe3b55645d8a3583f038.-IUZSILyClTbcALcY8zkTdVNM6zQ7EJR1hB0hI6c898scenes-app-customer-analytics-accounts--row-expanded-conversations--light:- hash: v1.k794b7964.fb56da84bf7207f04b189874dde79eb0e001e5e370429a9796b1e4c0b3d0099f.LYDaaQIU0fct9Q-q-hTr6r4XWlbHRqAfhRQ1bL2KCQE+ hash: v1.k794b7964.43a01f4a4ead1fec72e5bc47945d227f17157ce70aa4565475b4b46d966bb2a1.6-oGLB4OLJnRExymO2QXEM_kF9NnO-u-V2XMNbM66HUscenes-app-customer-analytics-accounts--row-expanded-empty--dark:- hash: v1.k794b7964.090b5451367cbc88e18653dc1899467cefe5f44e55d181a4837a9ba028e30ead.PMoKZW79l2Ve6A_haEZtirAB2EbBXGoQylPzm1jUyb0+ hash: v1.k794b7964.3615675b18f3db9ac2f0d386b58065793700eaef36eab726a192222cd7330169.nsjBIWfimBlqnxFeB5EVFA7LzeA-8-EBT-TWO4OsZbMscenes-app-customer-analytics-accounts--row-expanded-empty--light:- hash: v1.k794b7964.a91ffd7fc2442f3dbb6be4c84701345b72b2359420cc7e6f9039a1ac5ff4d063.c7Tg3Wa9BIaqhkxnOPPDAZcfAX5amRz2xlcK33TVvg0+ hash: v1.k794b7964.7149c6499214827ce4f14da8b81c7bbd91696c2c8a07e205f4e39ad215eb7c57.5s9-ULWQdoYaeL7mbBz6nx7z4J1TQQ5QQmTpcJ-meDkscenes-app-customer-analytics-accounts--row-expanded-feature-requests--dark:- hash: v1.k794b7964.ecbed5422bc8cd789bf9b455cf0ddecb47092d3da59dcd28ad47c83afac648ba.1rDHj438lRhPOmE_J7QHobW6I0fx318RqMK3PIEBFns+ hash: v1.k794b7964.806735fe8f0ba3151885b31eddfe7ba1fccefd67d2135aea432516b0eb0f752e.LPRlUkesd74SW7IktEQuP8FmsAu2fVl1TMNMBzfnmVMscenes-app-customer-analytics-accounts--row-expanded-feature-requests--light:- hash: v1.k794b7964.99974e44f77fc4ed83a182763355f604cbdc3a85b5cca849a8cacc410a655346.BDjnpHkdZ-V2_x74U-Y8UBRNUe_XBHnXB8PUP_iaWVU+ hash: v1.k794b7964.350c989f63860e493d19a9029ac30faa775d5fd6909aa14f3b48f0938827b7b3.WXL5E3WgAx43uPz_n_HTtMjNJG9KIuA8wF88l0TRmrAscenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:- hash: v1.k794b7964.4c0c753752f96153f8d35b0a0e276223e56f31c473f05bfd045dc65afebc8a93.uXxcKILaw61jSsFBo6h6uH7Udwu2esrWIEpAuKxlE7Y+ hash: v1.k794b7964.ee9c2124f27fc0c3fc80a127c4f30986dabbc6b8dc694ed69eaa70ab801953f2.01sZjNxj3w-jB3sQJyHtbPLETKV4ZSw2VvQbdbmbhs8scenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:- hash: v1.k794b7964.3357c1d1e85dcf873b250fe5cc19f695a5d82301ac2bf5dc8c71b9c48993ef5a.Ni88T6lNxljQO27P-1Sr9qGkehA6tN-pcrI93tPO634+ hash: v1.k794b7964.152d3710f1327d20dd59b31d7354d942a7fe31c763ff2405c1551c82f066371f.g72oNf8o6gS0ThkWFkpHFiXWdPml-N0jGD_ZmNCJrv8scenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--dark:- hash: v1.k794b7964.88c560218198aeef0e61775c4b3087f7a0111d53d4aa9873e7e28c8df7cedbe9.KVXryNv9x89Q3hGic4DdnU-ALGPGQ6dzMqnrQ--frIw+ hash: v1.k794b7964.2e8ce35ca61c66178b0ad43e43ca4a1f281f9178d25c16635fda3e813ccbead7.4u4xqor2VQNjmUfXRG4N01bRy0je3WJwEOvkCCw3UzUscenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--light:- hash: v1.k794b7964.d1bbe7fadec01dcf5468bc307e5ddaf120c0a05cf354a8107be95a3d08cba094.a-jmv3Srry1RzTZNouTKL2SWYazNQqcwBvP2fWbCGgE+ hash: v1.k794b7964.d65be977673cf9d1e964e06a6ac3795c7b13a9ad3327205b691f7bf51013432a.P3OmF9kb8NA0DJkXm5dgvJBnlqt1bOA53XjNNnAL-LEscenes-app-customer-analytics-accounts--row-expanded-pinned-properties--dark:- hash: v1.k794b7964.1a6a6a811b74d997851b9eb81d93c0c5a5c75cbbcdd9c4a81535da756f308847.mP5q4EFqTMDAID3pFx24qLVCfviBoaNmqN6xxDOJUqs+ hash: v1.k794b7964.e75e428a8349099de2a6d4ba11a0e9194ebbaa66fbacdc93d7ad3f9de8738794.bc5odeBTDWUq_i3QU3c2e-pkMMtVkE0HFDRbywVF8Q4scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--light:- hash: v1.k794b7964.95fda5852833bb19b7d0ec626dbe228297c6296c179215f69f835f5c76fb740f.PHQ2Hjp_qXXmXMYGCkY-E-ULQaNfEQ3zYZMg6Rn44ls+ hash: v1.k794b7964.908141790d32f0ab4f121ef7017e3517e8b75e9a7ab42b0aed03c2ed603699e8.cKUBb78WLf4UoYzbDiSQHl86Gp2csnyj-Rojd0lQ7L0scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--dark:- hash: v1.k794b7964.48fbedcb90e1b63a9f3472a750d84a9aed6226671a529eaacf20c832dd33be29.dPfzWKCqVueqTXahDik4Xgw_2dxOau-s9rE-AMbHegQ+ hash: v1.k794b7964.435947035814f0d3457b1a5204956987f9df29ee3e6b8a45c1ea29314b3c8d9f.gPFCq4S1UYOe0bgG_e8iVR10sNOiiLGk0CQquB6Uklwscenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--light:- hash: v1.k794b7964.5a08aeda76cd76b0203cdfaa8976522682bc1e83c70e62e4707f2b04cffb0634.zh56uPyuehDrM76JRt6h_aO3DdwqMUhE14dAx8BsUJ8+ hash: v1.k794b7964.e815e72a43a321670d01c2a603288e9ff5392c8d561512965f3992b7b9c6814f.e2jyDW8y_bLMcnqQ8b9To4XTpvAATpowuxUeXSL-h9Escenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--dark:hash: v1.k794b7964.a810538ef741184c82d24d8c00f44494a0da2d3e086a4eb3229e6549a922b7e3.8hdyPnDByKor8aXfR01h8gkn2vLfhRLG1dvksykXCCIscenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--light:hash: v1.k794b7964.cedd8bbe22b7d3e236b784e1d018d007a12f51f3676d6133f912f1c4e9b265c7.l-utJ4fsDPlG6aoWvqqeBtLmgQGG_7qCvyaFF1ZtFW4scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:- hash: v1.k794b7964.c52ec75dc9d1a1395448ca3a58bba70b8c43f8b676bff58dbdd7ae681256047a.PyQHfa6BWGInmt3T2c_8rZdl_ZO3Gi3Ruz7cOh-MGAI+ hash: v1.k794b7964.76389eaa3764f04933a9708c10c7551316e070f7a3cebf1c8e2d4e0e9fc626e4.5R7QgO5WJok3lg72hJbhNSvCqdAuh2pCo6_LsNJLZgQscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:- hash: v1.k794b7964.73d08c83fef42b5b86dec4fb6f3dc84fc57df10b313b8619ff0c6c84acb3020e.TevpXsaRG7pu0pfk54MXqGyijremhfP0HTZ5MHZ1kHQ+ hash: v1.k794b7964.fe93b898fc1ce33a4d06e670beca82e119d56a8a0a7cd14b663bf2fd43eed8e4.7EgB-106nV6Cgapi_SKZ26Gwie4h8APpOoVO1j1v2TAscenes-app-customer-analytics-accounts--row-expanded-with-note--dark:- hash: v1.k794b7964.e8866368c6f77514a1668f447c4286cb54223561a75532cd9b3dbe635153ff0d.4XhzwWuCbAiOobD5GWyLEFqLucISfDr0gvaFXDbSZME+ hash: v1.k794b7964.aaf5a471c675054d81314b5210fb0e730aa081722bf0996d1fad1e915b1ead48.2i9sg0kwmGcqrGypey-Bsx6OZDI6fcINxle0ow2435Yscenes-app-customer-analytics-accounts--row-expanded-with-note--light:- hash: v1.k794b7964.d2eba0241e41de35bea04e4de46914e70df9f95f48e3a28f31a85b313b3a5663.hMr_iWK7eUn2kq7m4pvVnB7BcOHg_--Yv7fphuUrhwo+ hash: v1.k794b7964.2f7a262166d6041d488d687f21e907be86bf7dd657ae38ee8cffb01a2260f9d1.h2llIuhAvIb7sAwlwqJlJxZogyeN_0-oO03WpxbVb6Iscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:hash: v1.k794b7964.676001075ee700388d9cdd0c7ec45430e7fc40c5b7aedbb7e26efe0e01ccee30.9lZ1hXCdIHbJEf7RqEWimEYspfWdC8UsIE8LKrK6c7cscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex c90ef6edde00..8e48d31d6b2c 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -43,8 +43,8 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc| Logic | Owns || ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `accountsLogic` | The hub. Search (debounced), tag / assignment-status (the canonical `assignmentStatus`: `all` \| `assigned` \| `unassigned`, default `all`) + assigned-to / native-field / relationship / custom-property filters, sort, inline role and custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). Canonical and warehouse-backed property values are read-only. Workflow-backed properties stay editable, but a future workflow run overwrites a manual value. `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select) and browser-persisted column widths. Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsLogic` | The hub. Search (debounced), tag / assignment-status (the canonical `assignmentStatus`: `all` \| `assigned` \| `unassigned`, default `all`) + assigned-to / native-field / relationship / custom-property filters, sort, inline role and custom-property assignment, typed Postgres list and metrics queries, in-memory working view state, saved-view URL references, and `openAccount` (the Max entry point). Canonical and warehouse-backed property values are read-only. Workflow-backed properties stay editable, but a future workflow run overwrites a manual value. `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select), URL references, remembered view IDs, and browser-persisted column widths. It owns `ColumnConfiguration` reads and writes. `accountsViewSessionLogic` holds the project-and-user-scoped working state across scene unmounts and discards it on identity changes. || `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. || `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. || `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |@@ -81,7 +81,7 @@ The shared `AccountAssignmentFilter` in `frontend/src/lib/components/` renders t`accountsTableQuery.ts` maps each status to a query filter: `all` omits the assignment filter entirely (both assigned and unassigned show), `assigned` emits `{ kind: 'assigned' }`, and `unassigned` emits `{ kind: 'unassigned' }`.Selecting users or checking "My accounts" narrows the assigned status to those user ids (`{ kind: 'assigned_to' }`) — both force the status to `assigned`; leaving the assigned status clears the user list.Legacy compatibility: a saved view or shared link created before this field defaulted to assigned-only, so any persisted filters object with no `assignmentStatus` resolves to `assigned` (an old `unassigned: true` resolves to `unassigned`) — they never silently broaden to `all`.-New saved views always store `assignmentStatus`; in the URL hash the default `all` is only written once another filter is present (so a pure-default view keeps an empty hash), and an empty hash restores as `all`.+New saved views always store `assignmentStatus`. Fresh list defaults use `all`. Legacy snapshot links remain readable, but new links identify a saved view with `?view=<id>`.Overview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:@@ -116,7 +116,7 @@ The Postgres runner returns `{ timestamp, value }` history points ascending (witFewer than 2 in-window points falls back to rendering the latest value plainly.The config persists per view via `ColumnConfiguration.properties.column_display` (round-tripped in `accountsViewState.ts`), and sorting uses the scalar custom property even when the displayed cell loads history.-**Account filters** live in `AccountsFilterGroups`, using a selected `LemonButton` with a spaced accent-colored count and compact `LemonCard` groups without headings inside a bordered filter area. Restored filters start collapsed. The shared `PropertyFilterButton` resolves relationship values through `membersLogic`, matching the member picker. The empty state shows only the shared Filter trigger; completing the first condition expands the editor. Removing the first group promotes the next branch via `removeFirstAccountFilterGroup`. Collapse is local presentation state and does not change saved filters. They reuse `PropertyFilters` for each OR branch; filters within a branch use AND. The first branch keeps the legacy flat `accountFilters` state, and further branches live in `accountFilterGroups`. Each branch offers native Account fields, Account relationships, and Account custom properties. Search, tags, assignment status, and tile filters remain global AND restrictions. The query planner sends multiple nonempty branches as `filterGroups` to the Postgres runner. Saved views, shared URL hashes, and session drafts persist the branches; legacy flat views keep their AND behavior.+**Account filters** live in `AccountsFilterGroups`, using a selected `LemonButton` with a spaced accent-colored count and compact `LemonCard` groups without headings inside a bordered filter area. Restored filters start collapsed. The shared `PropertyFilterButton` resolves relationship values through `membersLogic`, matching the member picker. The empty state shows only the shared Filter trigger; completing the first condition expands the editor. Removing the first group promotes the next branch via `removeFirstAccountFilterGroup`. Collapse is local presentation state and does not change saved filters. They reuse `PropertyFilters` for each OR branch; filters within a branch use AND. The first branch keeps the legacy flat `accountFilters` state, and further branches live in `accountFilterGroups`. Each branch offers native Account fields, Account relationships, and Account custom properties. Search, tags, assignment status, and tile filters remain global AND restrictions. The query planner sends multiple nonempty branches as `filterGroups` to the Postgres runner. Saved views persist the branches, and in-memory working state keeps unsaved branches during navigation. Legacy flat views and snapshot links keep their AND behavior.Relationship options come from the team's relationship definitions. They use the shared member picker and support matching a specific member, excluding a member, and checking whether a relationship is assigned.Native fields cover names, external and connection IDs, created and updated timestamps, and the `churned_at` and `ignored_at` lifecycle timestamps. Text fields support exact, negative, contains, and set operators. Timestamp fields support exact date, before, after, and set operators. A lifecycle timestamp filter with any operator except `is not set` lifts both default hides before applying its predicate, so `Ignored at is set` returns every ignored account, churned ones included, while an unfiltered list still hides them. Track Rules skip churned accounts, so a churned account keeps its `ignored_at`.Custom property options come from `accountsColumnConfigLogic.customPropertyTaxonomicOptions` via `optionsFromProp`. The filter `key` is the stable definition ID, and the definition name rides on the filter's `label` for display.@@ -252,24 +252,25 @@ The Notes tab is server-paginated, searchable, and sortable (all via `accountNot## Shareable view state-`accountsLogic` mirrors the full view (search, tags, assignment status, assigned-to, native-field and custom-property filters, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Column widths stay in browser-local preferences instead of the URL because they are display preferences. Only non-default values are serialized. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).--A list URL without a `#view=` hash must not erase the shared "mine only" toggle.-The tab link, account breadcrumb, and older history entries can return to the list without a view hash.-`restoreViewStateFromRoute` restores the session draft first. Without a draft, it uses the shared `mineOnly` preference.-Resolve assignment intent before calling `applyViewState`, because assignment setters also update the shared preference.-For the same reason, anything that rewrites the Customer analytics URL (the scene's date and test-account writers in `customerAnalyticsSceneLogic`) must carry the current hash through.--### Unsaved drafts--`accountsLogic.viewState` owns the full snapshot used by session drafts and saved views.-`applyViewState` restores the snapshot without intermediate URL writes.-Drafts use project-and-user-scoped `sessionStorage`, including cleared filters and unsaved changes to a selected view.-The draft key comes from loaded `teamLogic` and `userLogic` state. Draft hydration and automatic saved-view restoration wait for both IDs.-An explicit shared URL wins over the draft. The draft wins over automatic saved-view restoration.-Restoring only the My accounts preference keeps column initialization active and does not create a fallback draft.-While `awaitingSavedView` is true, draft and URL writes wait for the saved-view decision.-Selecting a saved view explicitly replaces the draft.+The Accounts list uses `?view=<id>` to identify a saved view.+Opening that link fresh loads the current saved definition, not the sender's unsaved changes.+The query-string ID takes precedence over the remembered selection and any legacy `#view` snapshot.+New links never serialize filters, columns, sorting, or overview tiles.+Existing snapshot links remain readable for compatibility.+Account detail paths and unrelated date or test-account parameters remain intact.++### Unsaved changes++`accountsLogic.viewState` supplies the working snapshot and explicit saved-view payload.+Unsaved changes stay in project-and-user-scoped memory only while editing the list or using its account-detail Back link.+Normal navigation discards them and reloads the saved definition. Neither localStorage nor sessionStorage stores a working snapshot.+`prepareAccountReturn` captures a dirty view in memory before an ordinary account-name click. The detail breadcrumb includes a one-use `restore_view` token, never serialized filters.+The list consumes the token and removes it from the URL. Pristine views, copied or reused tokens, reloads, browser Back, and other navigation load the saved definition instead.+Accounts never reads or writes the Notes `mineOnly` preference. The two My accounts filters are independent.+Removing Accounts My accounts returns `assignmentStatus` to `all`.+Selecting a saved view replaces the working state, but background view loads do not replace later edits.+Initial list and overview queries wait for the saved-view decision.+Column widths remain an independent browser preference.See [Accounts table](../../../../../docs/internal/customer-analytics/accounts-table.md) when changing persistence or navigation.### Deep-link to one account (path route)@@ -280,14 +281,9 @@ Returning to the bare `/customer_analytics/accounts` clears `accountIdFilter`.Because it filters by the PK, the id alone is enough; no name/external_id is needed in the link.A set `accountIdFilter` **replaces** the rest of the query's filters rather than ANDing with them: `applyAccountFilters` emits `toString(id) = '<id>'` alone and returns.-A deep link has to resolve to its account for whoever opens it, and the viewer's own filters (a restored saved view, the localStorage-persisted "my accounts" toggle) would otherwise exclude it and land them on an empty list.--Two things conspire to bounce a deep link back to the unfiltered list, so keep both in mind when touching URL sync:--- `actionToUrl` mirrors view state into the hash on ~14 setters, and those setters also fire while state is being _restored_ (the default-column upgrade once relationship definitions load, `accountsViewsLogic`'s auto-restored saved view) — not just on user edits.- So it writes back to `accountsPathToWriteBackTo(accountIdFilter)`, the path we are already on, never a hardcoded list path.-- Because the deep-link path can therefore carry a `#view=` hash, its `urlToAction` handlers restore that hash too — but only when one is present.- An absent hash there means "just open the account", not "reset the list".+A deep link has to resolve to its account for whoever opens it. The viewer's saved or working filters must not exclude that account.+Saved-view URL writes keep the current account path, never navigate to a hardcoded list path.+An account detail route keeps a prepared return snapshot until the detail Back link consumes it or another navigation discards it.**Build the URL via the canonical helpers, never hand-build the path:**@@ -315,13 +311,17 @@ Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer**Visibility** is `private` or `shared`. The owner can see and change a private view. Any team member who can see a shared view can edit or delete it. When a team member makes a shared view private, the view becomes that member's private view.-**Auto-restore:** the last-used view `id` is persisted in a team-scoped localStorage key (`currentViewId`).-A shared link's `#view=` URL hash or a session draft takes priority over the saved `currentViewId`.-When saved views exist but the viewer has no last-used view, the selector remains available without applying a view automatically.-`isDirty` is true when the live state diverges from the selected view's saved state.+**Auto-restore:** localStorage remembers the last-used view ID and name, scoped to the project and user.+The existing key accepts legacy ID strings and new `{ id, name }` objects. It never stores view contents.+The picker renders the cached name while loading and hydrates without replacing its button.+An explicit `?view=<id>` takes priority. Fresh loads fetch the current saved definition before applying it.+Bare list navigation, including the sidebar entry, preserves the selection but discards unsaved working state.+The existing team-scoped remembered ID migrates only when it identifies a view the user can access.+A missing or inaccessible view clears the stale selection and uses defaults. Load failures offer retry without marking defaults dirty.+When the viewer has no last-used view, the selector remains available without applying one automatically.+`isDirty` is true when the working state diverges from the selected view's saved state.-**One-time tiles migration:** on first load, if the signed-in user is the creator of the existing default `ColumnConfiguration` row and its `properties.tiles` is empty while their localStorage tiles differ from `DEFAULT_TILES`, `accountsViewsLogic` patches the localStorage tiles into that row.-The operation is idempotent and skips non-creators.+**Overview tiles:** the saved view's `properties.tiles` owns the configuration. Restoring a view never patches browser-local tiles into a saved row.**Column configurator:** `AccountsColumnConfigurator.tsx` no longer persists columns itself — "Done" closes only.Column changes are saved as part of a view via `AccountsViewSelector.tsx` (the view dropdown in `AccountsTabFilters`), which offers "Save current view" (creates) and "Update '<name>'" (patches the selected view).@@ -399,7 +399,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed || `customer analytics accounts view saved` | `accountsViewsLogic` `submitViewForm` listener after a create succeeds | `visibility` (`private` \| `shared`) || `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener after content or metadata changes | _(none)_ |-| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |+| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener on explicit selection or saved-view restoration | `visibility` || `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ || `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end \| `account_sidebar` or `list_expansion` from shared-field edits) || `customer analytics accounts relationship deleted` | `accountRelationshipsLogic` `deleteRelationship` listener (after the DELETE succeeds) | _(none - count only; relationship and account identifiers stay out)_ |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 09843407f64a..06fc5c0be80a 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -20,6 +20,7 @@ import type {import { ACCOUNTS_DEFAULT_COLUMNS, customPropertyAlias } from './accountsColumnConfigLogic'const QUERY_ENDPOINT = '/api/projects/:team_id/accounts_table_query/'+const COLUMN_CONFIGURATIONS_ENDPOINT = 'api/projects/:team_id/column_configurations/'const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'const ACCOUNT_EMAIL_THREADS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/email_threads/'@@ -246,10 +247,14 @@ function expandedRowDecorators(async function expandFirstRow(canvasElement: HTMLElement): Promise<void> {const canvas = within(canvasElement)// Generous first wait: the whole scene mounts and the accounts query resolves before rows exist.- await canvas.findByTitle('Show more', {}, { timeout: 15000 })+ const accountName = await canvas.findByText('Acme Inc', {}, { timeout: 15000 })+ const row = accountName.closest('tr')+ if (!row) {+ throw new Error('Account row did not render')+ }for (let attempt = 0; attempt < 3; attempt++) {if (!canvasElement.querySelector('[data-attr="account-expansion"]')) {- await userEvent.click(await canvas.findByTitle('Show more'))+ await userEvent.click(await within(row).findByTitle('Show more'))}try {await waitFor(@@ -343,6 +348,7 @@ const meta: Meta = {mswDecorator({get: {[WAREHOUSE_VIEW_LINK_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [COLUMN_CONFIGURATIONS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },[RELATIONSHIP_DEFINITIONS_ENDPOINT]: RELATIONSHIP_DEFINITIONS,[ACCOUNT_ICON_ENDPOINT]: mockAccountIcon,},@@ -781,8 +787,12 @@ function pinnedRowDecorators(overrides: Mocks['get'] = {}): ReturnType<typeof msasync function expandPinnedRow(canvasElement: HTMLElement): Promise<HTMLElement> {const canvas = within(canvasElement)- await canvas.findByText('Acme Inc', {}, { timeout: 15000 })- await userEvent.click(await canvas.findByTitle('Show more'))+ const accountName = await canvas.findByText('Acme Inc', {}, { timeout: 15000 })+ const row = accountName.closest('tr')+ if (!row) {+ throw new Error('Account row did not render')+ }+ await userEvent.click(await within(row).findByTitle('Show more'))return await waitFor(() => {const expansion = canvasElement.querySelector<HTMLElement>(PINNED_EXPANSION_SELECTOR)if (!expansion) {diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsxindex 4e642fa9c4e4..3ddb6535675a 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx@@ -1,6 +1,8 @@+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'+import '@testing-library/jest-dom'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { BindLogic, Provider } from 'kea'import { userLogic } from 'scenes/userLogic'@@ -15,28 +17,34 @@ import type { ColumnConfigurationApi } from 'products/product_analytics/frontendimport { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'import { accountsLogic } from './accountsLogic'import { AccountsTabFilters } from './AccountsTabFilters'+import { accountsViewsLogic } from './accountsViewsLogic'+import { accountsViewIdStorageKey } from './accountsViewState'describe('AccountsTabFilters', () => {let logic: ReturnType<typeof accountsLogic.build>let savedViews: ColumnConfigurationApi[]let tagsRequest: jest.Mock+ let viewsRequest: jest.Mock+ let manualViewsLogic: ReturnType<typeof accountsViewsLogic.build> | nullbeforeEach(() => {+ manualViewsLogic = nullsavedViews = []tagsRequest = jest.fn(() => [200, ['enterprise']])+ viewsRequest = jest.fn(() => [200, { count: savedViews.length, results: savedViews }])useMocks({get: {'/api/organizations/:organization_id/members/': () => [200, { results: [] }],'/api/projects/:team_id/tags': tagsRequest,- '/api/projects/:team_id/column_configurations': () => [- 200,- { count: savedViews.length, results: savedViews },- ],+ '/api/projects/:team_id/column_configurations': viewsRequest,},})+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ current_team: MOCK_DEFAULT_TEAM,+ current_user: MOCK_DEFAULT_USER,+ } as anyinitKeaTests()- // The shared "my accounts" (mineOnly) toggle persists to localStorage; clear it so a- // value set by one test can't bleed into the next (which would pre-check the checkbox).localStorage.clear()logic = accountsLogic()logic.mount()@@ -45,6 +53,7 @@ describe('AccountsTabFilters', () => {afterEach(() => {logic.unmount()cleanup()+ manualViewsLogic?.unmount()localStorage.clear()})@@ -101,6 +110,48 @@ describe('AccountsTabFilters', () => {expect(screen.getByDisplayValue('Shared accounts')).toBeInTheDocument()})+ it.each([true, false])(+ 'renders the cached picker immediately and hydrates without showing Save current view (exists=%s)',+ async (exists) => {+ const view: ColumnConfigurationApi = {+ id: 'cached-view',+ context_key: 'customer_analytics_accounts_columns',+ columns: ['name'],+ name: 'Cached accounts',+ filters: { assignmentStatus: 'all' },+ order_by: [],+ properties: {},+ visibility: 'shared',+ created_by: MOCK_DEFAULT_USER.id,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+ savedViews = exists ? [view] : [{ ...view, id: 'other-view', name: 'Other view' }]+ localStorage.setItem(+ accountsViewIdStorageKey(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid),+ JSON.stringify({ id: view.id, name: view.name })+ )+ let release!: () => void+ const pending = new Promise<void>((resolve) => {+ release = resolve+ })+ viewsRequest.mockImplementationOnce(async () => {+ await pending+ return [200, { count: savedViews.length, results: savedViews }]+ })+ renderFilters()+ const initialSelector = screen.getByText('Cached accounts').closest('button')+ expect(initialSelector).toBeInTheDocument()+ expect(screen.queryByText('Save current view')).not.toBeInTheDocument()++ await act(async () => release())+ await waitFor(() => expect(accountsViewsLogic.values.viewsLoaded).toBe(true))+ expect(screen.getByText(exists ? 'Cached accounts' : 'Select view').closest('button')).toBe(initialSelector)+ expect(screen.queryByText('Save current view')).not.toBeInTheDocument()+ expect(document.querySelector('[data-attr="accounts-update-view"]')).toBeNull()+ }+ )+it('loads existing tags when the tag filter opens', async () => {renderFilters()@@ -119,21 +170,25 @@ describe('AccountsTabFilters', () => {})it('reflects a restored my-accounts filter as checked', () => {- userLogic.actions.loadUserSuccess({ id: 42 } as unknown as UserType)+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, id: 42 } as unknown as UserType)logic.actions.setAssignedToCurrentUser(true)renderFilters()expect(myAccountsCheckbox().checked).toBe(true)})- it('clicking it enables the my-accounts filter (resolved to the current user id)', () => {- userLogic.actions.loadUserSuccess({ id: 42 } as unknown as UserType)+ it('clicking My accounts filters to the current user and removing it restores all assignment statuses', () => {+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, id: 42 } as unknown as UserType)renderFilters()-fireEvent.click(myAccountsCheckbox())-expect(logic.values.assignedToFilter).toEqual([42])expect(logic.values.assignedToCurrentUser).toBe(true)++ fireEvent.click(myAccountsCheckbox())+ expect(myAccountsCheckbox().checked).toBe(false)+ expect(logic.values.assignedToFilter).toEqual([])+ expect(logic.values.assignmentStatus).toBe('all')+ expect(screen.getByText('All accounts')).toBeInTheDocument()})it('renders the "Assigned to" picker with its default label', () => {@@ -152,6 +207,9 @@ describe('AccountsTabFilters', () => {expect(logic.values.assignmentStatus).toBe('assigned')})it('keeps OR branches when collapsed and returns to the empty trigger after removing every group', async () => {+ manualViewsLogic = accountsViewsLogic()+ manualViewsLogic.mount()+ await waitFor(() => expect(manualViewsLogic!.values.viewsLoaded).toBe(true))const first = [{type: PropertyFilterType.Account as const,diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsxindex 02a8303ec47b..4db11f32bfc0 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx@@ -11,6 +11,7 @@ import type { AccountPresenceViewerApi } from 'products/customer_analytics/frontimport { AccountNameCell } from './AccountNameCell'import { accountsExpansionLogic } from './accountsExpansionLogic'+import { accountsViewsLogic } from './accountsViewsLogic'import { AccountsEvents } from './constants'export interface AccountsTableNameCellProps {@@ -51,6 +52,7 @@ export function AccountsTableNameCell({}if (accountSceneEnabled) {+ accountsViewsLogic.findMounted()?.actions.prepareAccountReturn()posthog.capture(AccountsEvents.AccountOpened)return}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsxindex 2d00cafeb287..d4510ed57ecc 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsx@@ -20,8 +20,19 @@ import type { ColumnConfigurationApi } from 'products/product_analytics/frontendimport { accountsViewsLogic } from './accountsViewsLogic'export function AccountsViewSelector(): JSX.Element {- const { views, currentView, isDirty, viewsLoading } = useValues(accountsViewsLogic)- const { selectView, updateView, setViewToDelete, setViewToEdit, setIsCreating } = useActions(accountsViewsLogic)+ const {+ views,+ currentView,+ currentViewId,+ currentViewName,+ isDirty,+ viewsLoading,+ viewsLoaded,+ viewsLoadError,+ awaitingSavedView,+ } = useValues(accountsViewsLogic)+ const { selectView, updateView, setViewToDelete, setViewToEdit, setIsCreating, loadViews } =+ useActions(accountsViewsLogic)const menuItems: LemonMenuItems = [{@@ -57,23 +68,47 @@ export function AccountsViewSelector(): JSX.Element {),},{- items: [{ label: 'Save as new view...', icon: <IconPlus />, onClick: () => setIsCreating(true) }],+ items: [+ {+ label: 'Save as new view...',+ icon: <IconPlus />,+ onClick: () => setIsCreating(true),+ disabledReason: awaitingSavedView ? 'Wait for saved views to load' : undefined,+ },+ ],},]return (<div className="flex items-center gap-2">- {views.length > 0 ? (+ {viewsLoadError && (+ <LemonButton+ size="small"+ type="secondary"+ status="danger"+ onClick={loadViews}+ loading={viewsLoading}+ data-attr="accounts-retry-views"+ >+ Couldn't load views. Retry+ </LemonButton>+ )}+ {views.length > 0 || currentViewId || !viewsLoaded || viewsLoadError ? (<LemonMenu items={menuItems} closeOnClickInside>- <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>- {currentView ? (- <>+ <LemonButton+ type="secondary"+ size="small"+ sideIcon={<IconChevronDown />}+ icon={+ currentView ? (<ViewVisibilityIcon view={currentView} />- <span className="ml-2">{currentView.name}</span>- </>- ) : (- 'Select view'- )}+ ) : currentViewId ? (+ <span className="h-4 w-4" aria-hidden />+ ) : undefined+ }+ data-attr="accounts-select-view"+ >+ {currentView?.name ?? currentViewName ?? 'Select view'}</LemonButton></LemonMenu>) : (@@ -82,6 +117,8 @@ export function AccountsViewSelector(): JSX.Element {size="small"type="secondary"onClick={() => setIsCreating(true)}+ loading={viewsLoading && awaitingSavedView}+ disabledReason={awaitingSavedView ? 'Wait for saved views to load' : undefined}data-attr="accounts-save-view">Save current viewdiff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex d431ba1d231d..1b7e2590a7d5 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -59,7 +59,6 @@ import {SEARCH_DEBOUNCE_MS,} from './accountsLogic'import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'-import { readAccountsViewDraft, writeAccountsViewDraft } from './accountsViewState'import { AccountsEvents, DEFAULT_TILES } from './constants'const assignedToFilterOf = (query: AccountsTableQuery | null): number[] | undefined =>@@ -227,14 +226,14 @@ describe('accountsLogic', () => {initKeaTests()router.actions.push(urls.customerAnalyticsAccounts())jest.resetAllMocks()- // accountsLogic connects to the (localStorage-persisted) shared scene logic;- // clear it so a "mine only" write in one test can't leak into the next.localStorage.clear()sessionStorage.clear()mockDefinitionsList.mockResolvedValue({ count: DEFINITIONS.length, results: DEFINITIONS })mockCustomPropertiesList.mockResolvedValue({ count: 0, results: [] })logic = accountsLogic()logic.mount()+ // Saved-view restoration has its own suite; these tests exercise the settled list.+ logic.actions.applyViewState(logic.values.viewState, { source: 'draft', columns: 'keep' })// Legacy role columns only resolve into the query once definitions load.await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()})@@ -342,7 +341,7 @@ describe('accountsLogic', () => {operator: AccountsTableAccountFieldOperator.IsSet,values: [],})- expect(logic.values.viewUrlState.customProperties).toEqual(logic.values.accountFilters)+ expect(logic.values.viewState.filters.customProperties).toEqual(logic.values.accountFilters)})it('captures native filter shape without its field or value', () => {@@ -412,6 +411,7 @@ describe('accountsLogic', () => {mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))logic = accountsLogic()logic.mount()+ logic.actions.setAwaitingSavedView(false)expect(logic.values.accountsQuerySource).toBeNull()expect(logic.values.metricsQuery).toBeNull()@@ -426,40 +426,23 @@ describe('accountsLogic', () => {it.each([['the user before the team', ['user', 'team']],['the team before the user', ['team', 'user']],- ])('restores a draft when %s resolves without bootstrap or OAuth identity helpers', async (_, arrivals) => {+ ])('waits for identity when %s resolves without bootstrap or OAuth helpers', async (_, arrivals) => {+ logic.actions.setSearchQuery('previous session edits')logic.unmount()window.POSTHOG_APP_CONTEXT = undefinedsetOAuthContextIds(null)teamLogic.actions.loadCurrentTeamSuccess(null)userLogic.actions.loadUserSuccess(null)- writeAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid, {- columns: [...ACCOUNTS_DEFAULT_COLUMNS],- sortOrder: null,- filters: {- search: 'restored after identity',- assignmentStatus: 'all',- assignedTo: [],- tags: [],- tileFilter: null,- customProperties: [],- filterGroups: [],- },- tiles: [...DEFAULT_TILES],- columnDisplay: {},- })-+ sessionStorage.setItem(+ `customerAnalytics.accounts.viewDraft.${MOCK_DEFAULT_TEAM.id}.${MOCK_DEFAULT_USER.uuid}`,+ JSON.stringify({ filters: { search: 'stale storage' } })+ )expect(getCurrentTeamIdOrNone()).toBeNull()expect(getCurrentUserIdOrNone()).toBeNull()-logic = accountsLogic()logic.mount()expect(logic.values.viewStateHydrated).toBe(false)expect(logic.values.accountsQuerySource).toBeNull()-- accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN])- await expectLogic(logic).toFinishAllListeners()- expect(router.values.hashParams.view).toBeUndefined()-for (const arrival of arrivals) {if (arrival === 'user') {userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)@@ -468,21 +451,13 @@ describe('accountsLogic', () => {}await expectLogic(logic).toFinishAllListeners()}-expect(logic.values.viewStateHydrated).toBe(true)- expect(logic.values.searchQuery).toBe('restored after identity')- expect(logic.values.accountsQuerySource).not.toBeNull()-+ expect(logic.values.searchQuery).toBe('')+ logic.actions.setSearchQuery('private edits')const otherUser = { ...MOCK_DEFAULT_USER, uuid: 'other-user-uuid' }await expectLogic(logic, () => userLogic.actions.loadUserSuccess(otherUser)).toFinishAllListeners()expect(logic.values.searchQuery).toBe('')-- logic.actions.setSearchQuery('other user draft')- await expectLogic(logic).toFinishAllListeners()- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.filters.search).toBe(- 'restored after identity'- )- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, otherUser.uuid)?.filters.search).toBe('other user draft')+ expect(logic.values.awaitingSavedView).toBe(true)})it('removes relationship filters when relationship definitions fail to load', async () => {@@ -596,11 +571,13 @@ describe('accountsLogic', () => {expect(logic.values.assignedToCurrentUser).toBe(false)})- it('toggling the checkbox off clears the filter', () => {+ it('toggling the checkbox off restores all assignment statuses', () => {logic.actions.setAssignedToCurrentUser(true)logic.actions.setAssignedToCurrentUser(false)+ expect(logic.values.assignmentStatus).toBe('all')expect(logic.values.assignedToFilter).toEqual([])expect(assignedToFilterOf(logic.values.accountsQuerySource)).toBeUndefined()+ expect(logic.values.accountsQuerySource?.filters).not.toContainEqual({ kind: 'assigned' })})it('the Assigned to picker accepts explicit ids', () => {@@ -633,14 +610,11 @@ describe('accountsLogic', () => {expect(logic.values.assignedToFilter).toEqual([])})- it('persists concrete ids in the view hash (shareable, not viewer-relative)', async () => {- await expectLogic(logic, () => {- logic.actions.setAssignedToCurrentUser(true)- }).toFinishAllListeners()- expect(router.values.hashParams.view).toEqual({- assignmentStatus: 'assigned',- assignedTo: [CURRENT_USER_ID],- })+ it('keeps concrete assignee IDs in memory without writing URL snapshots', async () => {+ await expectLogic(logic, () => logic.actions.setAssignedToCurrentUser(true)).toFinishAllListeners()+ expect(logic.values.viewState.filters.assignedTo).toEqual([CURRENT_USER_ID])+ expect(router.values.hashParams.view).toBeUndefined()+ expect(router.values.searchParams.view).toBeUndefined()})it('restores the assigned-to filter from the view hash, independent of the viewer', async () => {@@ -662,89 +636,74 @@ describe('accountsLogic', () => {expect(logic.values.assignedToCurrentUser).toBe(true)})- // The "mine only" choice is held in the shared scene logic so it survives a- // switch to the Notes tab. These guard the two-way link between the accounts- // assigned-to filter and that shared toggle.- describe('shared "mine only" toggle', () => {- it('toggling "My accounts" writes the shared toggle', async () => {- await expectLogic(logic, () => {+ describe('independent My accounts filters', () => {+ beforeEach(() => customerAnalyticsSceneLogic.mount())+ afterEach(() => customerAnalyticsSceneLogic.unmount())++ it.each([false, true])(+ 'keeps the Notes preference at %s when Accounts filters change',+ async (notesMine) => {+ customerAnalyticsSceneLogic.actions.setMineOnly(notesMine)logic.actions.setAssignedToCurrentUser(true)- }).toFinishAllListeners()- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)+ await expectLogic(logic).toFinishAllListeners()+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(notesMine)- await expectLogic(logic, () => {logic.actions.setAssignedToCurrentUser(false)- }).toFinishAllListeners()- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)- })-- it('picking explicit assignees clears the shared toggle', async () => {- customerAnalyticsSceneLogic.actions.setMineOnly(true)- await expectLogic(logic, () => {logic.actions.setAssignedToFilter([7])- }).toFinishAllListeners()- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)- })+ await expectLogic(logic).toFinishAllListeners()+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(notesMine)+ expect(logic.values.assignedToFilter).toEqual([7])+ }+ )++ it.each([false, true])(+ 'discards Accounts My accounts=%s after visiting Notes without importing its preference',+ async (accountsMine) => {+ logic.actions.setAssignedToCurrentUser(accountsMine)+ logic.actions.setSearchQuery('keep search')+ logic.unmount()+ router.actions.push(urls.customerAnalyticsNotes())+ customerAnalyticsSceneLogic.actions.setMineOnly(!accountsMine)+ router.actions.push(urls.customerAnalyticsAccounts())+ logic = accountsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([])+ expect(logic.values.assignmentStatus).toBe('all')+ expect(logic.values.searchQuery).toBe('')+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(!accountsMine)+ }+ )- it('restores "my accounts" from the shared toggle when the URL has no view hash', async () => {+ it('does not import Notes changes while the Accounts logic remains mounted', async () => {+ logic.actions.setAssignedToFilter([7])+ router.actions.push(urls.customerAnalyticsNotes())customerAnalyticsSceneLogic.actions.setMineOnly(true)- router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))- await expectLogic(logic).toFinishAllListeners()+ customerAnalyticsSceneLogic.actions.setMineOnly(false)router.actions.push(urls.customerAnalyticsAccounts())await expectLogic(logic).toFinishAllListeners()- expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])- expect(logic.values.assignedToCurrentUser).toBe(true)+ expect(logic.values.assignedToFilter).toEqual([])+ expect(logic.values.assignmentStatus).toBe('all')})- // Regression: returning to the list on a URL with no view hash (the browser back- // button onto an entry written before the filter was picked, the tab link, or the- // breadcrumb) reset the status to "all", which cross-cleared the assigned-to filter- // and cascaded into setMineOnly(false), so the choice was gone for good.- it('keeps "my accounts" when the list URL loses the view hash', async () => {+ it('discards unsaved My accounts when navigating to the bare list URL', async () => {logic.actions.setAssignedToCurrentUser(true)- await expectLogic(logic).toFinishAllListeners()-+ router.actions.push(urls.customerAnalytics())router.actions.push(urls.customerAnalyticsAccounts())await expectLogic(logic).toFinishAllListeners()- expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])- expect(logic.values.assignmentStatus).toBe('assigned')- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)- })-- it('an explicit shared link still wins over the shared toggle', async () => {- customerAnalyticsSceneLogic.actions.setMineOnly(true)- router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignedTo: [7] } })- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.assignedToFilter).toEqual([7])- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)- })-- // Regression: on a fresh load the logic can run URL restore before userLogic- // resolves the user (currentUserId null), so the persisted choice can't be applied- // then. The user resolving later must apply it, without clearing the preference.- it('applies the persisted "my accounts" choice when the user resolves after restore', async () => {- userLogic.actions.loadUserSuccess(null)- customerAnalyticsSceneLogic.actions.setMineOnly(true)expect(logic.values.assignedToFilter).toEqual([])-- await expectLogic(logic, () => {- userLogic.actions.loadUserSuccess(buildUser({ id: CURRENT_USER_ID }) as unknown as UserType)- }).toFinishAllListeners()-- expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])- expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)+ expect(logic.values.assignmentStatus).toBe('all')+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)})it('the user resolving does not override an explicit assigned-to from the URL', async () => {router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignedTo: [7] } })await expectLogic(logic).toFinishAllListeners()-- await expectLogic(logic, () => {- userLogic.actions.loadUserSuccess(buildUser({ id: CURRENT_USER_ID }) as unknown as UserType)- }).toFinishAllListeners()+ userLogic.actions.loadUserSuccess(buildUser({ id: CURRENT_USER_ID }) as unknown as UserType)+ await expectLogic(logic).toFinishAllListeners()expect(logic.values.assignedToFilter).toEqual([7])})@@ -1040,8 +999,8 @@ describe('accountsLogic', () => {})})- describe('url persistence', () => {- it('writes active filters into the view hash param', async () => {+ describe('legacy URLs and session edits', () => {+ it('keeps active filters in memory without persisting snapshots', async () => {await expectLogic(logic, () => {logic.actions.setSearchQuery('acme')logic.actions.setTagsFilter(['enterprise'])@@ -1050,25 +1009,15 @@ describe('accountsLogic', () => {logic.actions.setTileFilter(TILE_FILTER)}).toFinishAllListeners()- expect(router.values.hashParams.view).toEqual({+ expect(logic.values.viewState.filters).toMatchObject({search: 'acme',tags: ['enterprise'],- assignmentStatus: 'assigned',assignedTo: [7],- sort: { column: 'name', direction: 'desc' },tileFilter: TILE_FILTER,})- })-- it('marks an explicit status in the hash while other filters are present', async () => {- await expectLogic(logic, () => {- logic.actions.setTagsFilter(['enterprise'])- logic.actions.setAssignmentStatus('all')- }).toFinishAllListeners()-- // A legacy hash with no status field restores as assigned-only, so a non-default- // hash must carry `all` explicitly rather than being mistaken for legacy.- expect(router.values.hashParams.view).toEqual({ tags: ['enterprise'], assignmentStatus: 'all' })+ expect(router.values.hashParams.view).toBeUndefined()+ expect(router.values.searchParams.view).toBeUndefined()+ expect(sessionStorage.length).toBe(0)})it('reads a legacy hash without a status field as assigned-only', async () => {@@ -1088,7 +1037,7 @@ describe('accountsLogic', () => {expect(router.values.hashParams.view).toBeUndefined()})- it('restores filters, sort, and tile filter when browser back returns to the original view hash', async () => {+ it('discards filters, sort, and tiles on browser Back without the account return token', async () => {const tileFilter = TILE_FILTERconst view = {search: 'beta',@@ -1110,45 +1059,41 @@ describe('accountsLogic', () => {})await expectLogic(logic).toFinishAllListeners()- expect(logic.values.searchQuery).toBe('beta')- expect(logic.values.searchInput).toBe('beta')- expect(logic.values.assignedToFilter).toEqual([7])- expect(logic.values.sortOrder).toEqual({ column: 'name', direction: 'desc' })- expect(logic.values.tileFilter).toEqual(tileFilter)- expect(logic.values.tiles).toEqual(CUSTOM_TILES)+ expect(logic.values.searchQuery).toBe('')+ expect(logic.values.searchInput).toBe('')+ expect(logic.values.assignedToFilter).toEqual([])+ expect(logic.values.sortOrder).toBeNull()+ expect(logic.values.tileFilter).toBeNull()+ expect(logic.values.tiles).toEqual(DEFAULT_TILES)})- it.each(['name', 'csm'])('keeps the %s sort while default columns load after Back', async (column) => {- logic.actions.setSortOrder({ column, direction: 'desc' })- const listLocation = router.values.currentLocation- router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))- logic.unmount()- initKeaTests()+ it.each(['name', 'csm'])(+ 'discards the %s sort on browser Back without a return token while columns load',+ async (column) => {+ logic.actions.setSortOrder({ column, direction: 'desc' })+ const listLocation = router.values.currentLocation+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))+ logic.unmount()- let resolveDefinitions!: (value: { count: number; results: AccountRelationshipDefinitionApi[] }) => void- mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))- router.actions.locationChanged({- ...listLocation,- url: `${listLocation.pathname}${listLocation.search}${listLocation.hash}`,- method: 'POP',- })- logic = accountsLogic()- logic.mount()- expect(logic.values.sortOrder).toEqual({ column, direction: 'desc' })+ let resolveDefinitions!: (value: { count: number; results: AccountRelationshipDefinitionApi[] }) => void+ mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))+ router.actions.locationChanged({+ ...listLocation,+ url: `${listLocation.pathname}${listLocation.search}${listLocation.hash}`,+ method: 'POP',+ })+ logic = accountsLogic()+ logic.mount()+ expect(logic.values.sortOrder).toBeNull()- resolveDefinitions({ count: DEFINITIONS.length, results: DEFINITIONS })- await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()- expect(logic.values.sortOrder).toEqual({ column, direction: 'desc' })- expect(logic.values.listDataCompleteness).toBe('unknown')- expect(logic.values.sortedRowsTransformer).toBeUndefined()- expect(logic.values.accountsQuerySource?.sort).toEqual({- column:- column === 'name'- ? { kind: 'account_field', field: 'name' }- : { kind: 'relationship', definitionId: CSM_DEFINITION_ID },- direction: 'desc',- })- })+ resolveDefinitions({ count: DEFINITIONS.length, results: DEFINITIONS })+ await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()+ expect(logic.values.sortOrder).toBeNull()+ expect(logic.values.listDataCompleteness).toBe('unknown')+ expect(logic.values.sortedRowsTransformer).toBeUndefined()+ expect(logic.values.accountsQuerySource).toBeNull()+ }+ )it('coerces a malformed scalar assignedTo from the view hash into an array', async () => {// normalizeRoleFilter defends the array-shaped filter against a stray@@ -1227,7 +1172,7 @@ describe('accountsLogic', () => {['a mounted list', false],['a remounted list', true],['a remounted account detail', 'detail'],- ])('keeps every unsaved view setting after detail navigation through %s', async (_, remountOnDetail) => {+ ])('discards unsaved settings on a plain return URL through %s', async (_, remountOnDetail) => {mockCustomPropertiesList.mockResolvedValue({count: 1,results: [buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID })],@@ -1238,10 +1183,6 @@ describe('accountsLogic', () => {const columnConfig = accountsColumnConfigLogic.findMounted()!columnConfig.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])columnConfig.actions.moveColumn(0, 1)- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.columns).toEqual([- 'csm',- ACCOUNTS_NAME_COLUMN,- ])columnConfig.actions.setColumnDisplay(CSM_DEFINITION_ID, { mode: 'sparkline', window_days: 30 })logic.actions.setSearchQuery('draft search')logic.actions.setTagsFilter(['enterprise'])@@ -1250,19 +1191,9 @@ describe('accountsLogic', () => {logic.actions.setSortOrder({ column: 'csm', direction: 'desc' })const overviewTiles = accountsOverviewTilesLogic.findMounted()!overviewTiles.actions.addTile(CUSTOM_TILES[0])- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.tiles).toEqual([- ...DEFAULT_TILES,- CUSTOM_TILES[0],- ])overviewTiles.actions.moveTile(0, 1)- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.tiles).toEqual([- CUSTOM_TILES[0],- ...DEFAULT_TILES,- ])logic.actions.setTileFilter(TILE_FILTER)await expectLogic(logic).toFinishAllListeners()- const expectedViewState = logic.values.viewState-router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))await expectLogic(logic).toFinishAllListeners()if (remountOnDetail) {@@ -1279,81 +1210,72 @@ describe('accountsLogic', () => {}await expectLogic(logic).toFinishAllListeners()- expect(logic.values.viewState).toEqual(expectedViewState)- expect(logic.values.accountsQuerySource?.filters).toEqual(- expect.arrayContaining([- { kind: 'search', query: 'draft search' },- { kind: 'tags', tagNames: ['enterprise'] },- { kind: 'assigned_to', userIds: [7] },- expect.objectContaining({ kind: 'account_field' }),- expect.objectContaining({ kind: 'custom_property' }),- expect.objectContaining({ kind: 'relationship' }),- ])- )+ expect(logic.values.viewState.filters).toEqual({+ search: '',+ assignmentStatus: 'all',+ assignedTo: [],+ tags: [],+ tileFilter: null,+ customProperties: [],+ filterGroups: [],+ })+ expect(logic.values.sortOrder).toBeNull()+ expect(logic.values.columnDisplay).toEqual({})+ expect(logic.values.selectColumns).toEqual(logic.values.defaultSelectColumns)logic.actions.setTagsFilter(['renewal'])await expectLogic(logic).toFinishAllListeners()- expect(router.values.hashParams.view).toEqual(- expect.objectContaining({- search: 'draft search',- tags: ['renewal'],- assignedTo: [7],- sort: { column: 'csm', direction: 'desc' },- columns: ['csm', ACCOUNTS_NAME_COLUMN],- tileFilter: TILE_FILTER,- customProperties: ACCOUNT_FILTERS,- })- )+ expect(logic.values.tagsFilter).toEqual(['renewal'])+ expect(router.values.hashParams.view).toBeUndefined()+ expect(router.values.searchParams.view).toBeUndefined()+ expect(sessionStorage.length).toBe(0)})it.each([['an empty shared view', {}, '', 'all'],['a populated shared view', { search: 'shared', assignmentStatus: 'all' }, 'shared', 'all'],- ])(- 'uses %s instead of the saved draft and keeps it as the next draft',- async (_, sharedView, search, status) => {- logic.actions.setSearchQuery('draft')- logic.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])- logic.actions.setAssignedToFilter([7])- await expectLogic(logic).toFinishAllListeners()- logic.unmount()+ ])('uses %s instead of session edits and keeps it in memory', async (_, sharedView, search, status) => {+ logic.actions.setSearchQuery('draft')+ logic.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])+ logic.actions.setAssignedToFilter([7])+ await expectLogic(logic).toFinishAllListeners()+ logic.unmount()- const customerAnalyticsScene = customerAnalyticsSceneLogic()- customerAnalyticsScene.mount()- customerAnalyticsScene.actions.setMineOnly(true)- router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: sharedView })- logic = accountsLogic()- const capture = jest.spyOn(posthog, 'capture').mockImplementation()- logic.mount()- await expectLogic(logic).toFinishAllListeners()+ const customerAnalyticsScene = customerAnalyticsSceneLogic()+ customerAnalyticsScene.mount()+ customerAnalyticsScene.actions.setMineOnly(true)+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: sharedView })+ logic = accountsLogic()+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()- expect(logic.values.searchQuery).toBe(search)- expect(logic.values.assignmentStatus).toBe(status)- expect(logic.values.assignedToFilter).toEqual([])- expect(logic.values.selectColumns).toEqual(logic.values.defaultSelectColumns)- expect(- capture.mock.calls.some(([event]) =>- [- AccountsEvents.FilterChanged,- AccountsEvents.OverviewTilesEdited,- AccountsEvents.Searched,- AccountsEvents.Sorted,- ].some((interactionEvent) => interactionEvent === event)- )- ).toBe(false)+ expect(logic.values.searchQuery).toBe(search)+ expect(logic.values.assignmentStatus).toBe(status)+ expect(logic.values.assignedToFilter).toEqual([])+ expect(logic.values.selectColumns).toEqual(logic.values.defaultSelectColumns)+ expect(+ capture.mock.calls.some(([event]) =>+ [+ AccountsEvents.FilterChanged,+ AccountsEvents.OverviewTilesEdited,+ AccountsEvents.Searched,+ AccountsEvents.Sorted,+ ].some((interactionEvent) => interactionEvent === event)+ )+ ).toBe(false)- logic.unmount()- router.actions.push(urls.customerAnalyticsAccounts())- logic = accountsLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()+ logic.unmount()+ router.actions.push(urls.customerAnalyticsAccounts())+ logic = accountsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()- expect(logic.values.searchQuery).toBe(search)- expect(logic.values.assignmentStatus).toBe(status)- expect(logic.values.assignedToFilter).toEqual([])- customerAnalyticsScene.unmount()- }- )+ expect(logic.values.searchQuery).toBe('')+ expect(logic.values.assignmentStatus).toBe('all')+ expect(logic.values.assignedToFilter).toEqual([])+ customerAnalyticsScene.unmount()+ })it('does not let a pending search overwrite a shared view restored from browser navigation', async () => {jest.useFakeTimers()@@ -1441,9 +1363,7 @@ describe('accountsLogic', () => {await expectLogic(logic).toFinishAllListeners()const deepLinkPath = router.values.location.pathname- // Landing on a deep link, the saved-view restore and the default-column upgrade both- // dispatch the setters that mirror view state into the URL. They must not rewrite the- // path, or the link bounces to the unfiltered list before the user sees the account.+ // Column initialization must not send an account deep link back to the list.accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])await expectLogic(logic).toFinishAllListeners()diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex ffdbb2c83f5d..3d964784e627 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -43,7 +43,6 @@ import {ACCOUNTS_METRICS_DATA_NODE_KEY,CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,} from '../../constants'-import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import type {AccountPresenceApi,AccountPresenceViewerApi,@@ -72,12 +71,8 @@ import {isAccountsTableRow,supportedAccountFilters,} from './accountsTableQuery'-import {- AccountsViewState,- normalizeRoleFilter,- readAccountsViewDraft,- writeAccountsViewDraft,-} from './accountsViewState'+import { getAccountsViewSession } from './accountsViewSessionLogic'+import { AccountsViewState, normalizeRoleFilter } from './accountsViewState'import { AccountsEvents, DEFAULT_TILES } from './constants'export const SEARCH_DEBOUNCE_MS = 300@@ -145,10 +140,6 @@ function accountsPathToWriteBackTo(accountIdFilter: string | null): string | nulreturn deepLinkPath && pathname.startsWith(deepLinkPath) ? pathname : null}-function isAccountsListPath(): boolean {- return removeProjectIdIfPresent(router.values.location.pathname) === urls.customerAnalyticsAccounts()-}-function hasSharedView(hashParams: Record<string, any> | undefined): boolean {return (!!hashParams &&@@ -179,7 +170,6 @@ function persistViewStateAndUrl(return}actions.persistViewState()- actions.syncViewStateToUrl()}export interface AccountsViewUrlState {@@ -209,25 +199,6 @@ export interface ApplyAccountsViewStateOptions {columns: 'restore' | 'defaults' | 'keep'}-function viewStateWithMineOnly(- viewState: AccountsViewState,- mineOnly: boolean,- currentUserId: number | null-): AccountsViewState {- if (currentUserId === null) {- return viewState- }- const assignedToCurrentUser =- viewState.filters.assignedTo.length === 1 && viewState.filters.assignedTo[0] === currentUserId- if (mineOnly) {- return {- ...viewState,- filters: { ...viewState.filters, assignmentStatus: 'assigned', assignedTo: [currentUserId] },- }- }- return assignedToCurrentUser ? { ...viewState, filters: { ...viewState.filters, assignedTo: [] } } : viewState-}-function accountsViewStateFromUrl(view: AccountsViewUrlState,defaultColumns: string[],@@ -287,7 +258,6 @@ export interface accountsLogicValues {overviewMetrics: AccountsTableMetric[] // accountsOverviewTilesLogictileFilter: TileFilter | null // accountsOverviewTilesLogictiles: AccountsOverviewTile[] // accountsOverviewTilesLogic- mineOnly: boolean // customerAnalyticsSceneLogiccurrentTeamId: number | null // teamLogicuser: UserType | null // userLogicaccountFilterGroups: AccountFilter[][]@@ -306,7 +276,6 @@ export interface accountsLogicValues {canSortClientSide: booleancurrentUserId: number | nullcustomPropertyOverrides: Record<string, CustomPropertyValueWriteApi['value']>- draftRestored: booleanisCustomPropertySaving: (accountId: string, definitionId: string) => booleanisRoleSaving: (accountId: string, column: string) => booleanisTagsSaving: (accountId: string) => boolean@@ -327,7 +296,6 @@ export interface accountsLogicValues {tagsFilter: string[]viewState: AccountsViewStateviewStateHydrated: boolean- viewUrlState: AccountsViewUrlState}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -391,9 +359,6 @@ export interface accountsLogicActions {setTiles: (tiles: AccountsOverviewTile[]) => {tiles: AccountsOverviewTile[]} // accountsOverviewTilesLogic- setMineOnly: (mineOnly: boolean) => {- mineOnly: boolean- } // customerAnalyticsSceneLogiclistLoadData: (refresh?: RefreshType | undefined,alreadyRunningQueryId?: string | undefined,@@ -583,9 +548,6 @@ export interface accountsLogicActions {definitionId: stringvalue: boolean | number | string | null | undefined}- setDraftRestored: (restored: boolean) => {- restored: boolean- }setListResponseState: (datasetKey: string,completeness: Exclude<AccountListDataCompleteness, 'unknown'>,@@ -705,19 +667,6 @@ export interface accountsLogicMeta {accountFilterGroups: AccountFilter[][],columnDisplay: AccountColumnDisplayState) => AccountsViewState- viewUrlState: (- searchQuery: string,- tagsFilter: string[],- assignmentStatus: AssignmentStatus,- assignedToFilter: RoleFilterValue,- sortOrder: AccountSortOrder,- selectColumns: string[],- defaultSelectColumns: string[],- tileFilter: TileFilter | null,- accountFilters: AccountFilter[],- accountFilterGroups: AccountFilter[][],- columnDisplay: AccountColumnDisplayState- ) => AccountsViewUrlStatelistDatasetKey: (currentTeamId: number | null,searchQuery: string,@@ -816,8 +765,6 @@ export const accountsLogic = kea<accountsLogicType>([],accountsOverviewTilesLogic,['metrics as overviewMetrics', 'tileFilter', 'tiles'],- customerAnalyticsSceneLogic,- ['mineOnly'],],actions: [accountsColumnConfigLogic,@@ -837,8 +784,6 @@ export const accountsLogic = kea<accountsLogicType>([['setTileFilter', 'setTiles'],accountsExpansionLogic,['openAccountTab'],- customerAnalyticsSceneLogic,- ['setMineOnly'],userLogic,['loadUserSuccess'],membersLogic,@@ -919,7 +864,6 @@ export const accountsLogic = kea<accountsLogicType>([}),setAccountIdFilter: (accountId: string | null) => ({ accountId }),setAwaitingSavedView: (awaiting: boolean) => ({ awaiting }),- setDraftRestored: (restored: boolean) => ({ restored }),setViewStateHydrated: (hydrated: boolean) => ({ hydrated }),}),reducers({@@ -977,17 +921,11 @@ export const accountsLogic = kea<accountsLogicType>([},],awaitingSavedView: [- false,+ true,{setAwaitingSavedView: (_, { awaiting }) => awaiting,},],- draftRestored: [- false,- {- setDraftRestored: (_, { restored }) => restored,- },- ],viewStateHydrated: [false,{@@ -1181,74 +1119,6 @@ export const accountsLogic = kea<accountsLogicType>([columnDisplay,}),],- viewUrlState: [- (s) => [- s.searchQuery,- s.tagsFilter,- s.assignmentStatus,- s.assignedToFilter,- s.sortOrder,- s.selectColumns,- s.defaultSelectColumns,- s.tileFilter,- s.accountFilters,- s.accountFilterGroups,- s.columnDisplay,- ],- (- searchQuery: string,- tagsFilter: string[],- assignmentStatus: AssignmentStatus,- assignedToFilter: RoleFilterValue,- sortOrder: AccountSortOrder,- selectColumns: string[],- defaultSelectColumns: string[],- tileFilter: TileFilter | null,- accountFilters: AccountFilter[],- accountFilterGroups: AccountFilter[][],- columnDisplay: AccountColumnDisplayState- ): AccountsViewUrlState => {- const state: AccountsViewUrlState = {}- const trimmedSearch = searchQuery.trim()- if (trimmedSearch) {- state.search = trimmedSearch- }- if (tagsFilter.length > 0) {- state.tags = tagsFilter- }- if (assignmentStatus === 'unassigned') {- state.assignmentStatus = 'unassigned'- } else if (assignmentStatus === 'assigned') {- state.assignmentStatus = 'assigned'- if (assignedToFilter.length > 0) {- state.assignedTo = assignedToFilter- }- }- if (sortOrder) {- state.sort = sortOrder- }- if (!objectsEqual(selectColumns, defaultSelectColumns)) {- state.columns = selectColumns- }- if (Object.keys(columnDisplay).length > 0) {- state.columnDisplay = columnDisplay- }- if (tileFilter) {- state.tileFilter = tileFilter- }- if (accountFilters.length > 0) {- state.customProperties = accountFilters- }- if (accountFilterGroups.some((group) => group.length > 0)) {- state.filterGroups = accountFilterGroups.filter((group) => group.length > 0)- }- // Without an explicit status, a nonempty hash would restore as a legacy assigned-only view.- if (assignmentStatus === 'all' && Object.keys(state).length > 0) {- state.assignmentStatus = 'all'- }- return state- },- ],listDatasetKey: [(s) => [s.currentTeamId,@@ -1446,10 +1316,10 @@ export const accountsLogic = kea<accountsLogicType>([}),listeners(({ actions, values, cache, selectors }) => ({applyViewState: ({ viewState, options }) => {- cache.assignmentStateResolved = true- if (options.source === 'draft') {- actions.setDraftRestored(true)+ if (options.columns !== 'keep') {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = options.columns}+ cache.assignmentStateResolved = truecache.searchGeneration = (cache.searchGeneration ?? 0) + 1cache.applyingViewState = truetry {@@ -1473,7 +1343,6 @@ export const accountsLogic = kea<accountsLogicType>([} finally {cache.applyingViewState = false}- // A fallback snapshot would become a draft that blocks the pending saved view.if (options.source !== 'defaults') {actions.persistViewState()}@@ -1482,7 +1351,6 @@ export const accountsLogic = kea<accountsLogicType>([const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)if (!values.viewStateHydrated ||- values.awaitingSavedView ||cache.applyingViewState ||!draftIdentity ||!objectsEqual(cache.viewStateDraftIdentity, draftIdentity) ||@@ -1494,20 +1362,35 @@ export const accountsLogic = kea<accountsLogicType>([...values.viewState,filters: { ...values.viewState.filters, search: search ?? values.searchInput },}- writeAccountsViewDraft(draftIdentity.teamId, draftIdentity.userId, viewState)- },- setAwaitingSavedView: ({ awaiting }) => {- if (!awaiting) {- actions.syncViewStateToUrl()- }+ const session = getAccountsViewSession(draftIdentity.teamId, draftIdentity.userId)+ session.state = viewState+ session.revision+++ session.initialized = true+ actions.setAwaitingSavedView(false)},setSearchQuery: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),setTagsFilter: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),setSortOrder: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),- restoreSelectColumns: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),- selectColumn: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),- [accountsColumnConfigLogic.actionTypes.moveColumn]: () =>- persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),+ restoreSelectColumns: () => {+ if (!cache.applyingViewState) {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'restore'+ }+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)+ },+ [accountsColumnConfigLogic.actionTypes.setDefaultSelectColumns]: () => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ if (session.initialized && session.state) {+ actions.persistViewState()+ }+ },+ selectColumn: () => {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'restore'+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)+ },+ [accountsColumnConfigLogic.actionTypes.moveColumn]: () => {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'restore'+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)+ },setColumnDisplay: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),setColumnDisplayConfig: () =>persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),@@ -1789,74 +1672,29 @@ export const accountsLogic = kea<accountsLogicType>([}},setAssignedToCurrentUser: ({ value }) => {- actions.setAssignedToFilter(value && values.currentUserId !== null ? [values.currentUserId] : [])+ if (!value) {+ actions.setAssignmentStatus('all')+ } else if (values.currentUserId !== null) {+ actions.setAssignedToFilter([values.currentUserId])+ }},setAssignedToFilter: ({ value }) => {persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)if (value.length > 0 && values.assignmentStatus !== 'assigned') {actions.setAssignmentStatus('assigned')}- // Notes uses the same My accounts preference.- if (!cache.pendingMineOnlyRestore) {- cache.mirroringMineOnly = true- try {- actions.setMineOnly(values.assignedToCurrentUser)- } finally {- cache.mirroringMineOnly = false- }- }- },- setMineOnly: ({ mineOnly }) => {- if (cache.mirroringMineOnly) {- return- }- if (!isAccountsListPath()) {- cache.mineOnlyChangedOutsideAccounts = mineOnly- return- }- if (cache.userUnavailable) {- cache.pendingMineOnlyRestore = mineOnly- return- }- if (mineOnly && values.currentUserId !== null) {- actions.setAssignedToFilter([values.currentUserId])- } else if (!mineOnly && values.assignedToCurrentUser) {- actions.setAssignedToFilter([])- }},[teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)- if (- !values.viewStateHydrated ||- (draftIdentity && !objectsEqual(cache.viewStateDraftIdentity, draftIdentity))- ) {+ if (!values.viewStateHydrated || !objectsEqual(cache.viewStateDraftIdentity, draftIdentity)) {actions.restoreViewStateFromRoute()}},- // Viewer-relative preferences and legacy mine links must wait for the user ID.- loadUserSuccess: ({ user }) => {- cache.userUnavailable = user === null+ // Legacy mine links must wait for the user ID.+ loadUserSuccess: () => {const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)- if (- !values.viewStateHydrated ||- (draftIdentity && !objectsEqual(cache.viewStateDraftIdentity, draftIdentity))- ) {+ if (!values.viewStateHydrated || !objectsEqual(cache.viewStateDraftIdentity, draftIdentity)) {actions.restoreViewStateFromRoute()- return- }- if (cache.pendingMineOnlyRestore && values.currentUserId !== null) {- cache.pendingMineOnlyRestore = false- actions.setAssignedToFilter([values.currentUserId])- return- }- if (- !cache.assignmentStateResolved &&- values.mineOnly &&- values.currentUserId !== null &&- !values.assignedToFilter.length &&- values.assignmentStatus !== 'unassigned'- ) {- actions.setAssignedToFilter([values.currentUserId])}},toggleSort: ({ column }) => {@@ -1876,16 +1714,21 @@ export const accountsLogic = kea<accountsLogicType>([})},setSelectColumns: () => {+ if (!cache.applyingViewState) {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'restore'+ }persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)clearSortIfColumnRemoved(values, actions)},unselectColumn: () => {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'restore'persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)clearSortIfColumnRemoved(values, actions)},resetColumns: () => {persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)clearSortIfColumnRemoved(values, actions)+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).columnMode = 'defaults'},refresh: () => {posthog.capture(AccountsEvents.Refreshed, {@@ -1897,91 +1740,97 @@ export const accountsLogic = kea<accountsLogicType>([dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')},restoreViewStateFromRoute: ({ method }) => {- const pathname = removeProjectIdIfPresent(router.values.location.pathname)- const sharedView = hasSharedView(router.values.hashParams)- ? (router.values.hashParams.view as AccountsViewUrlState)- : null- const pendingUrlRestore = cache.pendingUrlRestore- cache.pendingUrlRestore = undefined- if (- method === 'REPLACE' &&- pendingUrlRestore &&- pendingUrlRestore.pathname === pathname &&- objectsEqual(pendingUrlRestore.view, sharedView ?? {})- ) {+ const identity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)+ const session = getAccountsViewSession(identity?.teamId ?? null, identity?.userId ?? null)+ const scopeChanged = !objectsEqual(cache.viewStateDraftIdentity, identity)+ cache.viewStateDraftIdentity = identity+ if (cache.skipReturnCleanup && method === 'REPLACE') {+ cache.skipReturnCleanup = false+ session.entryLocation = router.values.currentLocationreturn}-- const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)- if (!sharedView && !draftIdentity) {+ if (!identity) {+ actions.setAwaitingSavedView(true)actions.setViewStateHydrated(false)return}-- const previousDraftIdentity = cache.viewStateDraftIdentity- cache.assignmentStateResolved = false- cache.pendingMineOnlyRestore = false- cache.viewStateDraftIdentity = draftIdentity- actions.setDraftRestored(false)- let restored = false- const draft = draftIdentity ? readAccountsViewDraft(draftIdentity.teamId, draftIdentity.userId) : null+ const explicitReference =+ typeof router.values.searchParams.view === 'string' ? router.values.searchParams.view : null+ const sharedView =+ explicitReference === null && hasSharedView(router.values.hashParams)+ ? (router.values.hashParams.view as AccountsViewUrlState)+ : null+ const isList =+ removeProjectIdIfPresent(router.values.location.pathname) === urls.customerAnalyticsAccounts()+ const enteringList = isList && session.entryLocation !== router.values.currentLocation+ const returning = session.returnView+ const restoreReturn =+ enteringList &&+ returning &&+ router.values.searchParams.restore_view === returning.token &&+ returning.viewId === explicitReference+ if (enteringList) {+ session.entryLocation = router.values.currentLocation+ if (restoreReturn) {+ session.state = returning.state+ session.currentViewId = returning.viewId+ session.reference = returning.viewId+ session.columnMode = returning.columnMode+ session.initialized = returning.state !== null+ session.returnView = null+ session.revision+++ } else if (method !== 'REPLACE') {+ session.state = null+ session.initialized = false+ session.returnView = null+ session.allowRemembered = true+ session.reference = explicitReference ?? session.currentViewId+ session.revision+++ }+ }+ const reference = explicitReference ?? (!sharedView ? (session.reference ?? null) : null)+ const referenceChanged = session.reference !== undefined && reference !== session.reference+ if (referenceChanged) {+ session.state = null+ session.currentViewId = null+ session.initialized = false+ session.allowRemembered = false+ session.revision+++ }+ session.reference = reference+ actions.setAwaitingSavedView(!session.initialized)if (sharedView) {- cache.mineOnlyChangedOutsideAccounts = undefined- cache.pendingMineOnlyRestore = !!sharedView.mine && values.currentUserId === nullactions.applyViewState(accountsViewStateFromUrl(sharedView,values.defaultSelectColumns,values.currentUserId,- draft?.tiles ?? values.tiles+ DEFAULT_TILES),{ source: 'shared_url', columns: Array.isArray(sharedView.columns) ? 'restore' : 'defaults' })- restored = true- } else if (isAccountsListPath() || pathname.startsWith(`${urls.customerAnalyticsAccounts()}/`)) {- const mineOnly = cache.mineOnlyChangedOutsideAccounts- cache.mineOnlyChangedOutsideAccounts = undefined- if (mineOnly !== undefined) {- cache.pendingMineOnlyRestore = mineOnly && values.currentUserId === null- actions.applyViewState(- viewStateWithMineOnly(draft ?? values.viewState, mineOnly, values.currentUserId),- {- source: draft ? 'draft' : 'defaults',- columns: draft ? 'restore' : 'keep',- }- )- restored = true- } else if (draft) {- actions.applyViewState(draft, { source: 'draft', columns: 'restore' })- restored = true- } else if (previousDraftIdentity && !objectsEqual(previousDraftIdentity, draftIdentity)) {- actions.applyViewState(- viewStateWithMineOnly(- accountsViewStateFromUrl(- {},- values.defaultSelectColumns,- values.currentUserId,- DEFAULT_TILES- ),- values.mineOnly,- values.currentUserId- ),- { source: 'defaults', columns: 'defaults' }- )- } else if (values.mineOnly) {- if (values.currentUserId === null) {- cache.pendingMineOnlyRestore = true- } else {- actions.applyViewState(viewStateWithMineOnly(values.viewState, true, values.currentUserId), {- source: 'defaults',- columns: 'keep',- })- }- }+ session.state = values.viewState+ session.currentViewId = null+ session.initialized = true+ } else if (session.state) {+ actions.applyViewState(session.state, { source: 'draft', columns: session.columnMode })+ } else if (scopeChanged || referenceChanged || (enteringList && !restoreReturn && method !== 'REPLACE')) {+ actions.applyViewState(+ accountsViewStateFromUrl({}, values.defaultSelectColumns, values.currentUserId, DEFAULT_TILES),+ { source: 'defaults', columns: 'defaults' }+ )}actions.setViewStateHydrated(true)- if (restored) {- actions.persistViewState()+ actions.setAwaitingSavedView(!session.initialized)+ if (isList && Object.hasOwn(router.values.searchParams, 'restore_view')) {+ const { restore_view: _, ...search } = router.values.searchParams+ cache.skipReturnCleanup = true+ router.actions.replace(router.values.location.pathname, search, router.values.hashParams)+ session.entryLocation = router.values.currentLocation+ }+ if (hasSharedView(router.values.hashParams)) {+ const { view: _, ...hash } = router.values.hashParams+ router.actions.replace(router.values.location.pathname, router.values.searchParams, hash)}},updateAccountCustomProperty: async ({ accountId, definition, value }) => {@@ -2149,35 +1998,25 @@ export const accountsLogic = kea<accountsLogicType>([actions.ensureAllMembersLoaded()actions.restoreViewStateFromRoute()}),- actionToUrl(({ values, cache }) => ({+ actionToUrl(({ values }) => ({syncViewStateToUrl: () => {- if (!values.viewStateHydrated || values.awaitingSavedView) {- return undefined- }const pathname = accountsPathToWriteBackTo(values.accountIdFilter)- if (!pathname) {- return undefined- }- const view = objectsEqual(values.viewUrlState, {}) ? {} : values.viewUrlState- const currentView = hasSharedView(router.values.hashParams)- ? (router.values.hashParams.view as AccountsViewUrlState)- : {}- if (objectsEqual(currentView, view)) {+ if (!pathname || !values.viewStateHydrated) {return undefined}- const pendingUrlRestore = {- pathname: removeProjectIdIfPresent(pathname),- view,- }- cache.pendingUrlRestore = pendingUrlRestore- queueMicrotask(() => {- if (cache.pendingUrlRestore === pendingUrlRestore) {- cache.pendingUrlRestore = undefined- }- })- return [pathname, router.values.searchParams, objectsEqual(view, {}) ? {} : { view }, { replace: true }]+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ const { view: _, ...search } = router.values.searchParams+ const { view: __, ...hash } = router.values.hashParams+ session.reference = session.currentViewId+ return [+ pathname,+ session.currentViewId ? { ...search, view: session.currentViewId } : search,+ hash,+ { replace: true },+ ]},})),+urlToAction(({ actions, values }) => {const openAccountByPath = (accountId: string | undefined, rawTab?: string): void => {if (!accountId || !isUUIDLike(accountId)) {@@ -2199,20 +2038,15 @@ export const accountsLogic = kea<accountsLogicType>([actions.setAccountIdFilter(null)}},- // Keep the list draft while the account ID controls the detail query.- [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }, __, ___, { method }): void => {- actions.restoreViewStateFromRoute(method)+ // Account navigation must not replace the active list edits.+ [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }): void => {+ actions.restoreViewStateFromRoute()openAccountByPath(accountId)},// This is a route template, not a navigable URL. `customerAnalyticsAccount` encodes// tab values for real links, so append the literal matcher segment here.- [`${urls.customerAnalyticsAccount(':accountId')}/:tab`]: (- { accountId, tab },- __,- ___,- { method }- ): void => {- actions.restoreViewStateFromRoute(method)+ [`${urls.customerAnalyticsAccount(':accountId')}/:tab`]: ({ accountId, tab }): void => {+ actions.restoreViewStateFromRoute()openAccountByPath(accountId, tab)},}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewSessionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewSessionLogic.tsnew file mode 100644index 000000000000..15d38ee60a9f--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewSessionLogic.ts@@ -0,0 +1,143 @@+import { MakeLogicType, connect, kea, listeners, path } from 'kea'+import { combineUrl, router } from 'kea-router'+import type { LocationChangedPayload } from 'kea-router/lib/types'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import type { UserType } from '~/types'++import type { AccountsViewState } from './accountsViewState'++export interface AccountsViewReturn {+ token: string+ url: string+ state: AccountsViewState | null+ viewId: string | null+ columnMode: 'defaults' | 'restore'+}++export interface AccountsViewSession {+ scope: string+ state: AccountsViewState | null+ columnMode: 'defaults' | 'restore'+ currentViewId: string | null+ reference: string | null | undefined+ initialized: boolean+ allowRemembered: boolean+ revision: number+ entryLocation: unknown+ returnView: AccountsViewReturn | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountsViewSessionLogicValues {+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogic+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountsViewSessionLogicMeta {+ __keaTypeGenInternalReducerActions: {+ 'location changed (kea.router)': ({+ method,+ pathname,+ search,+ searchParams,+ hash,+ hashParams,+ initial,+ url,+ routerState,+ }: LocationChangedPayload) => {+ payload: {+ 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+ }+ type: 'location changed (kea.router)'+ }+ }+}++export type accountsViewSessionLogicType = MakeLogicType<+ accountsViewSessionLogicValues,+ {},+ Record<string, any>,+ accountsViewSessionLogicMeta+>++const accountsViewSessionLogic = kea<accountsViewSessionLogicType>([+ path(['scenes', 'customerAnalytics', 'accounts', 'accountsViewSessionLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId'], userLogic, ['user']] })),+ listeners(({ values, cache }) => ({+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ },+ [userLogic.actionTypes.loadUserSuccess]: () => {+ getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ },+ [router.actionTypes.locationChanged]: ({ pathname }) => {+ const session = cache.session as AccountsViewSession | undefined+ const path = removeProjectIdIfPresent(pathname)+ if (+ !session ||+ path === urls.customerAnalyticsAccounts() ||+ path.startsWith(`${urls.customerAnalyticsAccounts()}/`)+ ) {+ return+ }+ session.state = null+ session.initialized = false+ session.returnView = null+ session.entryLocation = null+ session.reference = session.currentViewId+ session.revision+++ },+ })),+])++export function getAccountsViewSession(teamId: number | null, userId: string | null): AccountsViewSession {+ let logic = accountsViewSessionLogic.findMounted()+ if (!logic) {+ logic = accountsViewSessionLogic()+ // Identity changes must discard edits even when the Accounts scene is unmounted.+ // This owner stays mounted for the kea context's lifetime and never writes browser storage.+ logic.mount()+ }+ const scope = `${teamId}.${userId}`+ if (!logic.cache.session || logic.cache.session.scope !== scope) {+ logic.cache.session = {+ scope,+ state: null,+ columnMode: 'defaults',+ currentViewId: null,+ reference: undefined,+ initialized: false,+ allowRemembered: true,+ revision: 0,+ entryLocation: null,+ returnView: null,+ } satisfies AccountsViewSession+ }+ return logic.cache.session+}++export function getAccountsBackUrl(teamId: number | null, userId: string | null): string {+ if (teamId === null || userId === null) {+ return urls.customerAnalyticsAccounts()+ }+ const session = getAccountsViewSession(teamId, userId)+ return (+ session.returnView?.url ??+ combineUrl(urls.customerAnalyticsAccounts(), session.currentViewId ? { view: session.currentViewId } : {}).url+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.tsindex 0da7c681682e..4fc306ff935f 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts@@ -4,219 +4,211 @@ import { PropertyFilterType, PropertyOperator } from '~/types'import { ACCOUNTS_DEFAULT_COLUMNS } from './accountsColumnConfigLogic'import {AccountsViewState,- accountsViewDraftStorageKey,+ accountsViewIdStorageKey,deserializeAccountsView,normalizeRoleFilter,orderByToSortOrder,- readAccountsViewDraft,+ readAccountsViewId,+ readAccountsViewSelection,serializeAccountsView,sortOrderToOrderBy,- writeAccountsViewDraft,+ writeAccountsViewId,} from './accountsViewState'import { DEFAULT_TILES } from './constants'-const draft: AccountsViewState = {- columns: ['name'],- sortOrder: null,- filters: {- search: 'acme',- assignmentStatus: 'all',- assignedTo: [],- tags: [],- tileFilter: null,- customProperties: [],- filterGroups: [],- },- tiles: [...DEFAULT_TILES],- columnDisplay: {},-}--describe('accounts view drafts', () => {- beforeEach(() => {- sessionStorage.clear()- })-- afterEach(() => {- sessionStorage.clear()- jest.restoreAllMocks()- })-- it('scopes drafts to the current project and user', () => {- writeAccountsViewDraft(1, 'user-a', draft)- writeAccountsViewDraft(1, 'user-b', { ...draft, filters: { ...draft.filters, search: 'other user' } })- writeAccountsViewDraft(2, 'user-a', { ...draft, filters: { ...draft.filters, search: 'other project' } })-- expect(readAccountsViewDraft(1, 'user-a')).toEqual(draft)- expect(readAccountsViewDraft(1, 'user-b')?.filters.search).toBe('other user')- expect(readAccountsViewDraft(2, 'user-a')?.filters.search).toBe('other project')- })+describe('accountsViewState', () => {+ describe('saved-view references', () => {+ beforeEach(() => localStorage.clear())+ afterEach(() => {+ localStorage.clear()+ jest.restoreAllMocks()+ })- it('fails closed for malformed or unavailable session storage', () => {- sessionStorage.setItem(accountsViewDraftStorageKey(1, 'user-a'), '{invalid')- expect(readAccountsViewDraft(1, 'user-a')).toBeNull()+ it('remembers only the saved ID and name, scoped to a project and user', () => {+ writeAccountsViewId(1, 'user-a', 'view-1', 'First view')+ writeAccountsViewId(1, 'user-b', 'view-2', 'Second view')+ writeAccountsViewId(2, 'user-a', 'view-3', 'Other project')+ expect(JSON.parse(localStorage.getItem(accountsViewIdStorageKey(1, 'user-a'))!)).toEqual({+ id: 'view-1',+ name: 'First view',+ })+ expect(readAccountsViewSelection(1, 'user-a')).toEqual({ id: 'view-1', name: 'First view' })+ expect(readAccountsViewSelection(1, 'user-b')).toEqual({ id: 'view-2', name: 'Second view' })+ expect(readAccountsViewSelection(2, 'user-a')).toEqual({ id: 'view-3', name: 'Other project' })+ localStorage.setItem(accountsViewIdStorageKey(1, 'user-a'), JSON.stringify('legacy-id'))+ expect(readAccountsViewSelection(1, 'user-a')).toEqual({ id: 'legacy-id', name: null })+ })- jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {- throw new Error('storage denied')+ it.each(['{invalid', '42', '{}', 'null'])('ignores an invalid remembered reference: %s', (raw) => {+ localStorage.setItem(accountsViewIdStorageKey(1, 'user-a'), raw)+ expect(readAccountsViewId(1, 'user-a')).toBeNull()})- expect(readAccountsViewDraft(1, 'user-a')).toBeNull()- jest.restoreAllMocks()- jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {- throw new Error('storage denied')+ it('keeps the legacy reference when scoped storage is unavailable', () => {+ const legacyKey = 'customerAnalytics.accounts.accountsViewsLogic.1.currentViewId'+ localStorage.setItem(legacyKey, JSON.stringify('view-1'))+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('storage denied')+ })+ expect(() => writeAccountsViewId(1, 'user-a', 'view-1')).not.toThrow()+ expect(localStorage.getItem(legacyKey)).toBe(JSON.stringify('view-1'))+ jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new Error('storage denied')+ })+ expect(readAccountsViewId(1, 'user-a')).toBeNull()})- expect(() => writeAccountsViewDraft(1, 'user-a', draft)).not.toThrow()})-})-describe('sortOrderToOrderBy / orderByToSortOrder', () => {- it('round-trips a plain ascending column', () => {- expect(sortOrderToOrderBy({ column: 'name', direction: 'asc' })).toEqual(['name ASC'])- expect(orderByToSortOrder(['name ASC'])).toEqual({ column: 'name', direction: 'asc' })- })+ describe('sortOrderToOrderBy / orderByToSortOrder', () => {+ it('round-trips a plain ascending column', () => {+ expect(sortOrderToOrderBy({ column: 'name', direction: 'asc' })).toEqual(['name ASC'])+ expect(orderByToSortOrder(['name ASC'])).toEqual({ column: 'name', direction: 'asc' })+ })- it('round-trips a descending role/tuple column by its logical name', () => {- expect(sortOrderToOrderBy({ column: 'csm', direction: 'desc' })).toEqual(['csm DESC'])- expect(orderByToSortOrder(['csm DESC'])).toEqual({ column: 'csm', direction: 'desc' })- })+ it('round-trips a descending role/tuple column by its logical name', () => {+ expect(sortOrderToOrderBy({ column: 'csm', direction: 'desc' })).toEqual(['csm DESC'])+ expect(orderByToSortOrder(['csm DESC'])).toEqual({ column: 'csm', direction: 'desc' })+ })- it('treats null / empty as no sort', () => {- expect(sortOrderToOrderBy(null)).toEqual([])- expect(orderByToSortOrder([])).toBeNull()- expect(orderByToSortOrder(null)).toBeNull()- })+ it('treats null / empty as no sort', () => {+ expect(sortOrderToOrderBy(null)).toEqual([])+ expect(orderByToSortOrder([])).toBeNull()+ expect(orderByToSortOrder(null)).toBeNull()+ })- it('defaults to ascending when the direction token is missing', () => {- expect(orderByToSortOrder(['health_score'])).toEqual({ column: 'health_score', direction: 'asc' })+ it('defaults to ascending when the direction token is missing', () => {+ expect(orderByToSortOrder(['health_score'])).toEqual({ column: 'health_score', direction: 'asc' })+ })})-})-describe('normalizeRoleFilter', () => {- it('coerces a scalar (legacy link) to an array', () => {- expect(normalizeRoleFilter(7)).toEqual([7])- })+ describe('normalizeRoleFilter', () => {+ it('coerces a scalar (legacy link) to an array', () => {+ expect(normalizeRoleFilter(7)).toEqual([7])+ })- it('drops non-number array entries', () => {- expect(normalizeRoleFilter([1, 'x', 2])).toEqual([1, 2])- })+ it('drops non-number array entries', () => {+ expect(normalizeRoleFilter([1, 'x', 2])).toEqual([1, 2])+ })- it('falls back to empty for nullish/garbage', () => {- expect(normalizeRoleFilter(undefined)).toEqual([])- expect(normalizeRoleFilter('nope')).toEqual([])+ it('falls back to empty for nullish/garbage', () => {+ expect(normalizeRoleFilter(undefined)).toEqual([])+ expect(normalizeRoleFilter('nope')).toEqual([])+ })})-})-describe('serializeAccountsView / deserializeAccountsView', () => {- it('round-trips a fully populated view', () => {- const state: AccountsViewState = {- columns: ['name', 'csm'],- sortOrder: { column: 'csm' as const, direction: 'desc' as const },- filters: {- search: 'acme',- assignmentStatus: 'assigned',- assignedTo: [1, 2, 3],- tags: ['enterprise'],- tileFilter: {- tileId: 't1',- filter: {- kind: 'custom_property',- definitionId: '11111111-2222-3333-4444-555555555555',- operator: AccountsTableCustomPropertyOperator.GreaterThan,- values: [100],+ describe('serializeAccountsView / deserializeAccountsView', () => {+ it('round-trips a fully populated view', () => {+ const state: AccountsViewState = {+ columns: ['name', 'csm'],+ sortOrder: { column: 'csm' as const, direction: 'desc' as const },+ filters: {+ search: 'acme',+ assignmentStatus: 'assigned',+ assignedTo: [1, 2, 3],+ tags: ['enterprise'],+ tileFilter: {+ tileId: 't1',+ filter: {+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [100],+ },},- },- filterGroups: [- [+ filterGroups: [+ [+ {+ type: PropertyFilterType.AccountCustomProperty as const,+ key: '11111111-2222-3333-4444-555555555555',+ operator: PropertyOperator.Exact,+ value: 'Staged',+ label: 'Tier',+ },+ ],+ ],+ customProperties: [+ {+ type: PropertyFilterType.Account as const,+ key: AccountsTableAccountField.IgnoredAt,+ operator: PropertyOperator.IsSet,+ value: null,+ label: 'Ignored at',+ },{type: PropertyFilterType.AccountCustomProperty as const,key: '11111111-2222-3333-4444-555555555555',operator: PropertyOperator.Exact,- value: 'Staged',+ value: 'Enterprise',label: 'Tier',},],- ],- customProperties: [- {- type: PropertyFilterType.Account as const,- key: AccountsTableAccountField.IgnoredAt,- operator: PropertyOperator.IsSet,- value: null,- label: 'Ignored at',- },- {- type: PropertyFilterType.AccountCustomProperty as const,- key: '11111111-2222-3333-4444-555555555555',- operator: PropertyOperator.Exact,- value: 'Enterprise',- label: 'Tier',- },- ],- },- tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' as const } }],- columnDisplay: {- '11111111-2222-3333-4444-555555555555': { mode: 'sparkline' as const, window_days: 30 },- },- }- const payload = serializeAccountsView(state)- expect(payload.order_by).toEqual(['csm DESC'])- expect(payload.columns).toEqual(['name', 'csm'])- expect(payload.properties).toEqual({ tiles: state.tiles, column_display: state.columnDisplay })- expect(deserializeAccountsView(payload)).toEqual(state)- })+ },+ tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' as const } }],+ columnDisplay: {+ '11111111-2222-3333-4444-555555555555': { mode: 'sparkline' as const, window_days: 30 },+ },+ }+ const payload = serializeAccountsView(state)+ expect(payload.order_by).toEqual(['csm DESC'])+ expect(payload.columns).toEqual(['name', 'csm'])+ expect(payload.properties).toEqual({ tiles: state.tiles, column_display: state.columnDisplay })+ expect(deserializeAccountsView(payload)).toEqual(state)+ })++ it('omits empty filters but always stores the assignment status', () => {+ const payload = serializeAccountsView({+ columns: [...ACCOUNTS_DEFAULT_COLUMNS],+ sortOrder: null,+ filters: {+ search: '',+ assignmentStatus: 'all',+ assignedTo: [],+ tags: [],+ tileFilter: null,+ customProperties: [],+ filterGroups: [],+ },+ tiles: [...DEFAULT_TILES],+ columnDisplay: {},+ })+ // The status is stored even for the `all` default so reopening the view can't be+ // mistaken for a legacy view (no field), which restores as assigned-only.+ expect(payload.filters).toEqual({ assignmentStatus: 'all' })+ expect(payload.order_by).toEqual([])+ expect(payload.properties).toEqual({ tiles: DEFAULT_TILES })+ })- it('omits empty filters but always stores the assignment status', () => {- const payload = serializeAccountsView({- columns: [...ACCOUNTS_DEFAULT_COLUMNS],- sortOrder: null,- filters: {+ it('reads a legacy row with no assignment field as assigned-only', () => {+ const state = deserializeAccountsView({ columns: ['name'], order_by: null, filters: [], properties: {} })+ expect(state.filters).toEqual({search: '',- assignmentStatus: 'all',+ assignmentStatus: 'assigned',assignedTo: [],tags: [],tileFilter: null,customProperties: [],filterGroups: [],- },- tiles: [...DEFAULT_TILES],- columnDisplay: {},- })- // The status is stored even for the `all` default so reopening the view can't be- // mistaken for a legacy view (no field), which restores as assigned-only.- expect(payload.filters).toEqual({ assignmentStatus: 'all' })- expect(payload.order_by).toEqual([])- expect(payload.properties).toEqual({ tiles: DEFAULT_TILES })- })-- it('reads a legacy row with no assignment field as assigned-only', () => {- const state = deserializeAccountsView({ columns: ['name'], order_by: null, filters: [], properties: {} })- expect(state.filters).toEqual({- search: '',- assignmentStatus: 'assigned',- assignedTo: [],- tags: [],- tileFilter: null,- customProperties: [],- filterGroups: [],- })- expect(state.tiles).toEqual(DEFAULT_TILES)- expect(state.sortOrder).toBeNull()- expect(state.columnDisplay).toEqual({})- })+ })+ expect(state.tiles).toEqual(DEFAULT_TILES)+ expect(state.sortOrder).toBeNull()+ expect(state.columnDisplay).toEqual({})+ })- it('reads a legacy unassigned-only row as the unassigned status', () => {- const state = deserializeAccountsView({ columns: ['name'], order_by: null, filters: { unassigned: true } })- expect(state.filters.assignmentStatus).toEqual('unassigned')- })+ it('reads a legacy unassigned-only row as the unassigned status', () => {+ const state = deserializeAccountsView({ columns: ['name'], order_by: null, filters: { unassigned: true } })+ expect(state.filters.assignmentStatus).toEqual('unassigned')+ })- it('keeps an explicit stored status distinct from a legacy default', () => {- expect(deserializeAccountsView({ filters: { assignmentStatus: 'all' } }).filters.assignmentStatus).toEqual(- 'all'- )- expect(deserializeAccountsView({ filters: {} }).filters.assignmentStatus).toEqual('assigned')- })+ it('keeps an explicit stored status distinct from a legacy default', () => {+ expect(deserializeAccountsView({ filters: { assignmentStatus: 'all' } }).filters.assignmentStatus).toEqual(+ 'all'+ )+ expect(deserializeAccountsView({ filters: {} }).filters.assignmentStatus).toEqual('assigned')+ })- it('falls back to default columns when a row has none', () => {- const state = deserializeAccountsView({ columns: [], order_by: [], filters: {}, properties: {} })- expect(state.columns).toEqual(ACCOUNTS_DEFAULT_COLUMNS)+ it('falls back to default columns when a row has none', () => {+ const state = deserializeAccountsView({ columns: [], order_by: [], filters: {}, properties: {} })+ expect(state.columns).toEqual(ACCOUNTS_DEFAULT_COLUMNS)+ })})})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.tsindex b031933ae32b..f104ba93f0b9 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts@@ -1,5 +1,3 @@-import { z } from 'zod'-import {type AssignmentStatus,isAssignmentStatus,@@ -53,7 +51,51 @@ export interface AccountsViewState {columnDisplay: AccountColumnDisplayState}-const ACCOUNTS_VIEW_DRAFT_STORAGE_KEY = 'customerAnalytics.accounts.viewDraft'+export function accountsViewIdStorageKey(teamId: number, userId: string): string {+ return `customerAnalytics.accounts.accountsViewsLogic.${teamId}.${userId}.currentViewId`+}++export interface AccountsViewSelection {+ id: string+ name: string | null+}++export function readAccountsViewSelection(teamId: number, userId?: string): AccountsViewSelection | null {+ try {+ const key = userId+ ? accountsViewIdStorageKey(teamId, userId)+ : `customerAnalytics.accounts.accountsViewsLogic.${teamId}.currentViewId`+ const selection = JSON.parse(window.localStorage.getItem(key) ?? 'null')+ if (typeof selection === 'string' && selection) {+ return { id: selection, name: null }+ }+ if (selection && typeof selection.id === 'string' && selection.id) {+ return { id: selection.id, name: typeof selection.name === 'string' ? selection.name : null }+ }+ return null+ } catch {+ return null+ }+}++export function readAccountsViewId(teamId: number, userId?: string): string | null {+ return readAccountsViewSelection(teamId, userId)?.id ?? null+}++export function writeAccountsViewId(+ teamId: number,+ userId: string,+ id: string | null,+ name: string | null = null+): void {+ try {+ window.localStorage.setItem(accountsViewIdStorageKey(teamId, userId), JSON.stringify(id ? { id, name } : null))+ // Remove the team-only identity only after the scoped preference has been written.+ window.localStorage.removeItem(`customerAnalytics.accounts.accountsViewsLogic.${teamId}.currentViewId`)+ } catch {+ // Storage restrictions must not block view selection.+ }+}type AccountsViewPayload = Pick<ColumnConfigurationApi, 'columns' | 'order_by'> & {filters: Partial<AccountsViewFilters>@@ -122,87 +164,6 @@ export function serializeAccountsView(state: AccountsViewState): AccountsViewPay}}-const StoredTile = z.object({- id: z.string(),- label: z.string(),- metric: z.discriminatedUnion('type', [- z.object({ type: z.literal('count') }),- z.object({- type: z.enum(['sum', 'avg', 'min', 'max', 'median']),- columnExpression: z.string(),- columnLabel: z.string(),- scale: z.number().optional(),- }),- z.object({- type: z.literal('count_threshold'),- columnExpression: z.string(),- columnLabel: z.string(),- operator: z.string(),- value: z.number(),- }),- ]),- caption: z.string().optional(),- format: z.enum(['unit', 'currency', 'percentage']).optional(),-})--const AccountsViewDraft = z.object({- columns: z.array(z.string()),- sortOrder: z.object({ column: z.string(), direction: z.enum(['asc', 'desc']) }).nullable(),- filters: z.object({- search: z.string(),- assignmentStatus: z.enum(['all', 'assigned', 'unassigned']),- assignedTo: z.array(z.number()),- tags: z.array(z.string()),- tileFilter: z- .object({- tileId: z.string(),- filter: z.object({- kind: z.literal('custom_property'),- definitionId: z.string(),- operator: z.string(),- values: z.array(z.number()),- }),- })- .nullable(),- customProperties: z.array(z.object({}).passthrough()),- filterGroups: z- .array(z.array(z.object({}).passthrough()))- .optional()- .default([]),- }),- tiles: z.array(StoredTile),- columnDisplay: z.record(z.string(), z.object({ mode: z.enum(['sparkline', 'trend']), window_days: z.number() })),-})--export function accountsViewDraftStorageKey(teamId: number, userId: string): string {- // Changing this storage key strands existing drafts.- return `${ACCOUNTS_VIEW_DRAFT_STORAGE_KEY}.${teamId}.${userId}`-}--export function readAccountsViewDraft(teamId: number | null, userId: string | null): AccountsViewState | null {- if (teamId === null || userId === null || typeof window === 'undefined') {- return null- }- try {- const raw = window.sessionStorage.getItem(accountsViewDraftStorageKey(teamId, userId))- const draft = AccountsViewDraft.safeParse(raw ? JSON.parse(raw) : null)- return draft.success ? (draft.data as AccountsViewState) : null- } catch {- return null- }-}--export function writeAccountsViewDraft(teamId: number | null, userId: string | null, draft: AccountsViewState): void {- if (teamId === null || userId === null || typeof window === 'undefined') {- return- }- try {- window.sessionStorage.setItem(accountsViewDraftStorageKey(teamId, userId), JSON.stringify(draft))- } catch {- // Browsers can deny session storage. List navigation must still work.- }-}-export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>): AccountsViewState {// The backend represents empty filters as an array.const rawFilters = (view.filters && !Array.isArray(view.filters) ? view.filters : {}) as AccountsViewFiltersRawdiff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.tsindex 3788b2308a4b..fabaaf86774d 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts@@ -2,565 +2,598 @@ import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'-import { useMocks } from '~/mocks/jest'-import type { AccountsTableQuery } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'+import {+ columnConfigurationsCreate,+ columnConfigurationsDestroy,+ columnConfigurationsList,+ columnConfigurationsPartialUpdate,+} from 'products/product_analytics/frontend/generated/api'+import type { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import { ACCOUNTS_DEFAULT_COLUMNS, ACCOUNTS_TAGS_COLUMN, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { accountsLogic, SEARCH_DEBOUNCE_MS } from './accountsLogic'import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'+import { getAccountsBackUrl } from './accountsViewSessionLogic'import { accountsViewsLogic } from './accountsViewsLogic'-import { readAccountsViewDraft, type AccountsViewState, writeAccountsViewDraft } from './accountsViewState'-import { DEFAULT_TILES } from './constants'--const CURRENT_USER_ID = MOCK_DEFAULT_USER.id--const buildView = (overrides: Partial<ColumnConfigurationApi> = {}): ColumnConfigurationApi =>- ({- id: 'view-1',- context_key: 'customer_analytics_accounts_columns',- columns: ['name', 'csm'],- name: 'Enterprise',- filters: { search: 'acme', assignedTo: [1] },- order_by: ['csm DESC'],- properties: { tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' } }] },- visibility: 'shared',- created_by: CURRENT_USER_ID,- created_at: '2026-01-01T00:00:00Z',- updated_at: '2026-01-01T00:00:00Z',- ...overrides,- }) as ColumnConfigurationApi+import { accountsViewIdStorageKey, deserializeAccountsView, readAccountsViewId } from './accountsViewState'+import { ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX, AccountsEvents, DEFAULT_TILES } from './constants'++jest.mock('products/product_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/product_analytics/frontend/generated/api'),+ columnConfigurationsCreate: jest.fn(),+ columnConfigurationsDestroy: jest.fn(),+ columnConfigurationsList: jest.fn(),+ columnConfigurationsPartialUpdate: jest.fn(),+}))++const mockList = jest.mocked(columnConfigurationsList)+const mockCreate = jest.mocked(columnConfigurationsCreate)+const mockDelete = jest.mocked(columnConfigurationsDestroy)+const mockUpdate = jest.mocked(columnConfigurationsPartialUpdate)+const scopedKey = accountsViewIdStorageKey(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)+const legacyKey = `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`+const accountId = '0190da51-0b0e-7000-8000-000000000001'++const buildView = (overrides: Partial<ColumnConfigurationApi> = {}): ColumnConfigurationApi => ({+ id: 'view-1',+ context_key: 'customer_analytics_accounts_columns',+ columns: ['name', 'csm'],+ name: 'Enterprise',+ filters: { search: 'example', assignmentStatus: 'assigned', assignedTo: [1] },+ order_by: ['csm DESC'],+ properties: { tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' } }] },+ visibility: 'shared',+ created_by: MOCK_DEFAULT_USER.id,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ ...overrides,+})++const response = (views: ColumnConfigurationApi[]): Awaited<ReturnType<typeof columnConfigurationsList>> => ({+ count: views.length,+ results: views,+ next: null,+ previous: null,+})++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise+ })+ return { promise, resolve }+}describe('accountsViewsLogic', () => {let logic: ReturnType<typeof accountsViewsLogic.build>- const mountAll = (): void => {- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsLogic().mount()+ const mount = (): void => {logic = accountsViewsLogic()logic.mount()}+ const settle = async (): Promise<void> => {+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(accountsColumnConfigLogic).toFinishAllListeners()+ await expectLogic(accountsLogic).toFinishAllListeners()+ }+ const reload = (): void => {+ logic.unmount()+ initKeaTests()+ userLogic.mount()+ router.actions.push(urls.customerAnalyticsAccounts())+ mount()+ }beforeEach(() => {- // Set up POSTHOG_APP_CONTEXT with MOCK_DEFAULT_USER before initKeaTests so- // the user is pre-loaded (mirrors how the app bootstraps in production).+ localStorage.clear()+ sessionStorage.clear()window.POSTHOG_APP_CONTEXT = {...window.POSTHOG_APP_CONTEXT,current_team: MOCK_DEFAULT_TEAM,current_user: MOCK_DEFAULT_USER,} as anyinitKeaTests()- router.actions.push(urls.customerAnalyticsAccounts())- sessionStorage.clear()userLogic.mount()+ router.actions.push(urls.customerAnalyticsAccounts())+ mockList.mockReset().mockResolvedValue(response([buildView()]))+ mockCreate.mockReset()+ mockDelete.mockReset().mockResolvedValue(undefined)+ mockUpdate.mockReset()})afterEach(() => {+ logic?.unmount()localStorage.clear()sessionStorage.clear()jest.useRealTimers()+ jest.restoreAllMocks()+ resumeKeaLoadersErrors()})- it('lists views on mount', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] } } })- mountAll()- await expectLogic(logic)- .toDispatchActions(['loadViewsSuccess'])- .toMatchValues({- views: [expect.objectContaining({ id: 'view-1' })],+ it.each([scopedKey, legacyKey])(+ 'restores the current server definition from %s, ignoring storage snapshots',+ async (key) => {+ localStorage.setItem(key, JSON.stringify('view-1'))+ const draftKey = `customerAnalytics.accounts.viewDraft.${MOCK_DEFAULT_TEAM.id}.${MOCK_DEFAULT_USER.uuid}`+ const staleDraft = JSON.stringify(+ deserializeAccountsView(buildView({ filters: { search: 'stale draft' } }))+ )+ sessionStorage.setItem(draftKey, staleDraft)+ localStorage.setItem(draftKey, staleDraft)+ const capture = jest.spyOn(posthog, 'capture')+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(logic.values.isDirty).toBe(false)+ expect(router.values.searchParams.view).toBe('view-1')+ expect(router.values.hashParams.view).toBeUndefined()+ expect(JSON.parse(localStorage.getItem(scopedKey)!)).toEqual({ id: 'view-1', name: 'Enterprise' })+ expect(localStorage.getItem(legacyKey)).toBeNull()+ expect(capture).toHaveBeenCalledWith(AccountsEvents.ViewSelected, { visibility: 'shared' })++ accountsLogic.actions.setSearchQuery('unsaved')+ accountsLogic.actions.setTagsFilter(['draft'])+ expect(sessionStorage.getItem(draftKey)).toBe(staleDraft)+ expect(localStorage.getItem(draftKey)).toBe(staleDraft)+ const updated = buildView({+ name: 'Renamed elsewhere',+ columns: ['name'],+ filters: { search: 'fresh server', assignmentStatus: 'all' },})- })-- it('holds the first accounts fetch until a delayed draft decision permits the persisted view', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] } } })- localStorage.setItem(- `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,- JSON.stringify('view-1')- )- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsLogic().mount()- accountsLogic.actions.setViewStateHydrated(false)- logic = accountsViewsLogic()- logic.mount()-- expect(accountsLogic.values.awaitingSavedView).toBe(true)- expect(accountsLogic.values.accountsQuerySource).toBeNull()- expect(accountsLogic.values.metricsQuery).toBeNull()-- await expectLogic(logic).toDispatchActions(['loadViewsSuccess', 'restoreSavedView']).toFinishAllListeners()-- expect(accountsLogic.values.awaitingSavedView).toBe(true)- expect(accountsLogic.values.searchQuery).toBe('')-- await expectLogic(logic, () => accountsLogic.actions.setViewStateHydrated(true))- .toDispatchActions(['restoreSavedView', 'applyView'])- .toFinishAllListeners()-- expect(accountsLogic.values.awaitingSavedView).toBe(false)- expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', 'csm'])- expect(accountsLogic.values.searchQuery).toEqual('acme')- })+ mockList.mockResolvedValue(response([updated]))+ reload()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('fresh server')+ expect(accountsLogic.values.tagsFilter).toEqual([])+ expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name'])+ expect(logic.values.currentView?.name).toBe('Renamed elsewhere')+ expect(logic.values.currentViewName).toBe('Renamed elsewhere')+ expect(JSON.parse(localStorage.getItem(scopedKey)!)).toEqual({ id: 'view-1', name: 'Renamed elsewhere' })+ expect(logic.values.isDirty).toBe(false)+ }+ )it.each([- [false, 'views', true],- [true, 'views', true],- [false, 'relationships', true],- [true, 'relationships', true],- [true, 'views', false],- [true, 'relationships', false],+ [false, false],+ [true, false],+ [false, true],+ [true, true],] as const)(- 'restores a fresh tab with mineOnly=%s, %s loading first, and savedView=%s',- async (mineOnly, firstResponse, savedView) => {- customerAnalyticsSceneLogic.mount()- customerAnalyticsSceneLogic.actions.setMineOnly(mineOnly)- let releaseViews!: () => void- let releaseRelationships!: () => void- const viewsReady = new Promise<void>((resolve) => {- releaseViews = resolve- })- const relationshipsReady = new Promise<void>((resolve) => {- releaseRelationships = resolve- })- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': async () => {- await viewsReady- return { count: 1, results: [buildView()] }- },- '/api/projects/:team_id/account_relationship_definitions/': async () => {- await relationshipsReady- return {- count: 1,- results: [- {- id: '11111111-2222-3333-4444-555555555555',- name: 'CSM',- description: null,- is_single_holder: true,- },- ],- }- },- },- })- if (savedView) {- localStorage.setItem(- `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,- JSON.stringify('view-1')- )- }- mountAll()-- if (firstResponse === 'views') {- releaseViews()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])- releaseRelationships()- } else {- releaseRelationships()- await expectLogic(accountsColumnConfigLogic).toDispatchActions(['loadRelationshipDefinitionsSuccess'])- releaseViews()- }- await expectLogic(logic).toFinishAllListeners()-- expect(accountsColumnConfigLogic.values.selectColumns).toEqual(- savedView ? ['name', 'csm'] : [...ACCOUNTS_DEFAULT_COLUMNS, 'csm']+ 'prefers an explicit ID over the remembered ID and legacy hash (missing=%s, detail=%s)',+ async (missing, detail) => {+ localStorage.setItem(scopedKey, JSON.stringify('view-1'))+ const path = detail ? urls.customerAnalyticsAccount(accountId, 'usage') : urls.customerAnalyticsAccounts()+ router.actions.push(+ path,+ { view: 'view-2', date_from: '-30d', filter_test_accounts: 'true' },+ { view: { search: 'legacy' } })- expect(accountsLogic.values.searchQuery).toBe(savedView ? 'acme' : '')- expect(accountsLogic.values.assignedToFilter).toEqual(savedView ? [1] : [CURRENT_USER_ID])- expect(accountsLogic.values.awaitingSavedView).toBe(false)- expect(logic.values.currentViewId).toBe(savedView ? 'view-1' : null)+ const unrelatedSearch = Object.fromEntries(new URLSearchParams(router.values.location.search))+ delete unrelatedSearch.view+ const linked = buildView({ id: 'view-2', filters: { search: 'linked', assignmentStatus: 'all' } })+ mockList.mockResolvedValue(response(missing ? [buildView()] : [buildView(), linked]))+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe(missing ? '' : 'linked')+ expect(logic.values.currentViewId).toBe(missing ? null : 'view-2')+ expect(Object.fromEntries(new URLSearchParams(router.values.location.search))).toEqual({+ ...unrelatedSearch,+ ...(missing ? {} : { view: 'view-2' }),+ })+ expect(router.values.location.pathname.endsWith(path)).toBe(true)+ expect(router.values.hashParams.view).toBeUndefined()expect(logic.values.isDirty).toBe(false)- if (!savedView) {- expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)).toBeNull()+ expect(readAccountsViewId(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)).toBe(missing ? 'view-1' : 'view-2')+ if (missing) {+ reload()+ await settle()+ expect(logic.values.currentViewId).toBe('view-1')+ expect(accountsLogic.values.searchQuery).toBe('example')}})- it('opens the gate when loading views fails, so the list still fetches', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': () => [500, {}] } })- localStorage.setItem(- `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,- JSON.stringify('view-1')- )- silenceKeaLoadersErrors()- try {- mountAll()- expect(accountsLogic.values.awaitingSavedView).toBe(true)- await expectLogic(logic).toDispatchActions(['loadViewsFailure'])- expect(accountsLogic.values.awaitingSavedView).toBe(false)- } finally {- resumeKeaLoadersErrors()- }- })-- it('applyView hydrates columns, filters, sort, and tiles', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 0, results: [] } } })- mountAll()- const view = buildView({- filters: {- search: 'acme',- tags: ['enterprise'],- assignmentStatus: 'assigned',- assignedTo: [1, 2, 3],- tileFilter: {- tileId: 't1',- filter: {- kind: 'custom_property',- definitionId: '11111111-2222-3333-4444-555555555555',- operator: 'gt',- values: [100],- },- },- },- })- await expectLogic(logic, () => logic.actions.applyView(view)).toFinishAllListeners()-- expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', 'csm'])- expect(accountsLogic.values.searchQuery).toEqual('acme')- expect(accountsLogic.values.tagsFilter).toEqual(['enterprise'])- expect(accountsLogic.values.assignmentStatus).toBe('assigned')- expect(accountsLogic.values.assignedToFilter).toEqual([1, 2, 3])- expect(accountsLogic.values.sortOrder).toEqual({ column: 'csm', direction: 'desc' })- expect(accountsOverviewTilesLogic.values.tiles).toEqual([- { id: 't1', label: 'Accounts', metric: { type: 'count' } },- ])- expect(accountsOverviewTilesLogic.values.tileFilter).toEqual({- tileId: 't1',- filter: {- kind: 'custom_property',- definitionId: '11111111-2222-3333-4444-555555555555',- operator: 'gt',- values: [100],- },- })- expect(logic.values.currentViewId).toEqual('view-1')- })+ it.each([true, false])(+ 'hydrates a cached picker name and clears a missing cached view (exists=%s)',+ async (exists) => {+ localStorage.setItem(scopedKey, JSON.stringify({ id: 'view-1', name: 'Cached name' }))+ const pending = deferred<Awaited<ReturnType<typeof columnConfigurationsList>>>()+ mockList.mockReturnValue(pending.promise)+ mount()+ expect(logic.values.currentViewId).toBe('view-1')+ expect(logic.values.currentViewName).toBe('Cached name')+ expect(logic.values.viewsLoaded).toBe(false)+ expect(logic.values.currentView).toBeNull()+ expect(accountsLogic.values.accountsQuerySource).toBeNull()+ expect(logic.values.isDirty).toBe(false)- it('translates an applied saved view into the Postgres query', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 0, results: [] } } })- mountAll()- await expectLogic(logic, () =>- logic.actions.applyView(- buildView({- columns: ['name'],- filters: { search: 'acme', tags: ['enterprise'], assignedTo: [1, 2] },- order_by: ['name DESC'],- })+ await expectLogic(logic, () =>+ pending.resolve(response(exists ? [buildView({ name: 'Current name' })] : []))+ ).toDispatchActions(['loadViewsSuccess'])+ await settle()+ expect(logic.values.currentViewId).toBe(exists ? 'view-1' : null)+ expect(logic.values.currentViewName).toBe(exists ? 'Current name' : null)+ expect(logic.values.viewsLoaded).toBe(true)+ expect(logic.values.isDirty).toBe(false)+ expect(JSON.parse(localStorage.getItem(scopedKey)!)).toEqual(+ exists ? { id: 'view-1', name: 'Current name' } : null)- ).toFinishAllListeners()-- const source = accountsLogic.values.accountsQuerySource as AccountsTableQuery- expect(source.kind).toBe('AccountsTableQuery')- expect(source.columns).toEqual([{ kind: 'account_field', field: 'name' }])- expect(source.filters).toEqual([- { kind: 'search', query: 'acme' },- { kind: 'tags', tagNames: ['enterprise'] },- { kind: 'assigned_to', userIds: [1, 2] },- ])- })-- it('applies a legacy saved view (no assignment field) as assigned-only', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 0, results: [] } } })- mountAll()- // A view saved before the status field existed must not silently broaden to all.- await expectLogic(logic, () =>- logic.actions.applyView(buildView({ columns: ['name'], filters: { search: 'acme' } }))- ).toFinishAllListeners()+ }+ )- expect(accountsLogic.values.assignmentStatus).toBe('assigned')- const source = accountsLogic.values.accountsQuerySource as AccountsTableQuery- expect(source.filters).toContainEqual({ kind: 'assigned' })+ it('finds an explicit saved view beyond the first page', async () => {+ router.actions.push(urls.customerAnalyticsAccounts(), { view: 'view-2' })+ mockList+ .mockResolvedValueOnce({ ...response([buildView()]), count: 2, next: 'next-page' })+ .mockResolvedValueOnce(response([buildView({ id: 'view-2', filters: { search: 'second page' } })]))+ mount()+ await settle()+ expect(logic.values.currentViewId).toBe('view-2')+ expect(accountsLogic.values.searchQuery).toBe('second page')})- it('does not mark a saved view dirty when normalizing legacy tag columns', async () => {- const view = buildView({- columns: ['accounts.tags.account_id AS account_id', 'accounts.tags.names AS names'],- })- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [view] } } })- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])-- await expectLogic(logic, () => logic.actions.applyView(view)).toFinishAllListeners()-- expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', ACCOUNTS_TAGS_COLUMN])- expect(logic.values.isDirty).toBe(false)+ it('consumes a legacy snapshot without saving it or letting it override later selections', async () => {+ const remembered = { id: 'view-1', name: 'Enterprise' }+ localStorage.setItem(scopedKey, JSON.stringify(remembered))+ router.actions.push(+ urls.customerAnalyticsAccounts(),+ {},+ { view: { search: 'legacy', columns: ['name'], assignedTo: [7] } }+ )+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('legacy')+ expect(accountsLogic.values.assignedToFilter).toEqual([7])+ expect(router.values.hashParams.view).toBeUndefined()+ expect(mockUpdate).not.toHaveBeenCalled()+ expect(mockCreate).not.toHaveBeenCalled()+ expect(JSON.parse(localStorage.getItem(scopedKey)!)).toEqual(remembered)+ logic.actions.selectView('view-1')+ await settle()+ router.actions.push(urls.customerAnalyticsAccount(accountId), router.values.searchParams)+ router.actions.push(urls.customerAnalyticsAccounts(), router.values.searchParams)+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(router.values.searchParams.view).toBe('view-1')})- it('keeps column widths when the selected view changes', async () => {- useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 0, results: [] } } })- mountAll()-- logic.actions.setColumnWidth('name', 320)- logic.actions.setCurrentViewId('view-1')+ it.each(['edit', 'select', 'navigate'] as const)(+ 'does not let a slow restore replace a newer %s',+ async (action) => {+ localStorage.setItem(scopedKey, JSON.stringify('view-1'))+ const pending = deferred<Awaited<ReturnType<typeof columnConfigurationsList>>>()+ mockList.mockReturnValue(pending.promise)+ mount()+ expect(accountsLogic.values.accountsQuerySource).toBeNull()+ expect(accountsLogic.values.metricsQuery).toBeNull()+ expect(logic.values.isDirty).toBe(false)+ if (action === 'edit') {+ accountsLogic.actions.setSearchInput('typed while loading')+ } else if (action === 'select') {+ logic.actions.applyView(buildView({ id: 'view-2', filters: { search: 'new selection' } }))+ accountsLogic.actions.setTagsFilter(['edited selection'])+ } else {+ router.actions.push(urls.customerAnalyticsAccounts(), { view: 'view-2' })+ }+ await expectLogic(logic, () =>+ pending.resolve(+ response([buildView(), buildView({ id: 'view-2', filters: { search: 'new selection' } })])+ )+ ).toDispatchActions(['loadViewsSuccess'])+ await settle()+ expect(accountsLogic.values.searchInput).toBe(action === 'edit' ? 'typed while loading' : 'new selection')+ expect(accountsLogic.values.tagsFilter).toEqual(action === 'select' ? ['edited selection'] : [])+ expect(logic.values.currentViewId).toBe(action === 'edit' ? 'view-1' : 'view-2')+ expect(accountsLogic.values.awaitingSavedView).toBe(false)+ }+ )- await expectLogic(logic).toMatchValues({ columnWidths: { name: 320 } })+ it('keeps restoration gated on load errors and retries without dirty defaults', async () => {+ localStorage.setItem(scopedKey, JSON.stringify('view-1'))+ mockList.mockRejectedValueOnce(new Error('offline'))+ silenceKeaLoadersErrors()+ mount()+ await expectLogic(logic).toDispatchActions(['loadViewsFailure'])+ expect(logic.values.viewsLoadError).toBe(true)+ expect(logic.values.isDirty).toBe(false)+ expect(accountsLogic.values.accountsQuerySource).toBeNull()+ expect(accountsLogic.values.metricsQuery).toBeNull()+ await expectLogic(logic, () => logic.actions.loadViews()).toDispatchActions(['loadViewsSuccess'])+ expect(logic.values.viewsLoadError).toBe(false)+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(logic.values.isDirty).toBe(false)})- it('keeps dirty edits over automatic saved-view restore, then replaces them when the user selects the view', async () => {- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] },- },- })- mountAll()- // Wait for loadViewsSuccess so the view is in views, then select it.- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])- logic.actions.applyView(buildView())- await expectLogic(logic).toMatchValues({ isDirty: false })-+ it('retains edits through the account Back link, metadata saves, and list reloads, but explicit selection replaces them', async () => {+ mount()+ await settle()+ logic.actions.selectView('view-1')accountsLogic.actions.setSearchQuery('changed')- await expectLogic(logic).toMatchValues({ isDirty: true })+ const renamed = buildView({ name: 'Renamed' })+ const pendingSave = deferred<ColumnConfigurationApi>()+ mockUpdate.mockReturnValue(pendingSave.promise)+ logic.actions.updateView({ id: 'view-1', updates: { name: 'Renamed' } })+ accountsLogic.actions.setSearchQuery('changed during save')+ await expectLogic(logic, () => pendingSave.resolve(renamed)).toDispatchActions(['updateViewSuccess'])+ expect(accountsLogic.values.searchQuery).toBe('changed during save')+ const pendingReload = deferred<Awaited<ReturnType<typeof columnConfigurationsList>>>()+ mockList.mockReturnValueOnce(pendingReload.promise).mockResolvedValue(response([renamed]))+ logic.actions.loadViews()+ accountsLogic.actions.setSearchQuery('changed during reload')+ await expectLogic(logic, () => pendingReload.resolve(response([renamed]))).toDispatchActions([+ 'loadViewsSuccess',+ ])+ expect(accountsLogic.values.searchQuery).toBe('changed during reload')+ expect(logic.values.currentView?.name).toBe('Renamed')+ expect(JSON.parse(localStorage.getItem(scopedKey)!)).toEqual({ id: 'view-1', name: 'Renamed' })+ expect(logic.values.isDirty).toBe(true)+ expect(router.values.searchParams.view).toBe('view-1')+ logic.actions.prepareAccountReturn()+ const backUrl = getAccountsBackUrl(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)logic.unmount()- accountsLogic.findMounted()?.unmount()- accountsOverviewTilesLogic.findMounted()?.unmount()- accountsColumnConfigLogic.findMounted()?.unmount()- router.actions.push(urls.customerAnalyticsAccounts())- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])-- expect(accountsLogic.values.searchQuery).toBe('changed')+ expect(accountsLogic.findMounted()).toBeFalsy()+ router.actions.push(urls.customerAnalyticsAccount(accountId))+ router.actions.push(backUrl)+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('changed during reload')expect(logic.values.isDirty).toBe(true)-jest.useFakeTimers()accountsLogic.actions.setSearchInput('stale search')logic.actions.selectView('view-1')await jest.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)- await expectLogic(logic).toFinishAllListeners()+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(logic.values.isDirty).toBe(false)+ })- expect(accountsLogic.values.searchQuery).toBe('acme')+ it.each(['delete', 'inaccessible'] as const)(+ 'clears a selected view after %s and retains column widths',+ async (kind) => {+ mount()+ await settle()+ logic.actions.selectView('view-1')+ logic.actions.setColumnWidth('name', 320)+ accountsLogic.actions.setSearchQuery('unsaved')+ if (kind === 'delete') {+ await expectLogic(logic, () => logic.actions.deleteView({ id: 'view-1' })).toDispatchActions([+ 'deleteViewSuccess',+ ])+ } else {+ mockList.mockResolvedValue(response([]))+ await expectLogic(logic, () => logic.actions.loadViews()).toDispatchActions(['loadViewsSuccess'])+ }+ expect(logic.values.currentViewId).toBeNull()+ expect(router.values.searchParams.view).toBeUndefined()+ expect(accountsLogic.values.searchQuery).toBe('')+ expect(logic.values.isDirty).toBe(false)+ expect(logic.values.columnWidths).toEqual({ name: 320 })+ }+ )++ it('uses ID history for back and forward without restoring snapshots', async () => {+ mockList.mockResolvedValue(response([buildView(), buildView({ id: 'view-2', filters: { search: 'second' } })]))+ mount()+ await settle()+ router.actions.push(urls.customerAnalyticsAccounts(), { view: 'view-1' })+ await settle()+ accountsLogic.actions.setSearchQuery('unsaved')+ router.actions.push(urls.customerAnalyticsAccounts(), { view: 'view-2' })+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('second')+ router.actions.locationChanged({+ ...router.values.currentLocation,+ url: `${urls.customerAnalyticsAccounts()}?view=view-1`,+ method: 'POP',+ pathname: urls.customerAnalyticsAccounts(),+ search: '?view=view-1',+ searchParams: { view: 'view-1' },+ hashParams: {},+ })+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(logic.values.isDirty).toBe(false)+ router.actions.locationChanged({+ ...router.values.currentLocation,+ url: `${urls.customerAnalyticsAccounts()}?view=view-2`,+ method: 'POP',+ pathname: urls.customerAnalyticsAccounts(),+ search: '?view=view-2',+ searchParams: { view: 'view-2' },+ hashParams: {},+ })+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('second')+ accountsLogic.actions.setSearchQuery('unsaved sidebar')+ mockList.mockResolvedValue(response([buildView({ id: 'view-2', filters: { search: 'fresh second' } })]))+ router.actions.push(urls.customerAnalytics())+ router.actions.push(urls.customerAnalyticsAccounts())+ await settle()+ expect(logic.values.currentViewId).toBe('view-2')+ expect(accountsLogic.values.searchQuery).toBe('fresh second')+ expect(router.values.searchParams.view).toBe('view-2')expect(logic.values.isDirty).toBe(false)+ })++ it.each([true, false])('restores a one-use account Back return without URL snapshots (saved=%s)', async (saved) => {+ mount()+ await settle()+ if (saved) {+ logic.actions.selectView('view-1')+ }+ accountsLogic.actions.setSearchQuery('unsaved return')+ accountsLogic.actions.setTagsFilter(['draft tag'])+ logic.actions.prepareAccountReturn()+ const backUrl = getAccountsBackUrl(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)+ const back = new URL(backUrl, 'http://localhost')+ expect(back.searchParams.get('view')).toBe(saved ? 'view-1' : null)+ expect(back.searchParams.get('restore_view')).toBeTruthy()+ expect(backUrl).not.toContain('unsaved')+ expect(back.hash).toBe('')logic.unmount()- accountsLogic.findMounted()?.unmount()- accountsOverviewTilesLogic.findMounted()?.unmount()- accountsColumnConfigLogic.findMounted()?.unmount()- router.actions.push(urls.customerAnalyticsAccounts())- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])+ router.actions.push(urls.customerAnalyticsAccount(accountId))+ router.actions.push(backUrl)+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('unsaved return')+ expect(accountsLogic.values.tagsFilter).toEqual(['draft tag'])+ expect(logic.values.currentViewId).toBe(saved ? 'view-1' : null)+ expect(router.values.searchParams.restore_view).toBeUndefined()++ accountsLogic.actions.setSearchQuery('later edit')+ router.actions.push(urls.customerAnalyticsNotes())+ router.actions.push(backUrl)+ await settle()+ expect(accountsLogic.values.searchQuery).toBe(saved ? 'example' : '')+ expect(accountsLogic.values.tagsFilter).toEqual([])+ expect(logic.values.isDirty).toBe(false)+ expect(router.values.searchParams.restore_view).toBeUndefined()+ })- expect(accountsLogic.values.searchQuery).toBe('acme')+ it('loads the current saved definition when returning from an account without unsaved changes', async () => {+ mount()+ await settle()+ logic.actions.selectView('view-1')+ logic.actions.prepareAccountReturn()+ const backUrl = getAccountsBackUrl(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)+ logic.unmount()+ router.actions.push(urls.customerAnalyticsAccount(accountId))+ mockList.mockResolvedValue(response([buildView({ filters: { search: 'updated by teammate' } })]))+ router.actions.push(backUrl)+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('updated by teammate')expect(logic.values.isDirty).toBe(false)})- it('keeps a cleared all-default draft instead of auto-applying the selected saved view', async () => {- const clearedDraft: AccountsViewState = {- columns: [...ACCOUNTS_DEFAULT_COLUMNS],- sortOrder: null,- filters: {- search: '',- assignmentStatus: 'all',- assignedTo: [],- tags: [],- tileFilter: null,- customProperties: [],- filterGroups: [],- },- tiles: [...DEFAULT_TILES],- columnDisplay: {},- }- writeAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid, clearedDraft)- localStorage.setItem(- `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,- JSON.stringify('view-1')- )- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] },- },- })- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])+ it('ignores a return token copied into a fresh app context', async () => {+ mount()+ await settle()+ logic.actions.selectView('view-1')+ accountsLogic.actions.setSearchQuery('unsaved return')+ logic.actions.prepareAccountReturn()+ const backUrl = getAccountsBackUrl(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)+ logic.unmount()+ initKeaTests()+ userLogic.mount()+ router.actions.push(backUrl)+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('example')+ expect(logic.values.isDirty).toBe(false)+ expect(router.values.searchParams.restore_view).toBeUndefined()+ })+ it('resets scoped memory on user and project changes and rejects an older project response', async () => {+ mount()+ await settle()+ logic.actions.selectView('view-1')+ accountsLogic.actions.setSearchQuery('private draft')+ const pending = deferred<Awaited<ReturnType<typeof columnConfigurationsList>>>()+ mockList.mockReturnValueOnce(pending.promise).mockResolvedValue(response([]))+ logic.actions.loadViews()+ await expectLogic(logic, () =>+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 })+ ).toDispatchActions(['loadViewsSuccess'])+ pending.resolve(response([buildView()]))+ await settle()expect(accountsLogic.values.searchQuery).toBe('')+ expect(logic.values.currentViewId).toBeNull()+ expect(logic.values.views).toEqual([])+ await expectLogic(logic, () =>+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, uuid: 'other-user' })+ ).toDispatchActions(['loadViewsSuccess'])+ expect(accountsLogic.values.searchQuery).toBe('')+ expect(logic.values.currentViewId).toBeNull()+ accountsLogic.actions.setSearchQuery('edits before leaving')+ logic.unmount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, uuid: 'other-user' })+ mount()+ await settle()+ expect(accountsLogic.values.searchQuery).toBe('')+ })++ it('does not restore a persisted My accounts preference in a fresh Accounts view', async () => {+ customerAnalyticsSceneLogic.mount()+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ mockList.mockResolvedValue(response([]))+ mount()+ await settle()expect(accountsLogic.values.assignmentStatus).toBe('all')- expect(logic.values.currentViewId).toBe('view-1')- expect(logic.values.isDirty).toBe(true)+ expect(accountsLogic.values.assignedToFilter).toEqual([])+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)})- it('deleteView clears currentViewId when the active view is removed', async () => {- useMocks({- get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] } },- delete: { '/api/projects/:team_id/column_configurations/:id/': [204] },- })- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])- logic.actions.applyView(buildView())- await expectLogic(logic, () => logic.actions.deleteView({ id: 'view-1' }))- .toDispatchActions(['deleteViewSuccess'])- .toMatchValues({ currentViewId: null })+ it('normalizes legacy saved columns without marking the view dirty', async () => {+ const view = buildView({ columns: ['accounts.tags.account_id AS account_id', 'accounts.tags.names AS names'] })+ mockList.mockResolvedValue(response([view]))+ localStorage.setItem(scopedKey, JSON.stringify(view.id))+ mount()+ await settle()+ expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', ACCOUNTS_TAGS_COLUMN])+ expect(logic.values.isDirty).toBe(false)})- it('creates a view from the current state', async () => {- let createdBody: Record<string, unknown> | null = null- useMocks({- get: { '/api/projects/:team_id/column_configurations/': { count: 0, results: [] } },- post: {- '/api/projects/:team_id/column_configurations/': async ({ request }) => {- createdBody = (await request.json()) as Record<string, unknown>- return [201, buildView({ name: 'New view', visibility: 'private' })]- },- },+ it('creates and updates views using the existing snapshot schema', async () => {+ const created = buildView({+ name: 'New view',+ visibility: 'private',+ columns: [...ACCOUNTS_DEFAULT_COLUMNS],+ order_by: [],+ filters: { search: 'current state', assignmentStatus: 'all' },+ properties: { tiles: [...DEFAULT_TILES] },})- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])-+ mockCreate.mockResolvedValue(created)+ mockList.mockResolvedValue(response([created]))+ mount()+ await settle()+ accountsLogic.actions.setSearchQuery('current state')logic.actions.setViewFormValues({ name: ' New view ', visibility: 'private' })- await expectLogic(logic, () => logic.actions.submitViewForm()).toDispatchActions([- 'applyView',- 'submitViewFormSuccess',- ])-- expect(createdBody).toEqual(+ await expectLogic(logic, () => logic.actions.submitViewForm()).toDispatchActions(['submitViewFormSuccess'])+ expect(mockCreate).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),expect.objectContaining({context_key: 'customer_analytics_accounts_columns',name: 'New view',visibility: 'private',+ filters: { search: 'current state', assignmentStatus: 'all' },}))- })-- it('edit seeds the form and patches the trimmed name and visibility', async () => {- let patchedBody: Record<string, unknown> | null = null- const sharedView = buildView({ created_by: 999 })- useMocks({- get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [sharedView] } },- patch: {- '/api/projects/:team_id/column_configurations/:id/': async ({ request }) => {- patchedBody = (await request.json()) as Record<string, unknown>- return [200, buildView({ created_by: CURRENT_USER_ID, name: 'Renamed', visibility: 'private' })]- },- },- })- mountAll()- await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])- logic.actions.applyView(sharedView)- expect(logic.values.canEditCurrentView).toBe(true)-- await expectLogic(logic, () => logic.actions.setViewToEdit('view-1'))- .toDispatchActions(['setViewFormValues'])- .toMatchValues({- viewToEdit: 'view-1',- viewForm: { name: 'Enterprise', visibility: 'shared' },- })-- logic.actions.setViewFormValues({ name: ' Renamed ', visibility: 'private' })- await expectLogic(logic, () => logic.actions.submitViewForm())- .toDispatchActions(['updateView', 'updateViewSuccess'])- .toMatchValues({ viewToEdit: null })- expect(patchedBody).toEqual({ name: 'Renamed', visibility: 'private' })- })-- it('migrates localStorage tiles into the creator-owned default row exactly once', async () => {- const customTiles = [{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }]- let patchedBody: any = null- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': {- count: 1,- results: [buildView({ properties: {} })],- },- },- patch: {- '/api/projects/:team_id/column_configurations/:id/': async ({ request }) => {- patchedBody = await request.json()- return [200, buildView({ properties: patchedBody.properties })]- },- },- })- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsOverviewTilesLogic.actions.setTiles(customTiles)- accountsLogic().mount()- logic = accountsViewsLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions([- 'loadViewsSuccess',- 'patchViewProperties',- 'patchViewPropertiesSuccess',+ accountsLogic.actions.setSearchQuery('content update')+ mockUpdate.mockResolvedValue(buildView({ filters: { search: 'content update', assignmentStatus: 'all' } }))+ await expectLogic(logic, () => logic.actions.updateView({ id: 'view-1', updates: {} })).toDispatchActions([+ 'updateViewSuccess',])- expect(patchedBody.properties).toEqual({ tiles: customTiles })- })-- it('does not migrate when localStorage tiles are the defaults', async () => {- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': {- count: 1,- results: [buildView({ properties: {} })],- },- },- })- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsOverviewTilesLogic.actions.setTiles([...DEFAULT_TILES])- accountsLogic().mount()- logic = accountsViewsLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadViewsSuccess']).toFinishAllListeners()- expect(logic.values.views[0].properties).toEqual({})- })-- it('does not migrate into a row the user did not create', async () => {- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': {- count: 1,- results: [buildView({ properties: {}, created_by: 999 })],- },- },- })- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsOverviewTilesLogic.actions.setTiles([{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }])- accountsLogic().mount()- logic = accountsViewsLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadViewsSuccess']).toFinishAllListeners()- expect(logic.values.views[0].properties).toEqual({})+ expect(mockUpdate).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ 'view-1',+ expect.objectContaining({ filters: { search: 'content update', assignmentStatus: 'all' } })+ )})- it('preserves migrated tiles when the migrated row is the restored current view', async () => {- const customTiles = [{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }]+ it('does not migrate legacy tiles over a fetched server definition', async () => {+ mockList.mockResolvedValue(response([buildView({ properties: {} })]))+ localStorage.setItem(scopedKey, JSON.stringify('view-1'))localStorage.setItem(- `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,- JSON.stringify('view-1')+ `${ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX}legacy.tiles`,+ JSON.stringify([{ id: 'mine', label: 'Mine', metric: { type: 'count' } }]))- useMocks({- get: {- '/api/projects/:team_id/column_configurations/': {- count: 1,- results: [buildView({ properties: {} })],- },- },- patch: {- '/api/projects/:team_id/column_configurations/:id/': async ({ request }) => {- const body = (await request.json()) as any- return [200, buildView({ properties: body.properties })]- },- },- })- accountsColumnConfigLogic().mount()- accountsOverviewTilesLogic().mount()- accountsOverviewTilesLogic.actions.setTiles(customTiles)- accountsLogic().mount()- logic = accountsViewsLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadViewsSuccess', 'patchViewProperties', 'applyView'])- expect(accountsOverviewTilesLogic.values.tiles).toEqual(customTiles)+ mount()+ await settle()+ expect(mockUpdate).not.toHaveBeenCalled()+ expect(accountsOverviewTilesLogic.values.tiles).toEqual(DEFAULT_TILES)+ expect(logic.values.isDirty).toBe(false)})})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.tsindex 56b01e57de1d..f8a5df774ee0 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts@@ -2,12 +2,12 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reduimport { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'-import { router } from 'kea-router'+import { combineUrl, router } from 'kea-router'import posthog from 'posthog-js'+import { v4 as uuidv4 } from 'uuid'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getCurrentTeamId } from 'lib/utils/getAppContext'-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { objectsEqual } from 'lib/utils/objects'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -27,30 +27,33 @@ import type {import type { UserType } from '../../../../../frontend/src/types'import { ACCOUNTS_COLUMN_CONFIG_KEY } from './accountsColumnConfigLogic'import { accountsLogic, type ApplyAccountsViewStateOptions } from './accountsLogic'+import { getAccountsViewSession } from './accountsViewSessionLogic'import {- AccountsViewProperties,+ AccountsViewSelection,AccountsViewState,deserializeAccountsView,+ readAccountsViewId,+ readAccountsViewSelection,serializeAccountsView,+ writeAccountsViewId,} from './accountsViewState'-import { AccountsEvents, DEFAULT_TILES } from './constants'+import { AccountsEvents } from './constants'export type ViewVisibility = 'private' | 'shared'export type AccountColumnWidthState = Record<string, number>-function shouldAutoApplySavedView(): boolean {- const hasSharedView =- typeof router.values.hashParams?.view === 'object' &&- router.values.hashParams.view !== null &&- !Array.isArray(router.values.hashParams.view)- return (- removeProjectIdIfPresent(router.values.location.pathname) === urls.customerAnalyticsAccounts() && !hasSharedView- )+function getInitialAccountsViewSelection(teamId: number, userId: string): AccountsViewSelection | null {+ const session = getAccountsViewSession(teamId, userId)+ const remembered = readAccountsViewSelection(teamId, userId) ?? readAccountsViewSelection(teamId)+ const id = session.initialized+ ? session.currentViewId+ : (session.reference ?? (session.allowRemembered ? (remembered?.id ?? null) : null))+ return id ? { id, name: remembered?.id === id ? remembered.name : null } : null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountsViewsLogicValues {- draftRestored: boolean // accountsLogic+ awaitingSavedView: boolean // accountsLogicviewState: AccountsViewState // accountsLogicviewStateHydrated: boolean // accountsLogiccurrentTeamId: number | null // teamLogic@@ -59,6 +62,7 @@ export interface accountsViewsLogicValues {columnWidths: AccountColumnWidthStatecurrentView: ColumnConfigurationApi | nullcurrentViewId: string | null+ currentViewName: string | nullisCreating: booleanisDirty: booleanisViewFormSubmitting: boolean@@ -92,6 +96,8 @@ export interface accountsViewsLogicValues {viewToDelete: string | nullviewToEdit: string | nullviews: ColumnConfigurationApi[]+ viewsLoadError: boolean+ viewsLoaded: booleanviewsLoading: boolean}@@ -113,6 +119,9 @@ export interface accountsViewsLogicActions {applyView: (view: ColumnConfigurationApi) => {view: ColumnConfigurationApi}+ clearView: (remember?: boolean) => {+ remember: boolean+ }deleteView: ({ id }: { id: string }) => {id: string}@@ -134,7 +143,7 @@ export interface accountsViewsLogicActions {id: string}}- loadViews: () => any+ loadViews: (_?: unknown) => unknownloadViewsFailure: (error: string,errorObject?: any@@ -144,38 +153,20 @@ export interface accountsViewsLogicActions {}loadViewsSuccess: (views: ColumnConfigurationApi[],- payload?: any+ payload?: unknown) => {views: ColumnConfigurationApi[]- payload?: any- }- patchViewProperties: ({ id, properties }: { id: string; properties: AccountsViewProperties }) => {- id: string- properties: AccountsViewProperties- }- patchViewPropertiesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any+ payload?: unknown}- patchViewPropertiesSuccess: (- views: ColumnConfigurationApi[],- payload?: {- id: string- properties: AccountsViewProperties- }- ) => {- views: ColumnConfigurationApi[]- payload?: {- id: string- properties: AccountsViewProperties- }+ prepareAccountReturn: () => {+ value: true}reportColumnResize: () => {value: true}+ resetLoadedViews: () => {+ value: true+ }resetViewForm: (values?: { name: string; visibility: ViewVisibility }) => {values?: {name: string@@ -195,8 +186,14 @@ export interface accountsViewsLogicActions {column: stringwidth: number}- setCurrentViewId: (id: string | null) => {+ setCurrentViewId: (+ id: string | null,+ remember?: boolean,+ name?: string | null+ ) => {id: string | null+ name: string | null+ remember: boolean}setIsCreating: (isCreating: boolean) => {isCreating: boolean@@ -284,7 +281,11 @@ export interface accountsViewsLogicMeta {__keaTypeGenInternalSelectorTypes: {liveViewState: (viewState: AccountsViewState) => AccountsViewStatecurrentView: (views: ColumnConfigurationApi[], currentViewId: string | null) => ColumnConfigurationApi | null- isDirty: (currentView: ColumnConfigurationApi | null, liveViewState: AccountsViewState) => boolean+ isDirty: (+ currentView: ColumnConfigurationApi | null,+ liveViewState: AccountsViewState,+ awaitingSavedView: boolean+ ) => booleancanEditCurrentView: (currentView: ColumnConfigurationApi | null) => boolean}}@@ -305,30 +306,54 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([userLogic,['user'],accountsLogic,- ['viewState', 'draftRestored', 'viewStateHydrated'],+ ['viewState', 'viewStateHydrated', 'awaitingSavedView'],],actions: [accountsLogic, ['applyViewState', 'setAwaitingSavedView', 'syncViewStateToUrl']],})),- actions({+ actions(({ values }) => ({selectView: (id: string) => ({ id }),applyView: (view: ColumnConfigurationApi) => ({ view }),- setCurrentViewId: (id: string | null) => ({ id }),+ setCurrentViewId: (id: string | null, remember: boolean = true, name: string | null = null) => ({+ id,+ remember,+ name: id ? (name ?? values.views.find((view) => view.id === id)?.name ?? null) : null,+ }),setColumnWidth: (column: string, width: number) => ({ column, width }),reportColumnResize: true,setIsCreating: (isCreating: boolean) => ({ isCreating }),setViewToDelete: (id: string | null) => ({ id }),setViewToEdit: (id: string | null) => ({ id }),restoreSavedView: true,- }),- loaders(({ values }) => ({+ prepareAccountReturn: true,+ clearView: (remember: boolean = true) => ({ remember }),+ resetLoadedViews: true,+ })),+ loaders(({ values, cache }) => ({views: [[] as ColumnConfigurationApi[],{- loadViews: async (): Promise<ColumnConfigurationApi[]> => {- const response = await columnConfigurationsList(String(values.currentTeamId), {- context_key: ACCOUNTS_COLUMN_CONFIG_KEY,- })- return response.results+ loadViews: async (_: unknown = undefined, breakpoint): Promise<ColumnConfigurationApi[]> => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ const revision = session.revision+ const projectId = String(values.currentTeamId)+ const views: ColumnConfigurationApi[] = []+ while (true) {+ const response = await columnConfigurationsList(projectId, {+ context_key: ACCOUNTS_COLUMN_CONFIG_KEY,+ offset: views.length,+ })+ breakpoint()+ if (session !== getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)) {+ return values.views+ }+ views.push(...response.results)+ if (!response.next || response.results.length === 0) {+ break+ }+ }+ cache.loadedScope = session.scope+ cache.loadedRevision = revision+ return views},updateView: async ({id,@@ -337,40 +362,43 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([id: stringupdates: PatchedColumnConfigurationApi}): Promise<ColumnConfigurationApi[]> => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)const data =Object.keys(updates).length === 0 ? serializeAccountsView(values.liveViewState) : updatesconst response = await columnConfigurationsPartialUpdate(String(values.currentTeamId), id, data)+ if (session !== getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)) {+ return values.views+ }return values.views.map((view) => (view.id === id ? response : view))},deleteView: async ({ id }: { id: string }): Promise<ColumnConfigurationApi[]> => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)await columnConfigurationsDestroy(String(values.currentTeamId), id)+ if (session !== getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)) {+ return values.views+ }return values.views.filter((view) => view.id !== id)},- patchViewProperties: async ({- id,- properties,- }: {- id: string- properties: AccountsViewProperties- }): Promise<ColumnConfigurationApi[]> => {- const response = await columnConfigurationsPartialUpdate(String(values.currentTeamId), id, {- properties,- })- return values.views.map((view) => (view.id === id ? response : view))- },},],})),reducers(() => ({- currentViewId: [- null as string | null,+ views: [[] as ColumnConfigurationApi[], { resetLoadedViews: () => [] }],+ currentViewId: [null as string | null, { setCurrentViewId: (_, { id }) => id }],+ currentViewName: [null as string | null, { setCurrentViewId: (_, { name }) => name }],+ viewsLoaded: [+ false,{- persist: true,- storageKey: `customerAnalytics.accounts.accountsViewsLogic.${getCurrentTeamId()}.currentViewId`,+ loadViewsSuccess: () => true,+ resetLoadedViews: () => false,},+ ],+ viewsLoadError: [+ false,{- setCurrentViewId: (_, { id }) => id,- deleteViewSuccess: (state, { views }) => (state && !views.find((v) => v.id === state) ? null : state),+ loadViews: () => false,+ loadViewsSuccess: () => false,+ loadViewsFailure: () => true,},],columnWidths: [@@ -414,9 +442,13 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([views.find((view) => view.id === currentViewId) ?? null,],isDirty: [- (s) => [s.currentView, s.liveViewState],- (currentView: ColumnConfigurationApi | null, liveViewState: AccountsViewState): boolean =>- currentView+ (s) => [s.currentView, s.liveViewState, s.awaitingSavedView],+ (+ currentView: ColumnConfigurationApi | null,+ liveViewState: AccountsViewState,+ awaitingSavedView: boolean+ ): boolean =>+ currentView && !awaitingSavedView? !objectsEqual(serializeAccountsView(deserializeAccountsView(currentView)),serializeAccountsView(liveViewState)@@ -437,23 +469,58 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([actions.updateView({ id: values.viewToEdit, updates: { name: name.trim(), visibility } })return}+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ const revision = session.revision+ const selectedId = session.currentViewIdconst response = await columnConfigurationsCreate(String(values.currentTeamId), {...serializeAccountsView(values.liveViewState),context_key: ACCOUNTS_COLUMN_CONFIG_KEY,name: name.trim(),visibility,})+ if (session !== getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)) {+ return+ }actions.loadViews()- actions.applyView(response)+ if (session.revision === revision) {+ actions.applyView(response)+ } else if (session.currentViewId === selectedId) {+ session.revision+++ actions.setCurrentViewId(response.id, true, response.name ?? null)+ actions.syncViewStateToUrl()+ }actions.resetViewForm()posthog.capture(AccountsEvents.ViewSaved, { visibility }) // [PostHog] Event: dynamic event name},},})),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({reportColumnResize: () => {posthog.capture(AccountsEvents.ColumnResized) // [PostHog] Event: dynamic event name},+ prepareAccountReturn: () => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ const state = session.state ?? values.liveViewState+ const dirty =+ !values.currentView ||+ !objectsEqual(+ serializeAccountsView(state),+ serializeAccountsView(deserializeAccountsView(values.currentView))+ )+ const token = uuidv4()+ const { view: _, restore_view: __, ...search } = router.values.searchParams+ session.returnView = {+ token,+ url: combineUrl(urls.customerAnalyticsAccounts(), {+ ...search,+ ...(session.currentViewId ? { view: session.currentViewId } : {}),+ restore_view: token,+ }).url,+ state: dirty ? state : null,+ viewId: session.currentViewId,+ columnMode: session.columnMode,+ }+ },selectView: ({ id }) => {const view = values.views.find((v) => v.id === id)if (view) {@@ -461,12 +528,22 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([}},applyView: ({ view }) => {- const state = deserializeAccountsView(view)- actions.applyViewState(state, { source: 'saved_view', columns: 'restore' })+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ session.currentViewId = view.id+ session.initialized = true+ actions.setCurrentViewId(view.id, true, view.name ?? null)+ actions.applyViewState(deserializeAccountsView(view), { source: 'saved_view', columns: 'restore' })+ actions.setAwaitingSavedView(false)actions.syncViewStateToUrl()- actions.setCurrentViewId(view.id)posthog.capture(AccountsEvents.ViewSelected, { visibility: view.visibility }) // [PostHog] Event: dynamic event name},+ setCurrentViewId: ({ id, remember, name }) => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ session.currentViewId = id+ if (remember && values.currentTeamId !== null && values.user?.uuid) {+ writeAccountsViewId(values.currentTeamId, values.user.uuid, id, name)+ }+ },setViewToEdit: ({ id }) => {const view = id ? values.views.find((candidate) => candidate.id === id) : undefinedif (view) {@@ -479,12 +556,18 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([if (payload && Object.keys(payload.updates).length > 0) {actions.resetViewForm()}+ if (payload?.id === values.currentViewId) {+ actions.setCurrentViewId(values.currentViewId)+ }},updateViewFailure: ({ error }) => {posthog.captureException(error)lemonToast.error('Failed to update view')},- deleteViewSuccess: () => {+ deleteViewSuccess: ({ payload }) => {+ if (payload?.id === getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null).currentViewId) {+ actions.clearView()+ }lemonToast.success('View deleted')posthog.capture(AccountsEvents.ViewDeleted) // [PostHog] Event: dynamic event name},@@ -495,57 +578,108 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([loadViewsFailure: ({ error }) => {posthog.captureException(error)lemonToast.error('Failed to load views')- actions.setAwaitingSavedView(false)},submitViewFormFailure: ({ error }) => {posthog.captureException(error)lemonToast.error('Failed to save view')},- patchViewPropertiesFailure: ({ error }) => {- // Background migration failures report the exception without a toast.- posthog.captureException(error)- },[accountsLogic.actionTypes.setViewStateHydrated]: () => {- actions.restoreSavedView()+ if (!values.viewStateHydrated || values.currentTeamId === null || !values.user?.uuid) {+ return+ }+ const session = getAccountsViewSession(values.currentTeamId, values.user.uuid)+ if (cache.requestedScope !== session.scope) {+ cache.requestedScope = session.scope+ cache.requestedRevision = session.revision+ actions.resetLoadedViews()+ const selection = getInitialAccountsViewSelection(values.currentTeamId, values.user.uuid)+ actions.setCurrentViewId(selection?.id ?? null, false, selection?.name ?? null)+ actions.loadViews()+ } else if (!session.initialized && cache.requestedRevision !== session.revision) {+ cache.requestedRevision = session.revision+ const selection = getInitialAccountsViewSelection(values.currentTeamId, values.user.uuid)+ actions.setCurrentViewId(selection?.id ?? null, false, selection?.name ?? null)+ actions.loadViews()+ } else {+ actions.restoreSavedView()+ }},loadViewsSuccess: () => {actions.restoreSavedView()},+ clearView: ({ remember }) => {+ const session = getAccountsViewSession(values.currentTeamId, values.user?.uuid ?? null)+ actions.applyViewState(deserializeAccountsView({ filters: { assignmentStatus: 'all' } }), {+ source: 'defaults',+ columns: 'defaults',+ })+ session.state = values.liveViewState+ session.initialized = true+ actions.setCurrentViewId(null, remember)+ actions.setAwaitingSavedView(false)+ actions.syncViewStateToUrl()+ },restoreSavedView: () => {- if (!values.viewStateHydrated || values.viewsLoading) {+ if (+ !values.viewStateHydrated ||+ values.viewsLoading ||+ values.viewsLoadError ||+ values.currentTeamId === null ||+ !values.user?.uuid+ ) {return}-- let migratedView: ColumnConfigurationApi | null = null- if (!values.draftRestored && !objectsEqual(values.liveViewState.tiles, DEFAULT_TILES)) {- const candidate = values.views.find(- (view) =>- view.created_by === values.user?.id &&- !(view.properties as AccountsViewProperties | undefined)?.tiles?.length- )- if (candidate) {- actions.patchViewProperties({ id: candidate.id, properties: { tiles: values.liveViewState.tiles } })- // Use patched tiles because `views` still holds the stale row.- migratedView = { ...candidate, properties: { tiles: values.liveViewState.tiles } }- }+ const session = getAccountsViewSession(values.currentTeamId, values.user.uuid)+ if (cache.loadedScope !== session.scope) {+ return}-- if (values.currentViewId && !values.draftRestored && shouldAutoApplySavedView()) {- const view =- migratedView?.id === values.currentViewId- ? migratedView- : values.views.find((v) => v.id === values.currentViewId)- if (view) {- actions.applyView(view)+ if (!session.initialized && cache.loadedRevision !== session.revision) {+ cache.requestedRevision = session.revision+ actions.loadViews()+ return+ }+ if (session.initialized) {+ if (+ session.currentViewId &&+ cache.loadedRevision === session.revision &&+ !values.views.some((view) => view.id === session.currentViewId)+ ) {+ actions.clearView()+ } else {+ const saved = values.views.find((view) => view.id === session.currentViewId)+ actions.setCurrentViewId(+ session.currentViewId,+ !!session.currentViewId,+ saved?.name ?? values.currentViewName+ )}+ actions.setAwaitingSavedView(false)+ if (session.currentViewId && router.values.searchParams.view !== session.currentViewId) {+ actions.syncViewStateToUrl()+ }+ return+ }+ const explicitId = session.reference ?? null+ const rememberedId =+ readAccountsViewId(values.currentTeamId, values.user.uuid) ?? readAccountsViewId(values.currentTeamId)+ const id = explicitId ?? (session.allowRemembered ? rememberedId : null)+ const view = id ? values.views.find((candidate) => candidate.id === id) : null+ session.initialized = true+ if (view) {+ actions.applyView(view)+ } else {+ actions.clearView(!explicitId || explicitId === rememberedId)}- actions.setAwaitingSavedView(false)},})),- afterMount(({ actions, values }) => {- if (values.currentViewId && !values.draftRestored && shouldAutoApplySavedView()) {- actions.setAwaitingSavedView(true)+ afterMount(({ actions, values, cache }) => {+ if (values.currentTeamId !== null && values.user?.uuid) {+ const session = getAccountsViewSession(values.currentTeamId, values.user.uuid)+ cache.requestedScope = session.scope+ cache.requestedRevision = session.revision+ const selection = getInitialAccountsViewSelection(values.currentTeamId, values.user.uuid)+ actions.setCurrentViewId(selection?.id ?? null, false, selection?.name ?? null)+ actions.loadViews()}- actions.loadViews()}),])diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.tsindex 23fa48586e65..810a77a2aa7a 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts@@ -23,10 +23,12 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { objectsEqual } from 'lib/utils/objects'import { Scene } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { tagsModel } from '~/models/tagsModel'-import { Breadcrumb } from '~/types'+import { Breadcrumb, UserType } from '~/types'import {cleanDomains,@@ -36,6 +38,7 @@ import {AccountExpansionTab,getVisibleAccountExpansionTab,} from 'products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic'+import { getAccountsBackUrl } from 'products/customer_analytics/frontend/components/Accounts/accountsViewSessionLogic'import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'import {accountsByExternalIdRetrieve,@@ -116,6 +119,8 @@ function isAccountNotFound(error: unknown): boolean {export interface customerAnalyticsAccountSceneLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicreceivedFeatureFlags: boolean // featureFlagLogic+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogicaccount: AccountApi | nullaccountEditorOpen: booleanaccountEditorOpenedValues: AccountEditFormValues@@ -245,7 +250,12 @@ export interface customerAnalyticsAccountSceneLogicMeta {accountLoadError: unknown,arg: boolean) => boolean- breadcrumbs: (account: AccountApi | null) => Breadcrumb[]+ breadcrumbs: (+ account: AccountApi | null,+ user: UserType | null,+ currentTeamId: number | null,+ arg: any+ ) => Breadcrumb[]}}@@ -272,7 +282,14 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc`${props.projectId ?? 'unknown'}:${props.externalId ? 'external' : 'id'}:${props.externalId ?? props.accountId ?? 'invalid'}`),connect(() => ({- values: [featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],+ values: [+ featureFlagLogic,+ ['featureFlags', 'receivedFeatureFlags'],+ teamLogic,+ ['currentTeamId'],+ userLogic,+ ['user'],+ ],actions: [featureFlagLogic, ['setFeatureFlags']],})),actions({@@ -421,12 +438,17 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc): boolean => invalidRoute || (!account && !accountLoading && isAccountNotFound(accountLoadError)),],breadcrumbs: [- (s) => [s.account],- (account: AccountApi | null): Breadcrumb[] => [+ (s) => [s.account, s.user, s.currentTeamId, (_, props) => props.projectId],+ (+ account: AccountApi | null,+ user: UserType | null,+ currentTeamId: number | null,+ projectId: number | undefined+ ): Breadcrumb[] => [{key: Scene.CustomerAnalytics,name: 'Accounts',- path: urls.customerAnalyticsAccounts(),+ path: getAccountsBackUrl(currentTeamId === projectId ? currentTeamId : null, user?.uuid ?? null),iconType: 'cohort',},{