: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(notebooks): keep notebooks and their insights loaded across navigation (#118543)
Marius Andra3000f1e144dd
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsxindex c09fcca8db5c..0877ed73c18d 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditableCodeBlock.tsx@@ -190,10 +190,9 @@ export function EditableCodeBlock({return}- const selection = window.getSelection()const shouldSkipOwnInputSync =- (document.activeElement === element || isSelectionAnchoredInsideElement(selection, element)) &&- skipDomSyncForTextRef.current === node.text+ skipDomSyncForTextRef.current === node.text &&+ (document.activeElement === element || isSelectionAnchoredInsideElement(window.getSelection(), element))skipDomSyncForTextRef.current = nullif (shouldSkipOwnInputSync) {diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsxindex e57bd7d5d9e6..2235ab9442b5 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditableListBlock.tsx@@ -330,7 +330,8 @@ export function EditableListItemContent({// While the caret is inside the item, the DOM is the source of the latest model state:// rewriting innerHTML would destroy the caret mid-typing, so only sync when the live DOM// does not already represent the same content.- const selection = window.getSelection()+ // An empty element can't already hold the content, so it skips the selection read and its forced layout.+ const selection = element.firstChild ? window.getSelection() : nullif (selection?.anchorNode &&element.contains(selection.anchorNode) &&diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableTableBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableTableBlock.tsxindex 0f02a4f1be1f..ec7ed81152b1 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditableTableBlock.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditableTableBlock.tsx@@ -637,7 +637,7 @@ export function EditableTableCellContent({// While the caret is inside the cell, the DOM is the source of the latest model state:// rewriting innerHTML would destroy the caret mid-typing, so only sync when the live DOM// does not already represent the same content.- const selection = window.getSelection()+ const selection = element.firstChild ? window.getSelection() : nullif (selection?.anchorNode &&element.contains(selection.anchorNode) &&diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsxindex 0529ef208599..77061d67685f 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx@@ -128,13 +128,13 @@ export function EditableTextBlock({return}- const selection = window.getSelection()const rootEditableInputHtml = rootEditableInputHtmlByNodeIdRef.current[node.id]delete rootEditableInputHtmlByNodeIdRef.current[node.id]+ // Reading the selection forces a layout, so check it last: a notebook mounts hundreds of blocks at once.const shouldSkipOwnInputSync =- (document.activeElement === element || isSelectionAnchoredInsideElement(selection, element)) &&- (skipDomSyncForHtmlRef.current === renderedHtml || rootEditableInputHtml === renderedHtml)+ (skipDomSyncForHtmlRef.current === renderedHtml || rootEditableInputHtml === renderedHtml) &&+ (document.activeElement === element || isSelectionAnchoredInsideElement(window.getSelection(), element))skipDomSyncForHtmlRef.current = nullif (shouldSkipOwnInputSync || element.innerHTML === renderedHtml) {diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex a7c84f4bd07a..659260d9c10a 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -1232,7 +1232,8 @@ function MarkdownNotebookEditor({const firstTextNode = getRenderedNodes()[0]const firstElement = firstTextNode ? blockRefs.current[firstTextNode.id] : nullif (firstElement) {- firstElement.focus()+ // The host may have restored a scroll position, such as when the reader goes back to a notebook.+ firstElement.focus({ preventScroll: true })restoreSelection(firstElement, 0, 0)}// oxlint-disable-next-line exhaustive-depsdiff --git a/frontend/src/lib/utils/retainedValues.test.ts b/frontend/src/lib/utils/retainedValues.test.tsnew file mode 100644index 000000000000..34f6069b17ae--- /dev/null+++ b/frontend/src/lib/utils/retainedValues.test.ts@@ -0,0 +1,36 @@+import { initKeaTests } from '~/test/init'++import { RetainedValues } from './retainedValues'++describe('RetainedValues', () => {+ beforeEach(() => initKeaTests())++ test.each([+ { limit: 'entry count', options: { maxEntries: 3 }, size: 1 },+ { limit: 'total size', options: { maxEntries: 100, maxTotalSize: 10 }, size: 3 },+ ])('evicts the least recently used value when the $limit limit is reached', ({ options, size }) => {+ const values = new RetainedValues<number>({ ttlMs: 60_000, scopeToProject: false, ...options })+ values.set('0', 0, size)+ values.set('1', 1, size)+ values.set('2', 2, size)+ values.get('0')+ values.set('next', 3, size)+ expect(values.get('0')).toBe(0)+ expect(values.get('1')).toBeNull()+ expect(values.get('next')).toBe(3)+ })++ it('does not keep a value larger than the entry limit', () => {+ const values = new RetainedValues<string>({+ maxEntries: 10,+ ttlMs: 60_000,+ maxEntrySize: 3,+ sizeOf: (value) => value.length,+ scopeToProject: false,+ })+ values.set('small', 'abc')+ values.set('large', 'abcd')+ expect(values.get('small')).toBe('abc')+ expect(values.get('large')).toBeNull()+ })+})diff --git a/frontend/src/lib/utils/retainedValues.ts b/frontend/src/lib/utils/retainedValues.tsnew file mode 100644index 000000000000..dd0e9e0235f5--- /dev/null+++ b/frontend/src/lib/utils/retainedValues.ts@@ -0,0 +1,142 @@+import { getContext } from 'kea'++import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'++export type RetainedValuesOptions<T> = {+ maxEntries: number+ ttlMs: number+ /** Budget for all entries together, in the units `sizeOf` returns. */+ maxTotalSize?: number+ maxEntrySize?: number+ sizeOf?: (value: T) => number+ /** Prefix ids with the current project. Off when ids already name the project. */+ scopeToProject?: boolean+}++/** A timer for cleanup work that must not keep a Node process alive, such as a test worker. */+export function setBackgroundTimeout(callback: () => void, ms: number): ReturnType<typeof setTimeout> {+ const timer = setTimeout(callback, ms)+ ;(timer as { unref?: () => void }).unref?.()+ return timer+}++type Entry<T> = { value: T; expiresAt: number; size: number }+type Store<T> = { entries: Map<string, Entry<T>>; totalSize: number; sweepTimer: ReturnType<typeof setTimeout> | null }++/**+ * A bounded cache of recently loaded values with least recently used eviction. Expired values are+ * swept on a timer, so memory comes back after the TTL even when nothing reads the cache again.+ * Each kea context gets its own store, which isolates tests from each other.+ */+export class RetainedValues<T> {+ private readonly stores = new WeakMap<ReturnType<typeof getContext>, Store<T>>()++ constructor(private readonly options: RetainedValuesOptions<T>) {}++ get(id: string): T | null {+ const key = this.key(id)+ if (!key) {+ return null+ }+ const store = this.store()+ const entry = store.entries.get(key)+ if (!entry || entry.expiresAt <= Date.now()) {+ this.deleteEntry(store, key)+ return null+ }+ store.entries.delete(key)+ store.entries.set(key, entry)+ return entry.value+ }++ set(id: string, value: T, size?: number): void {+ this.setIn(this.store(), id, value, size)+ }++ /** A setter bound to the current kea context, for a value that may arrive after the context changed. */+ bindSet(): (id: string, value: T, size?: number) => void {+ const store = this.store()+ return (id, value, size) => this.setIn(store, id, value, size)+ }++ delete(id: string): void {+ const key = this.key(id)+ if (key) {+ this.deleteEntry(this.store(), key)+ }+ }++ private setIn(store: Store<T>, id: string, value: T, knownSize?: number): void {+ const key = this.key(id)+ if (!key) {+ return+ }+ const { maxEntries, maxTotalSize = Infinity, maxEntrySize = Infinity, ttlMs, sizeOf } = this.options+ const size = knownSize ?? sizeOf?.(value) ?? 0+ this.deleteEntry(store, key)+ if (size > maxEntrySize) {+ return+ }+ store.entries.set(key, { value, expiresAt: Date.now() + ttlMs, size })+ store.totalSize += size+ while (store.entries.size > maxEntries || store.totalSize > maxTotalSize) {+ this.deleteEntry(store, store.entries.keys().next().value!)+ }+ this.scheduleSweep(store)+ }++ // The TTL is the same for every entry, so the timer only has to wake for the next expiry.+ // `after` makes each wake-up move forward, so a test that pins the clock can't reschedule forever.+ private scheduleSweep(store: Store<T>, after: number = -Infinity): void {+ if (store.sweepTimer) {+ return+ }+ let nextExpiry = Infinity+ for (const entry of store.entries.values()) {+ nextExpiry = Math.min(nextExpiry, entry.expiresAt)+ }+ if (nextExpiry === Infinity || nextExpiry <= after) {+ return+ }+ store.sweepTimer = setBackgroundTimeout(+ () => {+ store.sweepTimer = null+ const now = Date.now()+ for (const [key, entry] of store.entries) {+ if (entry.expiresAt <= now) {+ this.deleteEntry(store, key)+ }+ }+ this.scheduleSweep(store, nextExpiry)+ },+ Math.max(nextExpiry - Date.now(), 1000)+ )+ }++ private deleteEntry(store: Store<T>, key: string): void {+ const entry = store.entries.get(key)+ if (entry) {+ store.totalSize -= entry.size+ store.entries.delete(key)+ }+ }++ // Ids such as insight and notebook short ids are unique only within a project.+ private key(id: string): string | null {+ if (this.options.scopeToProject === false) {+ return id+ }+ const teamId = getCurrentTeamIdOrNone()+ return teamId ? `${teamId}:${id}` : null+ }++ private store(): Store<T> {+ const context = getContext()+ let store = this.stores.get(context)+ if (!store) {+ store = { entries: new Map(), totalSize: 0, sweepTimer: null }+ this.stores.set(context, store)+ }+ return store+ }+}diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.tsindex 391e4c290478..91b0fdb9c8bc 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts@@ -16,7 +16,7 @@ import { DashboardFilter, HogQLVariable, NodeKind } from '~/queries/schema/schemimport { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'-import { RESPONSE_CACHE_TTL } from './responseCache'+import { ABANDONED_QUERY_GRACE_PERIOD, RESPONSE_CACHE_TTL } from './responseCache'const SCAN_ENDPOINT = '/api/environments/:team_id/query/scan/:cache_key/'// The scan endpoint answers with an empty body while the job runs.@@ -108,6 +108,75 @@ describe('dataNodeLogic', () => {expect(mockedQuery.mock.calls[1][1]?.signal?.aborted).toBe(true)})+ it('keeps a notebook query running across a remount instead of starting it again', async () => {+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })+ const response = { results: [[1]], columns: ['value'] }+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }+ const pending = promiseResolveReject<typeof response>()+ mockedQuery.mockReset()+ mockedQuery.mockReturnValueOnce(pending.promise)+ logic = dataNodeLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadData'])+ expect(mockedQuery).toHaveBeenCalledTimes(1)+ const queryId = logic.values.queryId++ logic.unmount()+ expect(mockedQuery.mock.calls[0][1]?.signal?.aborted).toBe(false)++ logic = dataNodeLogic(props)+ logic.mount()+ expect(logic.values.dataLoading).toBe(true)+ expect(logic.values.queryId).toBe(queryId)+ pending.resolve(response)+ await expectLogic(logic).toDispatchActions(['loadDataSuccess']).toMatchValues({ response })+ expect(mockedQuery).toHaveBeenCalledTimes(1)+ })++ it('cancels a notebook query that no remount picks up within the grace period', async () => {+ jest.useFakeTimers()+ try {+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }+ const cancel = jest.spyOn(api, 'delete').mockResolvedValue(undefined)+ mockedQuery.mockReset()+ mockedQuery.mockReturnValueOnce(promiseResolveReject<Record<string, any>>().promise)+ logic = dataNodeLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadData'])+ const queryId = logic.values.queryId+ logic.unmount()++ jest.advanceTimersByTime(ABANDONED_QUERY_GRACE_PERIOD - 1)+ expect(mockedQuery.mock.calls[0][1]?.signal?.aborted).toBe(false)+ jest.advanceTimersByTime(1)+ expect(mockedQuery.mock.calls[0][1]?.signal?.aborted).toBe(true)+ expect(cancel).toHaveBeenCalledWith(expect.stringContaining(`/query/${queryId}/`))+ } finally {+ jest.useRealTimers()+ }+ })++ it('aborts a reused notebook query when the remounted node loads again', async () => {+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })+ const response = { results: [[2]], columns: ['value'] }+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }+ mockedQuery.mockReset()+ mockedQuery.mockReturnValueOnce(promiseResolveReject<typeof response>().promise).mockResolvedValueOnce(response)+ logic = dataNodeLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadData'])+ logic.unmount()+ logic = dataNodeLogic(props)+ logic.mount()++ await expectLogic(logic, () => logic.actions.loadData())+ .toDispatchActions(['loadDataSuccess'])+ .toMatchValues({ response, responseError: null })+ expect(mockedQuery.mock.calls[0][1]?.signal?.aborted).toBe(true)+ expect(mockedQuery).toHaveBeenCalledTimes(2)+ })+it.each(['query', 'insight response'] as const)('restores notebook results when the query arrives after mount: %s',async (source) => {diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.tsindex ac615422b98e..0491d461c10b 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts@@ -112,10 +112,13 @@ import type {import type { DataNodeRegisteredProps } from './dataNodeCollectionLogic'import {forgetRetainedResponse,+ getInflightResponse,getRetainedResponse,isCompleteResponse,+ reclaimReleasedQuery,responseCacheKey,retainResponse,+ trackInflightResponse,} from './responseCache'export interface DataNodeLogicProps {@@ -192,6 +195,18 @@ const webAnalyticsConcurrencyController = new ConcurrencyController(6)const webAnalyticsPreAggConcurrencyController = new ConcurrencyController(6)const marketingAnalyticsConcurrencyController = new ConcurrencyController(6)const productAnalyticsHomeConcurrencyController = new ConcurrencyController(6, { batchStart: true })+const notebookConcurrencyController = new ConcurrencyController(4)+// The priority queue doesn't keep insertion order for equal priorities, so notebook loads count up instead.+let notebookLoadOrder = 0++async function cancelQueryOnServer(teamId: number | null, queryId: string): Promise<void> {+ try {+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.+ await api.delete(`api/projects/${teamId}/query/${queryId}/`)+ } catch (e) {+ console.warn('Failed cancelling query', e)+ }+}function getConcurrencyController(query: DataNode, currentTeam: TeamType): ConcurrencyController {if (isAccountsTableQuery(query)) {@@ -209,6 +224,10 @@ function getConcurrencyController(query: DataNode, currentTeam: TeamType): Concureturn productAnalyticsHomeConcurrencyController}+ if (activeScene === Scene.Notebook) {+ return notebookConcurrencyController+ }+if ([Scene.WebAnalytics,@@ -635,6 +654,9 @@ export interface dataNodeLogicActions {setPollResponse: (status: QueryStatus | null) => {status: QueryStatus | null}+ setQueryId: (queryId: string) => {+ queryId: string+ }setQueryLogQueryId: (queryId: string) => {queryId: string}@@ -1046,6 +1068,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([overrideQuery,}),abortAnyRunningQuery: true,+ setQueryId: (queryId: string) => ({ queryId }),abortQuery: (payload: { queryId: string }) => payload,cancelQuery: true,setResponse: (response: Exclude<AnyResponseType, undefined>) => response,@@ -1085,6 +1108,32 @@ export const dataNodeLogic = kea<dataNodeLogicType>([breakpoint()return retainedResponse}+ const inflightResponse =+ !pollOnly && !refreshArg?.startsWith('force_') ? getInflightResponse(key) : null+ if (inflightResponse) {+ inflightResponse.adopt()+ cache.inflightQuery = inflightResponse+ actions.setQueryId(inflightResponse.queryId)+ let data: AnyResponseType | null | undefined+ try {+ data = await inflightResponse.promise+ } catch (error: any) {+ // A query that never started because its node unmounted while queued is run again below.+ if (!isBreakpoint(error)) {+ error.queryId = inflightResponse.queryId+ if (shouldCancelQuery(error)) {+ actions.abortQuery({ queryId: inflightResponse.queryId })+ }+ breakpoint()+ throw error+ }+ }+ breakpoint()+ if (data !== undefined) {+ cache.responseCacheKey = null+ return data+ }+ }forgetRetainedResponse(key)const rawQuery = overrideQuery ?? props.queryif (!rawQuery || typeof rawQuery !== 'object' || !('kind' in rawQuery)) {@@ -1136,16 +1185,36 @@ export const dataNodeLogic = kea<dataNodeLogicType>([}const abortController = new AbortController()- cache.disposables.add(() => () => abortController.abort(), 'query', { pauseOnPageHidden: false })+ // A retained query keeps running when the node unmounts, so a remount can pick it up.+ const keepRunningOnUnmount = !!key && !pollOnly+ if (!keepRunningOnUnmount) {+ cache.disposables.add(() => () => abortController.abort(), 'query', {+ pauseOnPageHidden: false,+ })+ }const methodOptions: ApiMethodOptions = {signal: abortController.signal,}try {// For shared contexts, create a minimal team object if needed- const response = await getConcurrencyController(query, values.currentTeam as TeamType).run({+ const queryConcurrencyController = getConcurrencyController(+ query,+ values.currentTeam as TeamType+ )+ if (+ queryConcurrencyController === notebookConcurrencyController &&+ queryConcurrencyController._current.length >= queryConcurrencyController._concurrencyLimit+ ) {+ reclaimReleasedQuery()+ }+ const responsePromise = queryConcurrencyController.run({debugTag: query.kind,abortController,- priority: props.loadPriority,+ priority:+ props.loadPriority ??+ (queryConcurrencyController === notebookConcurrencyController+ ? notebookLoadOrder+++ : undefined),fn: async (): Promise<{ duration: number; data: Record<string, any> }> => {const now = performance.now()try {@@ -1171,6 +1240,24 @@ export const dataNodeLogic = kea<dataNodeLogicType>([}},})+ if (key && keepRunningOnUnmount) {+ const teamId = values.currentTeamId+ // The in-flight entry retains the result, so `loadDataSuccess` skips its copy.+ cache.responseCacheKey = null+ cache.inflightQuery = trackInflightResponse(+ key,+ responsePromise.then(({ data }) => data as AnyResponseType | null),+ {+ queryId,+ abort: () => abortController.abort(),+ abandon: () => {+ abortController.abort()+ void cancelQueryOnServer(teamId, queryId)+ },+ }+ )+ }+ const response = await responsePromisebreakpoint()actions.setElapsedTime(response.duration)return response.data@@ -1359,6 +1446,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([null as null | string,{loadData: (_, { queryId }) => queryId,+ setQueryId: (_, { queryId }) => queryId,},],newDataLoading: [@@ -2143,15 +2231,11 @@ export const dataNodeLogic = kea<dataNodeLogicType>([listeners(({ actions, values, cache, props }) => ({abortAnyRunningQuery: () => {cache.disposables.dispose('query')+ cache.inflightQuery?.abort()+ cache.inflightQuery = null},abortQuery: async ({ queryId }) => {- try {- const { currentTeamId } = values- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.- await api.delete(`api/projects/${currentTeamId}/query/${queryId}/`)- } catch (e) {- console.warn('Failed cancelling query', e)- }+ await cancelQueryOnServer(values.currentTeamId, queryId)},cancelQuery: () => {actions.abortAnyRunningQuery()@@ -2282,7 +2366,8 @@ export const dataNodeLogic = kea<dataNodeLogicType>([actions.loadData(refreshType)}}),- beforeUnmount(({ actions, props, values }) => {+ beforeUnmount(({ actions, props, values, cache }) => {+ cache.inflightQuery?.release()if (values.autoLoadRunning) {actions.stopAutoLoad()}diff --git a/frontend/src/queries/nodes/DataNode/responseCache.test.ts b/frontend/src/queries/nodes/DataNode/responseCache.test.tsindex 6ece6b6cc315..d69ebecd0bcf 100644--- a/frontend/src/queries/nodes/DataNode/responseCache.test.ts+++ b/frontend/src/queries/nodes/DataNode/responseCache.test.ts@@ -1,7 +1,15 @@import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { getRetainedResponse, responseCacheKey, retainResponse } from './responseCache'+import {+ MAX_RETAINED_RESPONSE_LENGTH,+ getInflightResponse,+ getRetainedResponse,+ reclaimReleasedQuery,+ responseCacheKey,+ retainResponse,+ trackInflightResponse,+} from './responseCache'beforeEach(() => initKeaTests())@@ -25,18 +33,32 @@ test.each([{ result: null },{ results: [], query_status: { complete: false } },{ results: [], error: 'failed' },- { results: ['x'.repeat(200_001)] },+ { results: ['x'.repeat(MAX_RETAINED_RESPONSE_LENGTH)] },])('does not retain unusable or oversized results: %p', (response) => {retainResponse('example', response)expect(getRetainedResponse('example')).toBeNull()})-test('evicts the least recently used result when capacity is reached', () => {- for (let index = 0; index < 100; index++) {- retainResponse(String(index), { results: [index] })- }- getRetainedResponse('0')- retainResponse('next', { results: [] })- expect(getRetainedResponse('0')).toEqual({ results: [0] })- expect(getRetainedResponse('1')).toBeNull()+test('reclaims the oldest released query first, and never one a node still uses', () => {+ const abandoned: string[] = []+ const track = (key: string): ReturnType<typeof trackInflightResponse> =>+ trackInflightResponse(key, new Promise(() => {}), {+ queryId: key,+ abort: () => {},+ abandon: () => abandoned.push(key),+ })+ const inUse = track('in use')+ const older = track('older')+ const newer = track('newer')+ older.release()+ newer.release()+ inUse.release()+ inUse.adopt()++ expect(reclaimReleasedQuery()).toBe(true)+ expect(reclaimReleasedQuery()).toBe(true)+ expect(reclaimReleasedQuery()).toBe(false)+ expect(abandoned).toEqual(['older', 'newer'])+ expect(getInflightResponse('in use')).toBe(inUse)+ expect(getInflightResponse('older')).toBeNull()})diff --git a/frontend/src/queries/nodes/DataNode/responseCache.ts b/frontend/src/queries/nodes/DataNode/responseCache.tsindex 7cc135630e8f..ed5d83d4ecfc 100644--- a/frontend/src/queries/nodes/DataNode/responseCache.ts+++ b/frontend/src/queries/nodes/DataNode/responseCache.ts@@ -1,15 +1,62 @@import { getContext } from 'kea'+import { RetainedValues, setBackgroundTimeout } from 'lib/utils/retainedValues'+import { AnyResponseType } from '~/queries/schema/schema-general'import type { DataNodeLogicProps } from './dataNodeLogic'-const MAX_ENTRIES = 100-const MAX_ENTRY_LENGTH = 200_000-export const RESPONSE_CACHE_TTL = 2 * 60 * 1000+export const RESPONSE_CACHE_TTL = 10 * 60 * 1000+export const MAX_RETAINED_RESPONSE_LENGTH = 10_000_000+/** How long a query keeps running after its node unmounts, waiting for a remount to pick it up. */+export const ABANDONED_QUERY_GRACE_PERIOD = 60 * 1000++// Sizes are in serialized characters. The keys already name the user and project.+const retainedResponses = new RetainedValues<AnyResponseType>({+ maxEntries: 500,+ ttlMs: RESPONSE_CACHE_TTL,+ maxTotalSize: 50_000_000,+ maxEntrySize: MAX_RETAINED_RESPONSE_LENGTH,+ scopeToProject: false,+})++export type InflightQuery = {+ promise: Promise<AnyResponseType | null>+ /** The id the request was submitted with, which a node that adopts it shows and cancels by. */+ queryId: string+ /** Stops the query for a node that loads again. Forgets it at once, so the next load can't rejoin it. */+ abort: () => void+ /** Starts the grace period. A query nobody adopts in time is abandoned. */+ release: () => void+ adopt: () => void+}+type InflightQueries = {+ byKey: Map<string, InflightQuery>+ /** Queries waiting out their grace period, oldest first, with the function that abandons each one. */+ released: Map<InflightQuery, () => void>+}+const inflightQueries = new WeakMap<ReturnType<typeof getContext>, InflightQueries>()++function getInflightQueries(): InflightQueries {+ const context = getContext()+ let queries = inflightQueries.get(context)+ if (!queries) {+ queries = { byKey: new Map(), released: new Map() }+ inflightQueries.set(context, queries)+ }+ return queries+}-type Entry = { response: AnyResponseType; expiresAt: number }-const caches = new WeakMap<ReturnType<typeof getContext>, Map<string, Entry>>()+/** Abandons the oldest query that no node uses, so a query someone is waiting for can take its slot. */+export function reclaimReleasedQuery(): boolean {+ const { released } = getInflightQueries()+ const oldest = released.entries().next().value+ if (!oldest) {+ return false+ }+ oldest[1]()+ return true+}export function responseCacheKey(props: DataNodeLogicProps,@@ -39,49 +86,93 @@ export function isCompleteResponse(response: AnyResponseType | null | undefined))}-function getCache(): Map<string, Entry> {- const context = getContext()- let cache = caches.get(context)- if (!cache) {- cache = new Map()- caches.set(context, cache)- }- return cache-}-export function getRetainedResponse(key: string | null): AnyResponseType | null {- if (!key) {- return null- }- const cache = getCache()- const entry = cache.get(key)- if (!entry || entry.expiresAt <= Date.now()) {- cache.delete(key)- return null- }- cache.delete(key)- cache.set(key, entry)- return structuredClone(entry.response)+ const response = key ? retainedResponses.get(key) : null+ return response ? structuredClone(response) : null}export function forgetRetainedResponse(key: string | null): void {if (key) {- getCache().delete(key)+ retainedResponses.delete(key)}}export function retainResponse(key: string | null, response: AnyResponseType | null | undefined): void {+ retainWith(retainedResponses.set.bind(retainedResponses), key, response)+}++function retainWith(+ set: (key: string, response: AnyResponseType, size: number) => void,+ key: string | null,+ response: AnyResponseType | null | undefined+): void {if (!key || !isCompleteResponse(response)) {return}const serialized = JSON.stringify(response)- if (serialized.length > MAX_ENTRY_LENGTH) {- return+ if (serialized.length <= MAX_RETAINED_RESPONSE_LENGTH) {+ set(key, JSON.parse(serialized), serialized.length)+ }+}++export function getInflightResponse(key: string | null): InflightQuery | null {+ return key ? (getInflightQueries().byKey.get(key) ?? null) : null+}++/**+ * Lets a query outlive the data node that started it. A node that remounts with the same key awaits+ * the running request instead of cancelling it and starting over, and the result is retained.+ */+export function trackInflightResponse(+ key: string,+ promise: Promise<AnyResponseType | null>,+ { queryId, abort, abandon }: { queryId: string; abort: () => void; abandon: () => void }+): InflightQuery {+ const { byKey, released } = getInflightQueries()+ const retain = retainedResponses.bindSet()+ let settled = false+ let graceTimer: ReturnType<typeof setTimeout> | null = null+ const stopGraceTimer = (): void => {+ if (graceTimer) {+ clearTimeout(graceTimer)+ graceTimer = null+ }+ released.delete(query)+ }+ const forget = (): void => {+ stopGraceTimer()+ if (byKey.get(key) === query) {+ byKey.delete(key)+ }+ }+ const abandonNow = (): void => {+ forget()+ abandon()}- const cache = getCache()- cache.delete(key)- cache.set(key, { response: JSON.parse(serialized), expiresAt: Date.now() + RESPONSE_CACHE_TTL })- while (cache.size > MAX_ENTRIES) {- cache.delete(cache.keys().next().value!)+ const query: InflightQuery = {+ promise,+ queryId,+ abort: () => {+ forget()+ abort()+ },+ release: () => {+ if (settled) {+ return+ }+ stopGraceTimer()+ released.set(query, abandonNow)+ graceTimer = setBackgroundTimeout(abandonNow, ABANDONED_QUERY_GRACE_PERIOD)+ },+ adopt: stopGraceTimer,}+ byKey.set(key, query)+ promise+ .then((response) => retainWith(retain, key, response))+ .catch(() => {})+ .finally(() => {+ settled = true+ forget()+ })+ return query}diff --git a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsxindex ae857ac23f7e..762f20374f53 100644--- a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx+++ b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx@@ -39,7 +39,8 @@ export function SavedInsight({useAttachedLogic(insightLogic(insightProps), attachTo)useAttachedLogic(insightDataLogic(insightProps), attachTo)- if (insightLoading) {+ // A remounted notebook node starts from the retained insight, so it renders while the insight loads again.+ if (insightLoading && !insight.query) {return (<div className="flex flex-col flex-1 justify-center items-center w-full h-full"><LoadingBar />diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex d451c3b47516..3c6d4baec912 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -451,6 +451,12 @@ describe('insightLogic', () => {await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])expect(requests).toHaveLength(1)expect(requests[0].searchParams.get('basic')).toBe(retain ? 'true' : null)++ logic.unmount()+ logic = insightLogic({ dashboardItemId: Insight42, retainResponseOnUnmount: retain })+ logic.mount()+ expect(!!logic.values.insight.query).toBe(retain)+ await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])})const verifyItLoadsFromTheAPI = async (logicUnderTest: ReturnType<typeof insightLogic.build>): Promise<void> =>diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex 0059b6cbe314..f0cf1c568f48 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -30,6 +30,7 @@ import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'import { InsightEventSource, sanitizeInsight, sanitizeQuery } from 'lib/utils/eventUsageLogic'import { isEmptyObject, isObject } from 'lib/utils/guards'import { objectsEqual } from 'lib/utils/objects'+import { RetainedValues } from 'lib/utils/retainedValues'import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'@@ -49,6 +50,7 @@ import { dashboardsModel } from '~/models/dashboardsModel'import { groupsModel } from '~/models/groupsModel'import { insightsModel } from '~/models/insightsModel'import { tagsModel } from '~/models/tagsModel'+import { RESPONSE_CACHE_TTL } from '~/queries/nodes/DataNode/responseCache'import { DashboardFilter, HogQLVariable, Node, TileFilters } from '~/queries/schema/schema-general'import {convertDataTableNodeToDataVisualizationNode,@@ -122,6 +124,17 @@ export const createEmptyInsight = (shortId: InsightShortId | `new-${string}` | 'result: null,})+const retainedInsights = new RetainedValues<Partial<InsightModel>>({+ maxEntries: 500,+ ttlMs: RESPONSE_CACHE_TTL,+ maxTotalSize: 20_000_000,+ sizeOf: (insight) => JSON.stringify(insight).length,+})++function getRetainedInsightForProps(props: InsightLogicProps): Partial<InsightModel> | null {+ return props.retainResponseOnUnmount && props.dashboardItemId ? retainedInsights.get(props.dashboardItemId) : null+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface insightLogicValues {cohortsById: Partial<Record<number | string, CohortType>> // cohortsModel@@ -669,7 +682,9 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType}),loaders(({ actions, values, props }) => ({insight: [- props.cachedInsight ?? createEmptyInsight(props.dashboardItemId || 'new'),+ props.cachedInsight ??+ getRetainedInsightForProps(props) ??+ createEmptyInsight(props.dashboardItemId || 'new'),{loadInsight: async ({ shortId, filtersOverride, variablesOverride, tileFiltersOverride },@@ -922,7 +937,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypeinsightMissing: [false, { setInsightMissing: () => true, loadInsight: () => false }],/** The insight's state as it is in the database. */savedInsight: [- () => props.cachedInsight || ({} as Partial<InsightModel>),+ () => props.cachedInsight || getRetainedInsightForProps(props) || ({} as Partial<InsightModel>),{setInsight: (state, { insight, options: { fromPersistentApi } }) =>fromPersistentApi ? { ...insight, query: insight.query || null } : state,@@ -1114,6 +1129,11 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType],}),listeners(({ actions, values, props }) => ({+ loadInsightSuccess: ({ insight }) => {+ if (props.retainResponseOnUnmount && insight.short_id) {+ retainedInsights.set(insight.short_id, insight)+ }+ },[insightsModel.actionTypes.insightSaved]: async ({ shortId }: { shortId: InsightShortId }, breakpoint) => {if ((props.dashboardId && !isInsightSceneInstance(props)) || values.insight.short_id !== shortId) {returndiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsxindex 4d69814d5258..1b9ee7c0ab75 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx@@ -476,6 +476,7 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttribminHeight: EMBEDDED_SQL_EDITOR_MIN_HEIGHT,resizeable: true,startExpanded: true,+ deferUntilInView: true,attributes: {query: {default: DEFAULT_QUERY,diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex 3f04c3818937..efc8b44bb39d 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -2,7 +2,7 @@ import './Notebook.scss'import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'-import { useEffect, useLayoutEffect } from 'react'+import { useEffect, useLayoutEffect, useState } from 'react'import { NotFound } from 'lib/components/NotFound'import { JSONContent } from 'lib/components/RichContentEditor/types'@@ -58,8 +58,16 @@ export function Notebook({cachedInlineQueryResultsByNodeId,}const logic = notebookLogic(logicProps)- const { notebook, notebookLoading, isEditable, isTemplate, notebookMissing, isShared, isLocalOnly } =- useValues(logic)+ const {+ notebook,+ notebookLoading,+ isEditable,+ isTemplate,+ notebookMissing,+ isShared,+ isLocalOnly,+ shouldBeEditable,+ } = useValues(logic)const { duplicateNotebook, loadNotebook, setEditable, setLocalContent, setContainerSize } = useActions(logic)const { isMarkdownExpanded } = useValues(notebookSettingsLogic)useAttachedContext(@@ -88,8 +96,12 @@ export function Notebook({}})- useEffect(() => {+ // A retained notebook is present on the first render. Rendering it read-only and then switching every block+ // to editable rewrites `contenteditable` across the whole document, so the content waits for this value.+ const [editableApplied, setEditableApplied] = useState(shouldBeEditable === editable)+ useLayoutEffect(() => {setEditable(editable)+ setEditableApplied(true)}, [editable]) // oxlint-disable-line exhaustive-depsconst { ref, size } = useResizeBreakpoints({@@ -116,7 +128,7 @@ export function Notebook({return (<BindLogic logic={notebookLogic} props={logicProps}>- {!notebook && notebookLoading ? (+ {(!notebook && notebookLoading) || !editableApplied ? (<NotebookLoadingState />) : notebookMissing ? (<NotFound object="notebook" />diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.tsindex 7c786263e982..a1de2d47de9f 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts@@ -73,6 +73,41 @@ describe('notebookLogic markdown editor state', () => {jest.restoreAllMocks()})+ it('drops a retained notebook once the server denies access', async () => {+ const retainedShortId = 'test-retained-notebook'+ let denied = false+ useMocks({+ get: {+ [`/api/projects/:team_id/notebooks/${retainedShortId}/`]: () =>+ denied+ ? [403, { type: 'authentication_error', code: 'permission_denied', detail: 'No access' }]+ : [200, { ...cachedNotebook, short_id: retainedShortId }],+ },+ })+ const mountRetained = (): ReturnType<typeof notebookLogic.build> => {+ const retained = notebookLogic({ shortId: retainedShortId, mode: 'notebook' })+ retained.mount()+ return retained+ }+ let retained = mountRetained()+ await expectLogic(retained, () => retained.actions.loadNotebook())+ .toDispatchActions(['loadNotebookSuccess'])+ .toFinishAllListeners()+ retained.unmount()++ denied = true+ retained = mountRetained()+ expect(retained.values.notebook?.short_id).toBe(retainedShortId)+ await expectLogic(retained)+ .toDispatchActions(['loadNotebookFailure'])+ .toMatchValues({ notebook: null, accessDeniedToNotebook: true })+ retained.unmount()++ retained = mountRetained()+ expect(retained.values.notebook).toBeNull()+ retained.unmount()+ })+it('applies editor changes to local content when no interaction is active', () => {const nextMarkdown = `${BASE_MARKDOWN} edited`diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 5e2f8e6cdfa9..f6e339d8a25e 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -42,6 +42,7 @@ import {useEffect,useMemo,useRef,+ useState,} from 'react'import { useInView } from 'react-intersection-observer'@@ -786,6 +787,27 @@ export function RealNotebookNodeComponent({)}+const scrollContainersByNotebook = new WeakMap<Element, Element | null>()++function findScrollContainer(element: Element): Element | null {+ const notebook = element.closest('.MarkdownNotebook')+ const cached = notebook ? scrollContainersByNotebook.get(notebook) : undefined+ if (cached !== undefined) {+ return cached+ }+ let container: Element | null = null+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {+ if (/auto|scroll|overlay/.test(getComputedStyle(parent).overflowY)) {+ container = parent+ break+ }+ }+ if (notebook) {+ scrollContainersByNotebook.set(notebook, container)+ }+ return container+}+export function MountedRealNotebookNodeComponent({node,mode,@@ -803,16 +825,25 @@ export function MountedRealNotebookNodeComponent({}): JSX.Element {const mountedNotebookLogic = useMountedLogic(notebookLogic)const contentRef = useRef<HTMLDivElement | null>(null)+ const [scrollContainer, setScrollContainer] = useState<Element | null | undefined>(undefined)const { ref: inViewRef, inView } = useInView({triggerOnce: !options.unmountWhenOutOfView,fallbackInView: true,+ // The observer clips targets to every scrolling ancestor, so the margin only reaches beyond+ // the visible area when the notebook's own scroll container is the root.+ ...(options.deferUntilInView+ ? { root: scrollContainer, rootMargin: '100% 0px', skip: scrollContainer === undefined }+ : {}),})const setContentRefs = useCallback((element: HTMLDivElement | null): void => {contentRef.current = elementinViewRef(element)+ if (element && options.deferUntilInView) {+ setScrollContainer(findScrollContainer(element))+ }},- [inViewRef]+ [inViewRef, options.deferUntilInView])const attributes = useMemo(() => getNodeAttributes(node.props, node.id, options, notebookNodeType, forceEditing),@@ -976,7 +1007,7 @@ export function MountedRealNotebookNodeComponent({style={contentStyle}onMouseDown={handleResizeStart}>- {!options.unmountWhenOutOfView || inView ? (+ {!(options.unmountWhenOutOfView || options.deferUntilInView) || inView ? (<Component attributes={attributes} updateAttributes={updateAttributes} />) : (<LemonSkeleton className="h-full w-full" />diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 488d3e13e877..f6ec71c0e469 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -41,6 +41,7 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'import { downloadFile } from 'lib/utils/dom'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { objectsEqual } from 'lib/utils/objects'+import { RetainedValues } from 'lib/utils/retainedValues'import { slugify } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -53,6 +54,7 @@ import {notebooksModel,openNotebook,} from '~/models/notebooksModel'+import { RESPONSE_CACHE_TTL } from '~/queries/nodes/DataNode/responseCache'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'import { AnyResponseType } from '~/queries/schema/schema-general'import { isHogQLQuery } from '~/queries/utils'@@ -268,6 +270,23 @@ export type NotebookLogicProps = {cachedInlineQueryResultsByNodeId?: Record<string, AnyResponseType>}+const retainedNotebooks = new RetainedValues<NotebookType>({+ maxEntries: 50,+ ttlMs: RESPONSE_CACHE_TTL,+ maxTotalSize: 30_000_000,+ maxEntrySize: 10_000_000,+ sizeOf: (notebook) => JSON.stringify(notebook.content ?? null).length,+})++function canRetainNotebook(props: NotebookLogicProps): boolean {+ return (+ (props.mode ?? 'notebook') === 'notebook' &&+ !props.cachedNotebook &&+ props.shortId !== SCRATCHPAD_NOTEBOOK.short_id &&+ !props.shortId.startsWith('template-')+ )+}+async function runWhenNotebookIsReady(waitForNotebook: () => boolean, fn: () => any): Promise<any | null> {const maxWaitMs = 5000const startTime = Date.now()@@ -995,7 +1014,7 @@ export const notebookLogic = kea<notebookLogicType>([})),loaders(({ values, props, actions, cache }) => ({notebook: [- null as NotebookType | null,+ (canRetainNotebook(props) ? retainedNotebooks.get(props.shortId) : null) as NotebookType | null,{loadNotebook: async () => {let response: NotebookType | null = null@@ -1027,11 +1046,13 @@ export const notebookLogic = kea<notebookLogicType>([})} catch (e: any) {if (e.status === 403 && e.code === 'permission_denied') {+ retainedNotebooks.delete(props.shortId)actions.setAccessDeniedToNotebook()} else if (e.status === 304) {// Indicates nothing has changedreturn values.notebook} else if (e.status === 404) {+ retainedNotebooks.delete(props.shortId)return null}throw e@@ -1230,6 +1251,8 @@ export const notebookLogic = kea<notebookLogicType>([// Extends the loader reducer: canonical remote states (streamed diffs, 409 replays)// land in `notebook` without a refetch.notebook: {+ // A retained copy can render before the server denies access, so it must not stay on screen.+ setAccessDeniedToNotebook: () => null,loadNotebookSuccess: (state, { notebook }) => keepNewestNotebookResponse(state, notebook),saveNotebookSuccess: (state, { notebook }) => keepNewestNotebookResponse(state, notebook),applyRemoteNotebookContent: (state, { content, version }) =>@@ -2195,8 +2218,11 @@ export const notebookLogic = kea<notebookLogicType>([},})),- subscriptions(({ actions }) => ({+ subscriptions(({ actions, props }) => ({notebook: (notebook?: NotebookType) => {+ if (notebook && canRetainNotebook(props)) {+ retainedNotebooks.set(props.shortId, notebook)+ }// Keep the list logic up to date with any changesif (notebook && notebook.short_id !== SCRATCHPAD_NOTEBOOK.short_id) {actions.receiveNotebookUpdate(notebook)@@ -2238,8 +2264,12 @@ export const notebookLogic = kea<notebookLogicType>([message: 'Leave notebook?\nChanges you made may not be saved.',})),- afterMount(({ props }) => {+ afterMount(({ props, values, actions }) => {drainPendingNotebookOperations(props.shortId)+ // A retained copy renders at once, so check it against the server straight away.+ if (values.notebook && canRetainNotebook(props)) {+ actions.loadNotebook()+ }}),beforeUnmount(() => {diff --git a/frontend/src/scenes/notebooks/notebookSceneLogic.ts b/frontend/src/scenes/notebooks/notebookSceneLogic.tsindex a739a9ff4d53..b8994316c48b 100644--- a/frontend/src/scenes/notebooks/notebookSceneLogic.ts+++ b/frontend/src/scenes/notebooks/notebookSceneLogic.ts@@ -1,10 +1,12 @@-import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'import type { BuiltLogic } from 'kea'+import { router } from 'kea-router'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'import { notebooksModel } from '~/models/notebooksModel'import { ActivityScope, Breadcrumb, ProjectTreeRef } from '~/types'@@ -17,6 +19,37 @@ import type { NotebookType } from './types'export type NotebookSceneLogicProps = {shortId: string}++const MAX_SCROLL_RESTORE_FRAMES = 60+const scrollPositions = new Map<string, number>()++function getSceneScrollContainer(): HTMLElement | null {+ return panelLayoutLogic.findMounted()?.values.mainContentRef?.current ?? null+}++function restoreScrollPosition(cache: Record<string, any>): void {+ const target: number | undefined = cache.scrollRestoreTarget+ cache.scrollRestoreTarget = undefined+ if (!target) {+ return+ }+ let frames = 0+ const restore = (): void => {+ const element = getSceneScrollContainer()+ if (!element) {+ return+ }+ if (element.scrollHeight - element.clientHeight >= target || ++frames >= MAX_SCROLL_RESTORE_FRAMES) {+ element.scrollTop = target+ return+ }+ cache.disposables.add(() => {+ const id = requestAnimationFrame(restore)+ return () => cancelAnimationFrame(id)+ }, 'scrollRestore')+ }+ restore()+}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookSceneLogicValues {isLocalOnly: boolean // notebookLogic@@ -35,6 +68,19 @@ export interface notebookSceneLogicActions {loadNotebook: () => {value: true} // notebookLogic+ loadNotebookSuccess: (+ notebook: NotebookType | null,+ payload?:+ | {+ value: true+ }+ | undefined+ ) => {+ notebook: NotebookType | null+ payload?: {+ value: true+ }+ } // notebookLogiccreateNotebook: (location: NotebookTarget,title?: string | undefined,@@ -80,7 +126,7 @@ export const notebookSceneLogic = kea<notebookSceneLogicType>([notebooksModel,['notebooksLoading'],],- actions: [notebookLogic(props), ['loadNotebook'], notebooksModel, ['createNotebook']],+ actions: [notebookLogic(props), ['loadNotebook', 'loadNotebookSuccess'], notebooksModel, ['createNotebook']],})),selectors(() => ({notebookId: [(_, p) => [p.shortId], (shortId: string) => shortId],@@ -139,8 +185,32 @@ export const notebookSceneLogic = kea<notebookSceneLogicType>([],})),- afterMount(({ actions, props }) => {- if (props.shortId !== 'new') {+ listeners(({ cache }) => ({+ loadNotebookSuccess: () => restoreScrollPosition(cache),+ })),+ afterMount(({ actions, props, values, cache }) => {+ if (router.values.lastMethod === 'POP') {+ cache.scrollRestoreTarget = scrollPositions.get(props.shortId)+ if (values.notebook) {+ restoreScrollPosition(cache)+ }+ }+ // Navigating away resets the scroll position while this notebook is still rendered, so positions are+ // recorded while mounted, and only while the URL still points at this notebook.+ const pathname = router.values.location.pathname+ cache.disposables.add(() => {+ // Scroll events don't bubble, so a capturing listener sees the scene container even when it mounts later.+ const onScroll = (event: Event): void => {+ const element = getSceneScrollContainer()+ if (element && event.target === element && router.values.location.pathname === pathname) {+ scrollPositions.set(props.shortId, element.scrollTop)+ }+ }+ document.addEventListener('scroll', onScroll, { capture: true, passive: true })+ return () => document.removeEventListener('scroll', onScroll, { capture: true })+ }, 'scrollTracking')+ // notebookLogic already revalidates a retained copy when it mounts.+ if (props.shortId !== 'new' && !values.notebookLoading) {actions.loadNotebook()}}),diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex 0c2fb7198e5c..adfc6c198f85 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -148,6 +148,8 @@ export type NodeWrapperProps<T extends CustomNotebookNodeAttributes> = Omit<Note/** Expand the node if the component is clicked */expandOnClick?: booleanunmountWhenOutOfView?: boolean+ /** Mount the content only once it nears the viewport, and keep it mounted afterwards */+ deferUntilInView?: booleansettingsPlacement?: NotebookNodeSettingsPlacementdefaultView?: PostHogWidgetDefaultViewviews?: PostHogWidgetViews<T>