Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): log snapshots on collab save and reject (#57895)

Alex Lidera8616511c3ad
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
index 386536c7c396..0fa5b67c3d5a 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.tsx
@@ -27,6 +27,7 @@ const getFieldChange = (logItem: ActivityLogItem, field: string): any => {
function NotebookHistoryList({ onItemClick }: { onItemClick: (logItem: ActivityLogItem) => void }): JSX.Element {
const { shortId, notebook, previewContent } = useValues(notebookLogic)
+ const { clearPreviewContent } = useActions(notebookLogic)
const logic = activityLogLogic({ scope: ActivityScope.NOTEBOOK, id: shortId })
const { activity, pagination, activityLoading } = useValues(logic)
@@ -46,11 +47,24 @@ function NotebookHistoryList({ onItemClick }: { onItemClick: (logItem: ActivityL
<LemonSkeleton className="w-full h-10" repeat={10} />
</div>
) : (
- activityWithChangedContent?.map((logItem: ActivityLogItem) => {
+ activityWithChangedContent?.map((logItem: ActivityLogItem, idx: number) => {
const name = userNameForLogItem(logItem)
- const isCurrent = getFieldChange(logItem, 'version') === notebook?.version
+ const isRejected = logItem.activity.startsWith('save_rejected_')
+ const isLastSaved = !isRejected && getFieldChange(logItem, 'version') === notebook?.version
+ // Top of page 1 = most recent attempt (what the editor is showing)
+ const isCurrent = idx === 0 && pagination.currentPage === 1
const changedContent = getFieldChange(logItem, 'content')
- const isButton = changedContent && !isCurrent
+ // Current entry is also clickable
+ const isButton = !!changedContent
+
+ let actionLabel: string
+ if (isRejected) {
+ actionLabel = 'unsaved changes'
+ } else if (changedContent) {
+ actionLabel = 'made changes'
+ } else {
+ actionLabel = 'created this'
+ }
const buttonContent = (
<span className="flex flex-1 gap-2 items-center p-2">
@@ -63,13 +77,18 @@ function NotebookHistoryList({ onItemClick }: { onItemClick: (logItem: ActivityL
size="md"
/>
<span className="flex-1">
- <b className="ph-no-capture">{name}</b>{' '}
- {changedContent ? 'made changes' : 'created this'}
+ <b className="ph-no-capture">{name}</b> {actionLabel}
</span>
<span className="text-secondary">
<TZLabel time={logItem.created_at} />
</span>
- {isCurrent ? <span className="text-secondary">(Current)</span> : null}
+ {isCurrent && isLastSaved ? (
+ <span className="text-secondary">(Current, saved)</span>
+ ) : isCurrent ? (
+ <span className="text-secondary">(Current)</span>
+ ) : isLastSaved ? (
+ <span className="text-secondary">(Last saved)</span>
+ ) : null}
</span>
)
@@ -79,8 +98,8 @@ function NotebookHistoryList({ onItemClick }: { onItemClick: (logItem: ActivityL
<LemonButton
fullWidth
size="small"
- active={previewContent === changedContent}
- onClick={() => onItemClick(logItem)}
+ active={isCurrent ? !previewContent : previewContent === changedContent}
+ onClick={() => (isCurrent ? clearPreviewContent() : onItemClick(logItem))}
noPadding
>
{buttonContent}
diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/api/notebook.py
index 9ce061cc0cff..98026846b5cc 100644
--- a/products/notebooks/backend/api/notebook.py
+++ b/products/notebooks/backend/api/notebook.py
@@ -761,8 +761,10 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
cursor_head=data.get("cursor_head"),
)
+ content = data["content"]
+
if result.status == "accepted":
- content = data["content"]
+ notebook_before = Notebook.objects.get(pk=notebook.pk)
Notebook.objects.filter(pk=notebook.pk).update(
content=annotate_python_nodes(content) if isinstance(content, dict) else content,
text_content=data.get("text_content", ""),
@@ -772,8 +774,40 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
last_modified_by=request.user,
)
notebook.refresh_from_db()
+
+ # Snapshot diffs into the activity logs for history
+ changes = changes_between("Notebook", previous=notebook_before, current=notebook)
+ log_notebook_activity(
+ activity="updated",
+ notebook=notebook,
+ organization_id=cast(UUIDT, user.current_organization_id),
+ team_id=notebook.team_id,
+ user=user,
+ was_impersonated=is_impersonated_session(request),
+ changes=changes,
+ )
+
return Response(NotebookSerializer(notebook, context=self.get_serializer_context()).data)
+ # Snapshot the rejected save attempt so user has a recovery path
+ log_notebook_activity(
+ activity=f"save_rejected_{result.status}", # save_rejected_conflict | save_rejected_stale
+ notebook=notebook,
+ organization_id=cast(UUIDT, user.current_organization_id),
+ team_id=notebook.team_id,
+ user=user,
+ was_impersonated=is_impersonated_session(request),
+ changes=[
+ Change(
+ type="Notebook",
+ field="content",
+ action="changed",
+ before=notebook.content,
+ after=content,
+ ),
+ ],
+ )
+
if result.status == "stale":
return Response(
{"code": "conflict_stale", "detail": "Reload the notebook."},
diff --git a/products/notebooks/backend/test/test_collab_api.py b/products/notebooks/backend/test/test_collab_api.py
index e645a4d490af..9d124f3a811a 100644
--- a/products/notebooks/backend/test/test_collab_api.py
+++ b/products/notebooks/backend/test/test_collab_api.py
@@ -8,6 +8,7 @@ from rest_framework import status
from posthog import redis as redis_module
from posthog.models import Team
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -170,6 +171,99 @@ class TestNotebookCollabSaveAPI(APIBaseTest):
data = response.json()
assert data["code"] == "conflict_stale"
+ def test_collab_save_accepted_logs_diff_against_pre_update_snapshot(self):
+ # The activity log records a diff between `notebook_before` and `notebook`
+ # Django returns independent Python objects per `.get()`,
+ # so refreshing one must not bleed into the other
+ notebook = self._create_notebook(SAMPLE_DOC)
+ version = notebook["version"]
+
+ response = self._collab_save(
+ notebook,
+ version=version,
+ steps=[{"stepType": "replace", "from": 0, "to": 0}],
+ content=UPDATED_DOC,
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ log = ActivityLog.objects.get(
+ team_id=self.team.id,
+ scope="Notebook",
+ item_id=notebook["short_id"],
+ activity="updated",
+ )
+ assert log.detail is not None
+ changes_by_field = {c["field"]: c for c in log.detail["changes"]}
+
+ assert changes_by_field["content"]["action"] == "changed"
+ assert changes_by_field["content"]["before"] == SAMPLE_DOC
+ assert changes_by_field["content"]["after"] == UPDATED_DOC
+
+ assert changes_by_field["version"]["action"] == "changed"
+ assert changes_by_field["version"]["before"] == version
+ assert changes_by_field["version"]["after"] == version + 1
+
+ # text_content is excluded from Notebook diffs and should never surface
+ assert "text_content" not in changes_by_field
+
+ def test_collab_save_rejected_stale_logs_attempted_content(self):
+ notebook = self._create_notebook(SAMPLE_DOC)
+
+ with patch("products.notebooks.backend.api.notebook.submit_steps") as mock_submit:
+ mock_submit.return_value = SubmitResult(status="stale", version=5, steps_since=None)
+ self._collab_save(
+ notebook,
+ version=0,
+ steps=[{"stepType": "replace", "from": 0, "to": 0}],
+ content=UPDATED_DOC,
+ )
+
+ log = ActivityLog.objects.get(
+ team_id=self.team.id,
+ scope="Notebook",
+ item_id=notebook["short_id"],
+ activity="save_rejected_stale",
+ )
+ assert log.detail is not None
+ [change] = log.detail["changes"]
+ assert change["field"] == "content"
+ assert change["before"] == SAMPLE_DOC
+ assert change["after"] == UPDATED_DOC
+
+ def test_collab_save_rejected_conflict_logs_attempted_content(self):
+ notebook = self._create_notebook(SAMPLE_DOC)
+ version = notebook["version"]
+
+ self._collab_save(
+ notebook,
+ version=version,
+ steps=[{"stepType": "replace", "from": 0, "to": 0}],
+ client_id="client-1",
+ )
+
+ rejected_doc = {"type": "doc", "content": [{"type": "heading", "content": [{"type": "text", "text": "C2"}]}]}
+ response = self._collab_save(
+ notebook,
+ version=version,
+ steps=[{"stepType": "replace", "from": 1, "to": 1}],
+ content=rejected_doc,
+ client_id="client-2",
+ )
+ assert response.status_code == status.HTTP_409_CONFLICT
+
+ log = ActivityLog.objects.get(
+ team_id=self.team.id,
+ scope="Notebook",
+ item_id=notebook["short_id"],
+ activity="save_rejected_conflict",
+ )
+ assert log.detail is not None
+ [change] = log.detail["changes"]
+ assert change["field"] == "content"
+ # `before` is the server's content at rejection time (post client-1's accepted save)
+ assert change["before"] == UPDATED_DOC
+ assert change["after"] == rejected_doc
+
# Keep the SSE generator lifetime tiny so tests terminate deterministically.
# XREAD blocks until we either see data or hit this window;