: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(file-system): count a star as added only when the api creates it (#119017)
posthog[bot]d3aceeaac773
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.tsindex 0869f46436de..21eb365ebc7f 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts@@ -1,5 +1,6 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import api from 'lib/api'import { sceneFileLogic } from 'lib/components/Scenes/sceneFileLogic'@@ -123,17 +124,25 @@ describe('projectTreeDataLogic', () => {expect(logic.values.shortcutData).toEqual(updatedShortcuts)})- it('does not list a shortcut twice when starring returns one that already exists', async () => {+ it.each([+ { listedLocally: true, created: false },+ { listedLocally: false, created: false },+ { listedLocally: false, created: true },+ ])('lists a star once and counts it as added only when created (%o)', async ({ listedLocally, created }) => {await expectLogic(logic).toFinishAllListeners()const existing = { id: 'star-dash', path: 'Dashboards', type: 'dashboard', ref: '42' }- logic.actions.loadShortcutsSuccess([existing])- jest.spyOn(api.fileSystemShortcuts, 'create').mockResolvedValue(existing)+ logic.actions.loadShortcutsSuccess(listedLocally ? [existing] : [])+ jest.spyOn(api.fileSystemShortcuts, 'create').mockResolvedValue({ shortcut: existing, created })+ const capture = jest.spyOn(posthog, 'capture')await expectLogic(logic, () => {logic.actions.addShortcutItem({ id: 'dash', path: 'Dashboards', type: 'dashboard', ref: '42' })}).toFinishAllListeners()expect(logic.values.shortcutData.map((shortcut) => shortcut.id)).toEqual(['star-dash'])+ expect(capture.mock.calls.filter(([event]) => event === 'navbar starred item added')).toHaveLength(+ created ? 1 : 0+ )})it.each([false, true])('keeps starred navigation in place unless explicitly revealed (%s)', async (explicit) => {diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex 5b844a5b0527..82891d926da5 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -1079,11 +1079,14 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([},addShortcutItem: async ({ item }) => {const shortcutItem = shortcutFromEntry(item)- const response = await api.fileSystemShortcuts.create(shortcutItem)- posthog.capture('navbar starred item added', {- item_type: shortcutItem.type ?? 'unknown',- item_name: shortcutItem.path,- })+ const { shortcut: response, created } = await api.fileSystemShortcuts.create(shortcutItem)+ // A star the user already has, for example from another tab, is not a new add.+ if (created) {+ posthog.capture('navbar starred item added', {+ item_type: shortcutItem.type ?? 'unknown',+ item_name: shortcutItem.path,+ })+ }lemonToast.success('Added to starred')// The API returns the existing shortcut when the item is already starred, so// appending it unconditionally would show the same star twice until a reload.diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 8640c6d9abb4..aa0ffea70566 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2447,8 +2447,17 @@ const api = {}return await request.get({ signal })},- async create(data: { path: string; href?: string; ref?: string; type?: string }): Promise<FileSystemEntry> {- return await new ApiRequest().fileSystemShortcut().create({ data })+ async create(data: {+ path: string+ href?: string+ ref?: string+ type?: string+ }): Promise<{ shortcut: FileSystemEntry; created: boolean }> {+ const url = new ApiRequest().fileSystemShortcut().assembleFullUrl()+ const response = await api.createResponse(url, data)+ const shortcut: FileSystemEntry = await getJSONFromSuccessResponse(response, 'POST', url)+ // The API answers 200 instead of 201 when the user already has this shortcut.+ return { shortcut, created: response.status === 201 }},async delete(id: FileSystemEntry['id']): Promise<void> {return await new ApiRequest().fileSystemShortcutDetail(id).delete()diff --git a/posthog/api/file_system/file_system_shortcut.py b/posthog/api/file_system/file_system_shortcut.pyindex a4bfb6d7c017..f21bba47661c 100644--- a/posthog/api/file_system/file_system_shortcut.py+++ b/posthog/api/file_system/file_system_shortcut.py@@ -25,6 +25,8 @@ def reject_retired_type(value: str) -> str:class FileSystemShortcutSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):+ created: bool = True+class Meta:model = FileSystemShortcutfields = [@@ -79,6 +81,7 @@ class FileSystemShortcutSerializer(FileSystemAccessLevelSerializerMixin, serialihref=validated_data.get("href"),).first()if duplicate is not None:+ self.created = Falsereturn duplicate# Place new shortcuts at the end of the user's current order so they don't jump# ahead of items the user has explicitly reordered.@@ -165,6 +168,22 @@ class FileSystemShortcutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):context["file_system_surface"] = self.file_system_surfacereturn context+ @extend_schema(+ responses={+ 201: OpenApiResponse(response=FileSystemShortcutSerializer, description="The shortcut was created."),+ 200: OpenApiResponse(+ response=FileSystemShortcutSerializer,+ description="The user already has this shortcut. The existing shortcut is returned unchanged.",+ ),+ }+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = cast(FileSystemShortcutSerializer, self.get_serializer(data=request.data))+ serializer.is_valid(raise_exception=True)+ serializer.save()+ # Clients count a star as added only on 201, so a repeated star does not count twice.+ return Response(serializer.data, status=status.HTTP_201_CREATED if serializer.created else status.HTTP_200_OK)+def _scope_by_project(self, queryset):return queryset.filter(surface_q(self.file_system_surface), team__project_id=self.team.project_id)diff --git a/posthog/api/file_system/test/test_file_system_shortcut.py b/posthog/api/file_system/test/test_file_system_shortcut.pyindex d0a2e77ea4ef..9be64136225c 100644--- a/posthog/api/file_system/test/test_file_system_shortcut.py+++ b/posthog/api/file_system/test/test_file_system_shortcut.py@@ -215,7 +215,7 @@ class TestFileSystemShortcutAPI(APIBaseTest):second = self.client.post(f"/api/projects/{self.team.id}/file_system_shortcut/", payload, format="json")self.assertEqual(first.status_code, status.HTTP_201_CREATED, first.json())- self.assertEqual(second.status_code, status.HTTP_201_CREATED, second.json())+ self.assertEqual(second.status_code, status.HTTP_200_OK, second.json())self.assertEqual(second.json()["id"], first.json()["id"])self.assertEqual(FileSystemShortcut.objects.filter(team=self.team, user=self.user).count(), 1)