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.

fix(cross-project-dashboards): show each tile's own project annotations (#112501)

Yasen3371df98be79
diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
index de4ec2af3706..5f5d05e2c163 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
@@ -115,7 +115,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({
kind,
}
const logic = annotationsOverlayLogic(annotationsOverlayLogicProps)
- const { activeDate, tickDates, annotationBadgeDataIndices, groupedAnnotations } = useValues(logic)
+ const { activeDate, tickDates, annotationBadgeDataIndices, groupedAnnotations, readOnly } = useValues(logic)
const { closePopover } = useActions(logic)
const { closeModal } = useActions(annotationModalLogic)
@@ -191,7 +191,8 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({
}
ref={overlayRef}
>
- {tickDates.map((date, index) => {
+ {/* Tick badges are only targets for adding an annotation. */}
+ {(readOnly ? [] : tickDates).map((date, index) => {
const leftPx = index * tickIntervalPx + firstTickLeftPx - chartAreaLeft
// Strict `<` on both sides mirrors the cluster merge criterion so the
// suppression zone matches the merge zone exactly (no boundary gap).
@@ -348,7 +349,7 @@ function AnnotationsPopover({
badgeElement: HTMLButtonElement | null
cluster: AnnotationBadgeCluster | undefined
}): JSX.Element {
- const { activeDate, groupingUnit, isDateLocked, insightId, isPopoverShown, annotationsOverlayProps } =
+ const { activeDate, groupingUnit, isDateLocked, insightId, isPopoverShown, annotationsOverlayProps, readOnly } =
useValues(annotationsOverlayLogic)
const { closePopover } = useActions(annotationsOverlayLogic)
const { openModalToCreateAnnotation } = useActions(annotationModalLogic)
@@ -396,15 +397,21 @@ function AnnotationsPopover({
inline
title={`${pluralize(popoverAnnotations.length, 'annotation')} • ${titleDate}`}
footer={
- <LemonButton
- type="primary"
- onClick={() =>
- openModalToCreateAnnotation(activeDate, insightId, annotationsOverlayProps.dashboardId)
- }
- disabled={!isDateLocked}
- >
- Add annotation
- </LemonButton>
+ readOnly ? undefined : (
+ <LemonButton
+ type="primary"
+ onClick={() =>
+ openModalToCreateAnnotation(
+ activeDate,
+ insightId,
+ annotationsOverlayProps.dashboardId
+ )
+ }
+ disabled={!isDateLocked}
+ >
+ Add annotation
+ </LemonButton>
+ )
}
closable={isDateLocked}
onClose={closePopover}
@@ -426,7 +433,7 @@ function AnnotationsPopover({
}
function AnnotationCard({ annotation }: { annotation: AnnotationType }): JSX.Element {
- const { insightId, timezone, annotationsOverlayProps } = useValues(annotationsOverlayLogic)
+ const { insightId, timezone, annotationsOverlayProps, readOnly } = useValues(annotationsOverlayLogic)
const { deleteAnnotation } = useActions(annotationsModel)
const { openModalToEditAnnotation } = useActions(annotationModalLogic)
@@ -445,7 +452,7 @@ function AnnotationCard({ annotation }: { annotation: AnnotationType }): JSX.Ele
{annotationScopeToName[annotation.scope]}
-level
</h5>
- {!isSystemAnnotation && (
+ {!isSystemAnnotation && !readOnly && (
<>
<LemonButton
size="small"
diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts
index 07a1ed5d7bc2..3d9b0d126261 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts
+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.test.ts
@@ -12,6 +12,7 @@ import { initKeaTests } from '~/test/init'
import { AnnotationScope, AnnotationType, InsightShortId, IntervalType, RawAnnotationType } from '~/types'
import { annotationsOverlayLogic } from './annotationsOverlayLogic'
+import { projectAnnotationsLogic } from './projectAnnotationsLogic'
jest.spyOn(Storage.prototype, 'getItem')
@@ -175,6 +176,20 @@ const MOCK_ANNOTATION_DASHBOARD_SCOPED_3: RawAnnotationType = {
...BASE_MOCK_ANNOTATION,
}
+const OTHER_PROJECT_ID = 999
+/** ID 30 at 2022-08-10T04:00:00.000Z, in a project other than the current one */
+const MOCK_ANNOTATION_FROM_OTHER_PROJECT: RawAnnotationType = {
+ id: 30,
+ content: 'MOCK_ANNOTATION_FROM_OTHER_PROJECT',
+ date_marker: '2022-08-10T04:00:00.000Z',
+ dashboard_item: null,
+ insight_short_id: null,
+ insight_name: null,
+ insight_derived_name: null,
+ scope: AnnotationScope.Project,
+ ...BASE_MOCK_ANNOTATION,
+}
+
function useInsightMocks(interval: string = 'day', timezone: string = 'UTC'): void {
const insight = {
result: {},
@@ -379,6 +394,47 @@ describe('annotationsOverlayLogic', () => {
})
})
+ it('shows only the annotations of the project the insight comes from, read-only', async () => {
+ useInsightMocks()
+ useMocks({
+ get: {
+ [`/api/projects/${OTHER_PROJECT_ID}/annotations/`]: {
+ results: [MOCK_ANNOTATION_FROM_OTHER_PROJECT],
+ },
+ },
+ })
+ // The same insight already shows on its own project's page, for example in another scene tab.
+ const ownProjectLogic = annotationsOverlayLogic({
+ dashboardItemId: MOCK_INSIGHT_SHORT_ID,
+ insightNumericId: MOCK_INSIGHT_NUMERIC_ID,
+ dashboardId: MOCK_DASHBOARD_ID,
+ dates: ['2022-01-01', '2023-01-01'],
+ ticks: [{ value: 0 }, { value: 1 }],
+ })
+ ownProjectLogic.mount()
+
+ logic = annotationsOverlayLogic({
+ dashboardItemId: MOCK_INSIGHT_SHORT_ID,
+ insightNumericId: MOCK_INSIGHT_NUMERIC_ID,
+ dashboardId: MOCK_DASHBOARD_ID,
+ dates: ['2022-01-01', '2023-01-01'],
+ ticks: [{ value: 0 }, { value: 1 }],
+ sourceProject: { id: OTHER_PROJECT_ID, timezone: 'Europe/Moscow' },
+ })
+ logic.mount()
+ await expectLogic(projectAnnotationsLogic({ projectId: OTHER_PROJECT_ID })).toDispatchActions([
+ 'loadAnnotationsSuccess',
+ ])
+ await expectLogic(
+ insightLogic({ dashboardItemId: MOCK_INSIGHT_SHORT_ID, dashboardId: MOCK_DASHBOARD_ID })
+ ).toDispatchActions(['loadInsightSuccess'])
+ await expectLogic(logic).toMatchValues({
+ readOnly: true,
+ relevantAnnotations: [deserializeAnnotation(MOCK_ANNOTATION_FROM_OTHER_PROJECT, 'Europe/Moscow')],
+ })
+ ownProjectLogic.unmount()
+ })
+
it.each([
{
annotationsScope: AnnotationScope.Organization,
diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
index 24831f7073c8..436c497e94e7 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
@@ -10,7 +10,7 @@ import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { teamLogic } from 'scenes/teamLogic'
-import { AnnotationDataWithoutInsight, annotationsModel } from '~/models/annotationsModel'
+import { AnnotationDataWithoutInsight, annotationsModel, deserializeAnnotation } from '~/models/annotationsModel'
import { BreakdownFilter } from '~/queries/schema/schema-general'
import {
AnnotationScope,
@@ -19,6 +19,7 @@ import {
DashboardType,
DatedAnnotationType,
InsightLogicProps,
+ InsightSourceProject,
IntervalType,
PropertyGroupFilter,
InsightModel,
@@ -28,6 +29,7 @@ import type { AnnotationData } from '../../../models/annotationsModel'
import type { Node } from '../../../queries/schema/schema-general'
import type { RawAnnotationType } from '../../../types'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
+import { projectAnnotationsLogic } from './projectAnnotationsLogic'
export interface AnnotationsOverlayLogicProps extends Omit<InsightLogicProps, 'dashboardId'> {
dashboardId: DashboardType['id'] | undefined
@@ -77,8 +79,8 @@ function hasPersonPropertyFiltersOrBreakdown(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsOverlayLogicValues {
- annotations: AnnotationType[] // annotationsModel
- annotationsLoading: boolean // annotationsModel
+ currentProjectAnnotationsLoading: boolean // annotationsModel
+ currentProjectRawAnnotations: RawAnnotationType[] // annotationsModel
featureFlags: FeatureFlagsSet // featureFlagLogic
insightId: number | null // insightLogic
savedInsight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic
@@ -86,13 +88,17 @@ export interface annotationsOverlayLogicValues {
breakdownFilter: BreakdownFilter | null | undefined // insightVizDataLogic
interval: IntervalType | null | undefined // insightVizDataLogic
properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined // insightVizDataLogic
- timezone: string // teamLogic
+ sourceProjectAnnotationsLoading: boolean // projectAnnotationsLogic
+ sourceProjectRawAnnotations: RawAnnotationType[] // projectAnnotationsLogic
+ currentProjectTimezone: string // teamLogic
activeDate: Dayjs | null
annotationBadgeDataIndices: Array<{
dataIndex: number
date: Dayjs
dateKey: string
}>
+ annotations: AnnotationType[]
+ annotationsLoading: boolean
annotationsOverlayProps: AnnotationsOverlayLogicProps
dateRange: [Dayjs, Dayjs] | null
groupedAnnotations: Record<number | string, DatedAnnotationType[]>
@@ -100,9 +106,11 @@ export interface annotationsOverlayLogicValues {
intervalUnit: IntervalType
isDateLocked: boolean
isPopoverShown: boolean
+ readOnly: boolean
relevantAnnotations: DatedAnnotationType[]
tickDates: Dayjs[]
tickPositions: number[]
+ timezone: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -143,6 +151,19 @@ export interface annotationsOverlayLogicMeta {
key: number | string
__keaTypeGenInternalSelectorTypes: {
annotationsOverlayProps: (arg: any) => AnnotationsOverlayLogicProps
+ readOnly: (arg: InsightSourceProject | undefined) => boolean
+ timezone: (currentProjectTimezone: string, arg: InsightSourceProject | undefined) => string
+ annotations: (
+ currentProjectRawAnnotations: RawAnnotationType[],
+ sourceProjectRawAnnotations: RawAnnotationType[],
+ timezone: string,
+ arg: InsightSourceProject | undefined
+ ) => AnnotationType[]
+ annotationsLoading: (
+ currentProjectAnnotationsLoading: boolean,
+ sourceProjectAnnotationsLoading: boolean,
+ arg: InsightSourceProject | undefined
+ ) => boolean
intervalUnit: (interval: IntervalType | null | undefined) => IntervalType
groupingUnit: (intervalUnit: IntervalType) => IntervalType
tickPositions: (
@@ -190,18 +211,31 @@ export type annotationsOverlayLogicType = MakeLogicType<
export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
path((key) => ['lib', 'components', 'Annotations', 'annotationsOverlayLogic', key]),
- props({ dashboardId: undefined } as AnnotationsOverlayLogicProps),
- key(({ insightNumericId, kind }) => (kind ? `${insightNumericId}::${kind}` : insightNumericId)),
- connect(() => ({
+ props({ dashboardId: undefined, sourceProject: undefined } as AnnotationsOverlayLogicProps),
+ key(({ insightNumericId, kind, sourceProject }) => {
+ const key = kind ? `${insightNumericId}::${kind}` : insightNumericId
+ // The connected annotation source is fixed when the logic is built, and one insight can show in its own
+ // project and on a cross-project dashboard at once, in two scene tabs.
+ return sourceProject ? `${key}@${sourceProject.id}` : key
+ }),
+ connect((props: AnnotationsOverlayLogicProps) => ({
values: [
insightLogic,
['insightId', 'savedInsight'],
insightVizDataLogic,
['interval', 'properties', 'breakdownFilter', 'annotationsScope'],
annotationsModel,
- ['annotations', 'annotationsLoading'],
+ [
+ 'rawAnnotations as currentProjectRawAnnotations',
+ 'rawAnnotationsLoading as currentProjectAnnotationsLoading',
+ ],
+ projectAnnotationsLogic({ projectId: props.sourceProject?.id ?? null }),
+ [
+ 'rawAnnotations as sourceProjectRawAnnotations',
+ 'rawAnnotationsLoading as sourceProjectAnnotationsLoading',
+ ],
teamLogic,
- ['timezone'],
+ ['timezone as currentProjectTimezone'],
featureFlagLogic,
['featureFlags'],
],
@@ -241,8 +275,11 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
},
],
}),
- listeners(({ actions, props }) => ({
+ listeners(({ actions, props, values }) => ({
createAnnotation: async ({ annotationData }) => {
+ if (values.readOnly) {
+ return
+ }
const insightNumericId = props.insightNumericId !== 'new' ? props.insightNumericId : null
actions.createAnnotationGenerically({ ...annotationData, dashboard_item: insightNumericId })
},
@@ -252,6 +289,46 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
() => [(_, props) => props],
(props: AnnotationsOverlayLogicProps): AnnotationsOverlayLogicProps => props,
],
+ // Annotations are created and edited through the current project's endpoints, which would
+ // file them under the wrong project or miss them.
+ readOnly: [
+ () => [(_, props: AnnotationsOverlayLogicProps) => props.sourceProject],
+ (sourceProject: InsightSourceProject | undefined): boolean => !!sourceProject,
+ ],
+ timezone: [
+ (s) => [s.currentProjectTimezone, (_, props: AnnotationsOverlayLogicProps) => props.sourceProject],
+ (currentProjectTimezone: string, sourceProject: InsightSourceProject | undefined): string =>
+ sourceProject?.timezone ?? currentProjectTimezone,
+ ],
+ annotations: [
+ (s) => [
+ s.currentProjectRawAnnotations,
+ s.sourceProjectRawAnnotations,
+ s.timezone,
+ (_, props: AnnotationsOverlayLogicProps) => props.sourceProject,
+ ],
+ (
+ currentProjectRawAnnotations: RawAnnotationType[],
+ sourceProjectRawAnnotations: RawAnnotationType[],
+ timezone: string,
+ sourceProject: InsightSourceProject | undefined
+ ): AnnotationType[] =>
+ (sourceProject ? sourceProjectRawAnnotations : currentProjectRawAnnotations).map((annotation) =>
+ deserializeAnnotation(annotation, timezone)
+ ),
+ ],
+ annotationsLoading: [
+ (s) => [
+ s.currentProjectAnnotationsLoading,
+ s.sourceProjectAnnotationsLoading,
+ (_, props: AnnotationsOverlayLogicProps) => props.sourceProject,
+ ],
+ (
+ currentProjectAnnotationsLoading: boolean,
+ sourceProjectAnnotationsLoading: boolean,
+ sourceProject: InsightSourceProject | undefined
+ ): boolean => (sourceProject ? sourceProjectAnnotationsLoading : currentProjectAnnotationsLoading),
+ ],
intervalUnit: [(s) => [s.interval], (interval: IntervalType | null | undefined) => interval || 'day'],
groupingUnit: [
(s) => [s.intervalUnit],
diff --git a/frontend/src/lib/components/AnnotationsOverlay/projectAnnotationsLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/projectAnnotationsLogic.ts
new file mode 100644
index 000000000000..f8407ab7c429
--- /dev/null
+++ b/frontend/src/lib/components/AnnotationsOverlay/projectAnnotationsLogic.ts
@@ -0,0 +1,78 @@
+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { RawAnnotationType } from '~/types'
+
+import { annotationsList } from 'products/annotations/frontend/generated/api'
+import type { AnnotationsListParams } from 'products/annotations/frontend/generated/api.schemas'
+
+export interface ProjectAnnotationsLogicProps {
+ /** Null when the chart belongs to the current project, whose annotations `annotationsModel` already holds. */
+ projectId: number | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectAnnotationsLogicValues {
+ rawAnnotations: RawAnnotationType[]
+ rawAnnotationsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectAnnotationsLogicActions {
+ loadAnnotations: () => any
+ loadAnnotationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAnnotationsSuccess: (
+ rawAnnotations: RawAnnotationType[],
+ payload?: any
+ ) => {
+ rawAnnotations: RawAnnotationType[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectAnnotationsLogicMeta {
+ key: number | 'current'
+}
+
+export type projectAnnotationsLogicType = MakeLogicType<
+ projectAnnotationsLogicValues,
+ projectAnnotationsLogicActions,
+ ProjectAnnotationsLogicProps,
+ projectAnnotationsLogicMeta
+>
+
+/** `annotationsModel` holds only the current project's annotations, so a chart from another project reads them here. */
+export const projectAnnotationsLogic = kea<projectAnnotationsLogicType>([
+ props({} as ProjectAnnotationsLogicProps),
+ key(({ projectId }) => projectId ?? 'current'),
+ path((key) => ['lib', 'components', 'AnnotationsOverlay', 'projectAnnotationsLogic', key]),
+ loaders(({ props }) => ({
+ rawAnnotations: [
+ [] as RawAnnotationType[],
+ {
+ loadAnnotations: async () => {
+ if (props.projectId === null) {
+ return []
+ }
+ // The endpoint filters on this parameter, but its schema does not declare it.
+ const params = { hidden_in_user_interface: false } as AnnotationsListParams
+ const response = await annotationsList(String(props.projectId), params)
+ // The overlay works on the handwritten annotation type, which describes this same payload.
+ return response.results as unknown as RawAnnotationType[]
+ },
+ },
+ ],
+ })),
+ afterMount(({ actions, props }) => {
+ if (props.projectId !== null) {
+ actions.loadAnnotations()
+ }
+ }),
+])
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 16e1da66c851..94de9d84005d 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -225,6 +225,8 @@ export interface InsightCardProps extends Resizeable {
onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
/** Project the insight belongs to, when that is not the current project. The card's links then open it there. */
projectId?: number
+ /** Time zone of `projectId`, so the chart places that project's annotations on the right day. */
+ projectTimezone?: string
/** Shown above the title, for a card that has to name where its insight comes from. */
contextHeading?: JSX.Element | null
}
@@ -267,6 +269,7 @@ function InsightCardInternal(
variablesOverride,
children,
projectId,
+ projectTimezone,
contextHeading,
breakdownColorOverride: _breakdownColorOverride,
dataColorThemeId: _dataColorThemeId,
@@ -321,8 +324,17 @@ function InsightCardInternal(
loadPriority,
doNotLoad,
refreshAfterDisplayOptionsChange: handleRefreshAfterDisplayOptionsChange,
+ sourceProject: projectId !== undefined ? { id: projectId, timezone: projectTimezone } : undefined,
}),
- [insight, dashboardId, loadPriority, doNotLoad, handleRefreshAfterDisplayOptionsChange]
+ [
+ insight,
+ dashboardId,
+ loadPriority,
+ doNotLoad,
+ handleRefreshAfterDisplayOptionsChange,
+ projectId,
+ projectTimezone,
+ ]
)
const { persistDisplayOptions } = useActions(insightDataLogic(insightLogicPropsBase))
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 90810501e6db..12c48993ac2b 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3774,6 +3774,17 @@ export interface InsightLogicProps<Q extends QuerySchema = QuerySchema> {
tileFiltersOverride?: TileFilters | null
/** The tab of the scene if the insight is a full scene insight */
tabId?: string | null
+ /**
+ * The project the insight comes from, when a page shows insights from several projects. Its
+ * charts then show that project's annotations, read-only, in that project's time zone.
+ */
+ sourceProject?: InsightSourceProject
+}
+
+export interface InsightSourceProject {
+ id: number
+ /** Unknown until the page has loaded the project, and the chart uses the current project's time zone until then. */
+ timezone?: string
}
export interface SetInsightOptions {
diff --git a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx
index fef48c9f9d66..c0ee3cabcce4 100644
--- a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx
+++ b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx
@@ -144,6 +144,7 @@ function CrossProjectTileInternal(
insight={insight}
tile={asCardTile(tile)}
projectId={tile.project_id}
+ projectTimezone={projectTimezone}
contextHeading={projectHeading}
ribbonColor={tile.color as InsightColor | null}
updateColor={onSetColor ? (color) => onSetColor(color ?? null) : undefined}