:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): show changes since the last browser visit (#116058)
Marius Andra225fe9a2ea61
diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex d8dc0b89d13e..3f04c3818937 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -14,8 +14,10 @@ import { NotebookLogicProps, notebookLogic } from 'scenes/notebooks/Notebook/notimport { ErrorBoundary } from '~/layout/ErrorBoundary'import { SCRATCHPAD_NOTEBOOK } from '~/models/notebooksModel'+import { NotebookChangesNotice } from 'products/notebooks/frontend/NotebookChangesNotice'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { getMarkdownNotebookMarkdown } from './markdownNotebookV2'import { MarkdownNotebookV2 } from './MarkdownNotebookV2Renderer'import { NotebookColumnLeft } from './NotebookColumnLeft'import { NotebookColumnRight } from './NotebookColumnRight'@@ -56,7 +58,8 @@ export function Notebook({cachedInlineQueryResultsByNodeId,}const logic = notebookLogic(logicProps)- const { notebook, notebookLoading, isEditable, isTemplate, notebookMissing, isShared } = useValues(logic)+ const { notebook, notebookLoading, isEditable, isTemplate, notebookMissing, isShared, isLocalOnly } =+ useValues(logic)const { duplicateNotebook, loadNotebook, setEditable, setLocalContent, setContainerSize } = useActions(logic)const { isMarkdownExpanded } = useValues(notebookSettingsLogic)useAttachedContext(@@ -144,6 +147,12 @@ export function Notebook({</LemonBanner>)}<NotebookHistoryWarning />+ {notebook && !isShared && !isTemplate && !isLocalOnly && mode !== 'canvas' && (+ <NotebookChangesNotice+ notebookId={shortId}+ markdown={getMarkdownNotebookMarkdown(notebook.content)}+ />+ )}<NotebookMergeConflictDetails />{shortId === SCRATCHPAD_NOTEBOOK.short_id ? (<LemonBannerdiff --git a/products/notebooks/frontend/NotebookChangesNotice.tsx b/products/notebooks/frontend/NotebookChangesNotice.tsxnew file mode 100644index 000000000000..594e228e7485--- /dev/null+++ b/products/notebooks/frontend/NotebookChangesNotice.tsx@@ -0,0 +1,93 @@+import { useActions, useValues } from 'kea'+import { Suspense } from 'react'++import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { lazyWithRetry } from 'lib/utils/retryImport'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { notebookChangesLogic } from './notebookChangesLogic'++const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))++export function NotebookChangesNotice({+ notebookId,+ markdown,+}: {+ notebookId: string+ markdown: string+}): JSX.Element | null {+ const { user } = useValues(userLogic)+ const { currentTeamId } = useValues(teamLogic)+ const logic = notebookChangesLogic({+ scope: user && currentTeamId ? JSON.stringify([user.id, currentTeamId, notebookId]) : null,+ markdown,+ })+ const { hasChanges, showChanges, previousVisit } = useValues(logic)+ const { setShowChanges, dismissChanges } = useActions(logic)+ if (!hasChanges || !previousVisit) {+ return null+ }+ return (+ <>+ <LemonBanner+ type="info"+ className="mb-4"+ onClose={dismissChanges}+ action={{ children: 'Review changes', onClick: () => setShowChanges(true) }}+ >+ This notebook has changed since your last visit on this browser.+ </LemonBanner>+ <LemonModal+ isOpen={showChanges}+ onClose={() => setShowChanges(false)}+ title="Changes since your last visit"+ width={800}+ footer={+ <LemonButton type="primary" onClick={() => setShowChanges(false)}>+ Close+ </LemonButton>+ }+ >+ <p>+ Compared with the version you viewed{' '}+ <TZLabel time={new Date(previousVisit.viewedAt).toISOString()} /> on this browser.+ </p>+ <div className="flex flex-wrap gap-4 mb-3 text-sm">+ <del className="text-danger bg-danger-highlight">Removed</del>+ <ins className="text-success bg-success-highlight no-underline">Added</ins>+ </div>+ <div+ className="max-h-[60vh] overflow-y-auto overflow-x-hidden break-words font-mono text-sm"+ data-attr="notebook-visit-diff"+ >+ <Suspense fallback={<Spinner className="text-2xl mx-auto my-4" />}>+ <MonacoDiffEditor+ original={previousVisit.markdown}+ modified={markdown}+ language="markdown"+ options={{+ renderSideBySide: false,+ renderOverviewRuler: false,+ renderGutterMenu: false,+ scrollBeyondLastLine: false,+ automaticLayout: true,+ wordWrap: 'on',+ diffWordWrap: 'on',+ minimap: { enabled: false },+ hideUnchangedRegions: {+ enabled: true,+ contextLineCount: 3,+ minimumLineCount: 3,+ revealLineCount: 20,+ },+ }}+ />+ </Suspense>+ </div>+ </LemonModal>+ </>+ )+}diff --git a/products/notebooks/frontend/notebookChangesLogic.test.ts b/products/notebooks/frontend/notebookChangesLogic.test.tsnew file mode 100644index 000000000000..1637093ce250--- /dev/null+++ b/products/notebooks/frontend/notebookChangesLogic.test.ts@@ -0,0 +1,84 @@+import { initKeaTests } from '~/test/init'++import { notebookChangesLogic } from './notebookChangesLogic'+import { NotebookVisitStorage } from './notebookVisitStorage'++const scope = JSON.stringify([1, 1, 'example-notebook'])++beforeEach(() => {+ initKeaTests()+ localStorage.clear()+})++test('compares with the previous visit while retaining the latest viewed version for the next visit', () => {+ let logic = notebookChangesLogic({ scope, markdown: '# First version' })+ logic.mount()+ expect(logic.values.hasChanges).toBe(false)+ logic.unmount()++ logic = notebookChangesLogic({ scope, markdown: '# Second version' })+ logic.mount()+ expect(logic.values.previousVisit?.markdown).toBe('# First version')+ expect(logic.values.hasChanges).toBe(true)+ logic.actions.setShowChanges(true)+ expect(logic.values.showChanges).toBe(true)++ notebookChangesLogic({ scope, markdown: '# Third version' })+ expect(logic.values.previousVisit?.markdown).toBe('# First version')+ logic.actions.dismissChanges()+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.showChanges).toBe(false)+ logic.unmount()++ logic = notebookChangesLogic({ scope, markdown: '# Third version' })+ logic.mount()+ expect(logic.values.hasChanges).toBe(false)+ logic.unmount()+})++test('waits for loaded content and saves the latest version when the browser page closes', () => {+ NotebookVisitStorage.write(scope, '# Before')+ const logic = notebookChangesLogic({ scope, markdown: null })+ logic.mount()+ expect(logic.values.visitInitialized).toBe(false)+ notebookChangesLogic({ scope, markdown: '# Loaded' })+ expect(logic.values.hasChanges).toBe(true)+ window.dispatchEvent(new Event('pagehide'))+ expect(NotebookVisitStorage.read(scope)?.markdown).toBe('# Loaded')+ logic.unmount()+})++test.each([null, JSON.stringify([2, 1, 'example-notebook']), JSON.stringify([1, 2, 'example-notebook'])])(+ 'does not show a previous visit across identities: %s',+ (otherScope) => {+ NotebookVisitStorage.write(scope, '# Private version')+ const logic = notebookChangesLogic({ scope: otherScope, markdown: '# Current' })+ logic.mount()+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.previousVisit).toBeNull()+ logic.unmount()+ }+)++test('tolerates corrupt storage and evicts old or oversized snapshots', () => {+ localStorage.setItem('notebook-last-visits', '{broken')+ expect(NotebookVisitStorage.read(scope)).toBeNull()+ for (let index = 0; index < 11; index++) {+ NotebookVisitStorage.write(String(index), '# Version')+ }+ expect(NotebookVisitStorage.read('0')).toBeNull()+ expect(NotebookVisitStorage.read('10')?.markdown).toBe('# Version')+ NotebookVisitStorage.write('10', 'x'.repeat(500_001))+ expect(NotebookVisitStorage.read('10')).toBeNull()+})++test('keeps notebook visits usable when browser storage is unavailable', () => {+ const write = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new DOMException('Storage unavailable', 'QuotaExceededError')+ })+ try {+ expect(() => NotebookVisitStorage.write(scope, '# Version')).not.toThrow()+ } finally {+ write.mockRestore()+ }+})diff --git a/products/notebooks/frontend/notebookChangesLogic.ts b/products/notebooks/frontend/notebookChangesLogic.tsnew file mode 100644index 000000000000..1151338149e5--- /dev/null+++ b/products/notebooks/frontend/notebookChangesLogic.ts@@ -0,0 +1,129 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ kea,+ key,+ listeners,+ path,+ props,+ propsChanged,+ reducers,+ selectors,+} from 'kea'++import { NotebookVisitStorage, type NotebookVisit } from './notebookVisitStorage'++export interface NotebookChangesLogicProps {+ scope: string | null+ markdown: string | null+}++function saveCurrentVisit({ scope, markdown }: NotebookChangesLogicProps): void {+ if (scope && markdown !== null) {+ NotebookVisitStorage.write(scope, markdown)+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookChangesLogicValues {+ dismissed: boolean+ hasChanges: boolean+ previousVisit: NotebookVisit | null+ showChanges: boolean+ visitInitialized: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookChangesLogicActions {+ dismissChanges: () => {+ value: true+ }+ initializeVisit: (visit: NotebookVisit | null) => {+ visit: NotebookVisit | null+ }+ observeVisit: () => {+ value: true+ }+ persistVisit: () => {+ value: true+ }+ setShowChanges: (show: boolean) => {+ show: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface notebookChangesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ hasChanges: (previousVisit: NotebookVisit | null, dismissed: boolean, arg: string | null) => boolean+ }+}++export type notebookChangesLogicType = MakeLogicType<+ notebookChangesLogicValues,+ notebookChangesLogicActions,+ NotebookChangesLogicProps,+ notebookChangesLogicMeta+>++export const notebookChangesLogic = kea<notebookChangesLogicType>([+ path((key) => ['products', 'notebooks', 'notebookChangesLogic', key]),+ props({} as NotebookChangesLogicProps),+ key(({ scope }) => scope ?? 'disabled'),+ actions({+ observeVisit: true,+ initializeVisit: (visit: NotebookVisit | null) => ({ visit }),+ persistVisit: true,+ setShowChanges: (show: boolean) => ({ show }),+ dismissChanges: true,+ }),+ reducers({+ previousVisit: [null as NotebookVisit | null, { initializeVisit: (_, { visit }) => visit }],+ visitInitialized: [false, { initializeVisit: () => true }],+ dismissed: [false, { dismissChanges: () => true }],+ showChanges: [false, { setShowChanges: (_, { show }) => show, dismissChanges: () => false }],+ }),+ selectors({+ hasChanges: [+ (s) => [s.previousVisit, s.dismissed, (_, props: NotebookChangesLogicProps) => props.markdown],+ (previousVisit: NotebookVisit | null, dismissed: boolean, markdown: string | null): boolean =>+ !dismissed && !!previousVisit && markdown !== null && previousVisit.markdown !== markdown,+ ],+ }),+ listeners(({ actions, values, props }) => ({+ observeVisit: () => {+ if (!props.scope || props.markdown === null) {+ return+ }+ if (!values.visitInitialized) {+ actions.initializeVisit(NotebookVisitStorage.read(props.scope))+ }+ actions.persistVisit()+ },+ persistVisit: async (_, breakpoint) => {+ await breakpoint(1000)+ saveCurrentVisit(props)+ },+ })),+ propsChanged(({ actions, props }, previous) => {+ if (props.markdown !== previous.markdown) {+ actions.observeVisit()+ }+ }),+ afterMount(({ actions, props, cache }) => {+ actions.observeVisit()+ cache.disposables.add(+ () => {+ const save = (): void => saveCurrentVisit(props)+ window.addEventListener('pagehide', save)+ return () => window.removeEventListener('pagehide', save)+ },+ 'saveVisit',+ { pauseOnPageHidden: false }+ )+ }),+ beforeUnmount(({ props }) => saveCurrentVisit(props)),+])diff --git a/products/notebooks/frontend/notebookVisitStorage.ts b/products/notebooks/frontend/notebookVisitStorage.tsnew file mode 100644index 000000000000..ff14bb97757f--- /dev/null+++ b/products/notebooks/frontend/notebookVisitStorage.ts@@ -0,0 +1,50 @@+export type NotebookVisit = { markdown: string; viewedAt: number }+type StoredVisit = NotebookVisit & { scope: string }++const STORAGE_KEY = 'notebook-last-visits'+const MAX_MARKDOWN_LENGTH = 500_000+const MAX_TOTAL_LENGTH = 2_000_000+const MAX_VISITS = 10++export class NotebookVisitStorage {+ private static readAll(): StoredVisit[] {+ try {+ const value: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]')+ if (!Array.isArray(value)) {+ return []+ }+ return value.filter(+ (entry): entry is StoredVisit =>+ !!entry &&+ typeof entry.scope === 'string' &&+ typeof entry.markdown === 'string' &&+ entry.markdown.length <= MAX_MARKDOWN_LENGTH &&+ typeof entry.viewedAt === 'number' &&+ Number.isFinite(new Date(entry.viewedAt).getTime())+ )+ } catch {+ return []+ }+ }++ static read(scope: string): NotebookVisit | null {+ return this.readAll().find((entry) => entry.scope === scope) ?? null+ }++ static write(scope: string, markdown: string): void {+ const entries = this.readAll().filter((entry) => entry.scope !== scope)+ if (markdown.length <= MAX_MARKDOWN_LENGTH) {+ entries.unshift({ scope, markdown, viewedAt: Date.now() })+ }+ let remaining = MAX_TOTAL_LENGTH+ const retained = entries.slice(0, MAX_VISITS).filter((entry) => {+ remaining -= JSON.stringify(entry).length+ return remaining >= 0+ })+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(retained))+ } catch {+ // Storage can be disabled or full; opening and editing the notebook must still work.+ }+ }+}