: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(activity-log): make activity across products easier to scan (#101980)
Paul D'Ambrace92f0f0b0e8
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 291ea8894195..98ebb5375cc4 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -9,6 +9,33 @@ This doc says how a change becomes an activity row, where the code for a new modThe skill `.agents/skills/adding-activity-logging/SKILL.md` carries the step-by-step workflow.Read this doc before you add or change activity logging.+## Reading activity rows++Activity rows show the actor, optional client tag, and time above the action summary and its target.+Long action summaries collapse to two lines.+Description changes include a two-line preview of the new value in normal text.+The expand control on the right reveals the complete action, preview, and agent intent, along with the existing detail tabs.+Diff compares the recorded values, and Raw shows the activity payload.+Product-specific detail tabs remain the initial view when supplied by a describer.+The copy-link control beside expand appears on hover or keyboard focus.++Every visible describer result supplies a `summary` with `actor`, `action`, and `target` fields alongside its existing `description`.+Use `activityLogSummary` for the usual actor, or pass a specialized actor such as a workflow link or an anonymous user.+The optional plain-text `preview` holds long values such as descriptions; keep them out of the action headline.+Field mappings can supply separate summary clauses and a preview while preserving their notification wording.+Summary clauses stay lowercase so combined changes read as one sentence, and they do not depend on notification mode.+Use `summarizeDescriptionChange` for consistent added, updated, and cleared description clauses.+Rename summaries retain both names, with the resource link in the target.+Use `describeMappedChanges` for a field-to-handler mapping, or `describeChangeMappings` when a product needs its own change selection.+Both helpers assemble the summary and notification sentence and retain extended descriptions and custom detail tabs.+The row uses that structure without parsing a JSX sentence.+The complete `description` remains available to notifications and other activity consumers.+A describer can still return `description: null` to hide an event.+Keep existing fallback rows when no fields have a description, and preserve collected changes if a later field cannot be described.+The row retains sentence rendering for legacy items constructed without a summary.+The sentence aligns with the avatar, with the client tag and time underneath.+Agent intent and task links remain optional and retain their existing attribution rules.+## How a change becomes an activity row```textdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 767237de5de8..6a2f73124aef 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -93,37 +93,65 @@ snapshots:components-activityclienttag--sdk--light:hash: v1.k794b7964.9c2107c79242cdf242289e892425279ec458cdd52bd7db647511edc9e201ef82.0RLoWz3N9SJu232VDLYehttumTHmbRhxGd3zOqY311Icomponents-activitylog--data-management-activity--dark:- hash: v1.k794b7964.c0fd7565eccb2a1b348b4e994751489c4d2922648e7bd2aafed432a72e979e44.D18rmt5xbd-90izaBhP2OrO9uNIGf_4PKa_f2Mogmyk+ hash: v1.k794b7964.51bcd190a645921a30076aff575bcdc48bc6e12f8ddfefd757a17a572f1cc955.5uBxPvBCvyLTHgnBNUzlo8KKoxEPNPQs1f_vy-EI7P4components-activitylog--data-management-activity--light:- hash: v1.k794b7964.2de1f2b9f7ac1b902c9e2e0c43867770ae703abc07bf397d62f173171f0f3e97.EcZZDXwHHM4LaBsE1yChqI_9TBtDIflrBdz6OTtFjxE+ hash: v1.k794b7964.390698bc726f80e26bc050b095c8930faeff706cd0ba758fee5651c4c986bf77.9rm06eBJ8XOZJgtbHSF-zIs0pcRFWDpaD_UUQLYeC-Mcomponents-activitylog--feature-flag-activity--dark:- hash: v1.k794b7964.1dac32db25d6d76a6d02953093f1e0a0368ca8ef009faba9b01250b8da223a95.VyKy0x-jtdoLlv3B-3p4xplcbAU6jyk9HbuRDdZG1Fo+ hash: v1.k794b7964.ca16df64c83ff18eba1f458e6262133024444ef23d1cf64fae990caaad2f7030.ac5p7UacbC6GF9pd8QuDUlvPyligSFXDHbECQ17E8fccomponents-activitylog--feature-flag-activity--light:- hash: v1.k794b7964.4d0ea9b5e240664f5a1bfd696d07d1a4eea152567cd3ee16af963ecd9ab31cb9.XFh5MPIIt4FV_pf16hgPtmBadov5zGa6jA8s1AOfzrU+ hash: v1.k794b7964.92bd60b30317c238ee304d1cc1a8733ec25a320c49999c5617fe4a15597e9543.tKiW7XZxSQJeObWp934Hi1-Mm-Rvv3Rb7hKPFK1UcH0components-activitylog--insight-activity--dark:- hash: v1.k794b7964.eeb2e5b54ba0acf05e292aba372702616dc9c6326fd8bcbf4bbf1125fcb7c637.XMwf5MqrlV-FQsYrL-4Db38vN69QQAmBms5tmbFQlSw+ hash: v1.k794b7964.001945e53edef6a7e26d36c6fdd96e33a9da0da16decea1f0c7b2f45f969fe82.ejmGyyd4QUZkG0mee3y4PqGTZFEB3itQppw0iQamkf0components-activitylog--insight-activity--light:- hash: v1.k794b7964.94aae0b511d11de8cf139dd502bc7170494be36e74fd517187ce37048c514447.ZOKfzkSSO6DcNPVEP0DWvmeA3hHVd35t1AYL5yrrkPk+ hash: v1.k794b7964.7f24036a783846f5f283e86ed291c76276de97c5509d5f9212f783150f771b12.WvTI8ECQTFBjjIdfd7l3QLSnfreqBPAKtGJL1FiziW4components-activitylog--persons-activity--dark:- hash: v1.k794b7964.432ff34c2d8dd67ca60593d6440de2eb053e4a8ddbfcc6cbfe4a25bce324f0d9.kljasPbvnNb_HfMKLGFlj58Wgh283EQnarNEpOf8J4U+ hash: v1.k794b7964.7869047b2d8473c7b13d111bd4dd5b555858c9a97e43e71940637fa2b965a1cf.9_lJVnk7KUQtV6uT_Fxv-1hQwdFXCV4SYoSis-xmym0components-activitylog--persons-activity--light:- hash: v1.k794b7964.b5eb5208d760d4a941552dab6cd2aab1edc92ecfa58926ec264aeef97ff9150f.-tTuCQ_o2m613vcQ4vWUcn3ayr_AaiawCrbsOBHYQys+ hash: v1.k794b7964.f1350b93b18b74b069e182b554af2b527164c160691c2544fbdf92e271d458c1.M4v_D_EX3-g8bTgRtg4loBYpy2arSxTWZiCJG3ppxN8components-activitylog--team-activity--dark:- hash: v1.k794b7964.bc25a618afb2de26c3eff106868ab4fbd3e52b19c7ac52d47c4427db32dd732c.bXtU3DwI_WpnlCnHAOu_8lbo2gMt9qQA4zp3UEhjf04+ hash: v1.k794b7964.b4f3f641dfcab8b74c30fe59e300fc84ddd8415093802b9aecf3443f35b6941c.L0AcRJ4rXbWxoqvixP4BirCJrlvrrTA5e1LHOdxKe3Ycomponents-activitylog--team-activity--light:- hash: v1.k794b7964.10d5353835f51b3db0c19a80aa9f457523e6d698389a02b72bdf360a636807bd.2Fjfwjkw22VkdyEm_oYP64jgiEZbtSYUV2P_snheeHU+ hash: v1.k794b7964.a61dbf78e04e1c28bc8e61336753ab0bee6c2ae8b61ac52f6dbbcb844654b45b.O7cNdE8jWTjbMddnD5XbMXm5R7zNPBxaXv5RVPoCwjccomponents-activitylog--with-caption--dark:- hash: v1.k794b7964.9188cd8eecfbe14ff000a4daa237858f90d02667c76ae4e40bf902857fb2f407.USkSSkFqRGXtN-wH8cetAwOqFKH0nFnXKh6tjRx5zOc+ hash: v1.k794b7964.beba3ba19e4bce30a1b0d3b5e8815faf7a0a97d34c12b80801d621ee351f11be.sM201sLL5PurOVO6W-j35-MUF7L76KpiNPDuK-ggWfwcomponents-activitylog--with-caption--light:- hash: v1.k794b7964.38803a04d4ae34e0901aae419866fd1571d06cba43aa585374450efa5dbbb654.EocQNZd4xc-hKDaksq_LzruooC1nBMisuTV5xL0kTCc+ hash: v1.k794b7964.7296f93d203c6c225126bff12356d20f502bd0287fca8ca0d5ce09e460956ac7.nm4w9WkJzCjBEzDnrapKbuZEEIw27o22YgJSTHmKspAcomponents-activitylog--with-no-data--dark:- hash: v1.k794b7964.a639d0f489ca1519634969688cbadae4ebd9e977221b2d85594dfd793e494a57.A1Sl4bZi1PZr56FFNlP4SIy-lCtzRdRgPQOgtyiPdSs+ hash: v1.k794b7964.0ecabad3d54691d2fefafa9b50c0b88db5e9169a2f0dd43c28986a3ca2a65393.EUqGWCrlfXmeq333qfrbMDQ6JKE_mumU7Ers6OJP4dMcomponents-activitylog--with-no-data--light:- hash: v1.k794b7964.02fb05a0a574572e30f7c15b6b43000680acb584e556bdaf95f99032346054df.Bm6yBJfwUttSy609Eo1TXXFj0cNk_8YJcot92ZgJD1s+ hash: v1.k794b7964.0f33c04ce2f5de667b11c84f87d73fef746686d5f54d740fcd73bc8a7606d1f3.zZo_wyZHw0A2FGdZdX-gsNzKZGyGXl0_5sdKE67SGdkcomponents-activitylog--without-audit-logs-feaure--dark:- hash: v1.k794b7964.6aab6f60f5f5106fd66cf02ad1f62be1e3c7bf08e13b75761f75b1fdff364568.YblDy_cCbcSdCbly1El4Qw3GRwtAFGM11gHIH-dHk9o+ hash: v1.k794b7964.a1bbe747f3fcdc3c082040c3abd9875466536a09274eb8e325f6d5451a25229b.IKUWU3Xi2gCedlDdCaexrvu7FTJoOhOTIeEG4YM1JKYcomponents-activitylog--without-audit-logs-feaure--light:- hash: v1.k794b7964.1eed88732da4c326634cb530f95a9abd01a0c58ee567835a43165e77d675b6eb.rB6MYt2DBwRCcUcRIYjwQ629nrgOWhD3uoF8J02EuXU+ hash: v1.k794b7964.4eef20bf1ecaf303d033bac6c574aca8d32dba6efab91858aec48032585ce951.m8DC6Q3s0giRc3IlHBNr_iYPCaBG3Hd8FRjESoWCr14+ components-activitylogrow--across-products--dark:+ hash: v1.k794b7964.0ecc4f8f6eab5ed35a4dc1d7f3a997a74dcc6b2c8ea08e025412a95442cf568e.EASqf__UfRGPtPC7h6ShrSGOTQvGX5gK374AvUxV1Vw+ components-activitylogrow--across-products--light:+ hash: v1.k794b7964.4772a84d1d3449b6897878e67153430cee0c577f7ed1f7e7dd8396593dc0835e.NSH7C-98Lbdcpu8HRX4Uxi5vjF03YTvHwwleISrcW_w+ components-activitylogrow--dashboard-changes--dark:+ hash: v1.k794b7964.96f7c6fa429d6a8221876d3318337a3e7c6e6b9f107f63792342cd6e4d365a4d.hn51ZQzBNUfhvY5YHtn1YHww7lXasyfSCcyk-BMdPYw+ components-activitylogrow--dashboard-changes--light:+ hash: v1.k794b7964.50bf8f3a91f04a5311eae39e1ed5c4e2843e128fed9c3a04796977efbdd0f916.1iEMJtc9WI70AqQOhr6GmHUubxq7LafRlSfs-e1AtYU+ components-activitylogrow--expanded-view--dark:+ hash: v1.k794b7964.f9596bca85d244306d21b6a892ab5554cfaef09efa6eace45e7e76a2b8936842.ZkoywlWpeMSEwX7sZVDio_mfhCfo2-R7Xvl8oum_nPs+ components-activitylogrow--expanded-view--light:+ hash: v1.k794b7964.fb20830c52b193dc724b7675d2a4bf19f3f76f7554728e1b6470a7b4a9743a80.iXsa5h1q1k1RaZt8Azyj8lFzyu6-oYIBbcErQBg0v74+ components-activitylogrow--human-change--dark:+ hash: v1.k794b7964.139a79a458233b51dd5d9f33087b628ae4c7c8004b2f498219f3aeab56455a6e._Z8p8eot-MoqL4r13f7Q8pG4dOIKYqSwzfqW3nHKjBk+ components-activitylogrow--human-change--light:+ hash: v1.k794b7964.e498e055beb2ab00b1da412b6f629dc1d4d52be3560c6d2dca2b90a4db8ab634.p8-csA9eUQ9iihRoJDOFI7smezp633lBuJsuBYbEu4c+ components-activitylogrow--legacy-description--dark:+ hash: v1.k794b7964.903539a9804a4147c4b492a54b04b251d920352900d4753bd75820e45bed69aa.piwMO-La6cXlE4lAAPK9huyo2-W0SfdGV0A1TkRnRZ0+ components-activitylogrow--legacy-description--light:+ hash: v1.k794b7964.a3eb0b7cbb64705754166c38b671b4b84d879356768cba63d20a6bf0ad113a7f.QKBSux_6rSnQ8P2fa8f0vqGDLRxW8UDxMWw0cP9xLrE+ components-activitylogrow--narrow-across-products--dark:+ hash: v1.k794b7964.6a698c15a2b55889575cd95c5a9bd83b4d573ec85704d693e38229a37514a089.uBZjKrSmBxVSqrEgzIpM6DudrQw40SK2pjXo-DzIGkU+ components-activitylogrow--narrow-across-products--light:+ hash: v1.k794b7964.e4869822676914235fc9eb78611d464ac2ec6513a9ef81a59bde7c74d2c29fc2.2fhY8cqkX7KUaDnq2q1_1HJuOo5G5nWPpyzUr7fDU54+ components-activitylogrow--narrow-dashboard-changes--dark:+ hash: v1.k794b7964.4f7b276bd60977800b9ea20ddd221bffb6ccda7814b973e7b07bdaa85467996c.l51S8oLHNfi5ewuK9InQ4F9ixNJfXEeXnVLGXkyxucM+ components-activitylogrow--narrow-dashboard-changes--light:+ hash: v1.k794b7964.095ac6cc7ea7e35c94ab04aa2241c01e5ef3fdaa46d4fcde75ac76fae3ff01ad.F9DiID4HmI2V97skUnG3PT25MCLIAGxOda6D-BvVf_kcomponents-agentattribution--intent-and-task--dark:hash: v1.k794b7964.0d80c815b27006d88f038af4b2d689f510f8bdf583d7fc830eb68942821b56e4.vFLLhu562dwroQu8TA_dLSIrYC3SgtRpKdZTB8ufS84components-agentattribution--intent-and-task--light:@@ -7117,9 +7145,9 @@ snapshots:scenes-app-batchexports--history-empty--light:hash: v1.k794b7964.6e59b0f0726dd11daf6b7718d9f32d720e336a6753c19131e62098a40931961e.nZDF42SgAaRmgUR6tFKyVXF-M4LgD7Z55mwCTy_UeDMscenes-app-batchexports--history-with-activity--dark:- hash: v1.k794b7964.047ea02963790378acdd8aee67dbde3a6f8a14558477fd079d049ac54ac016e0.AxL4eaTLOQ7Nk9YNv0NrenX-mBA2LcNfmUZeGQZ8Zz0+ hash: v1.k794b7964.c4ac886c4397a4c7da4ca7b23893c4dd74b64235306917fd30576025d30a179e.zH3x0zixm2U87fZaZpWmz-VL8XvmGeERiAd7GXGBrvUscenes-app-batchexports--history-with-activity--light:- hash: v1.k794b7964.258d61da8bfdf1965ca21687fd1e3267e82cbc40f92ff0953df7dd5865eafffb.tbvK_J8jZZr-6jdU-hbv_sYd8CeHmkPjziHPtUGYbzY+ hash: v1.k794b7964.d5285c5ee3958e569d5d6075a29cbf6dcc10f64007f197312d85ed83701611c9.XlE6H8rUtUxmXDgoP75X1TJk7vyckKaW8OADPH_OND0scenes-app-batchexports--logs--dark:hash: v1.k794b7964.ba725da206f3bf072c49d556df9b19cea3fbaa8e48a205c036ac94f9c100f047.zRJXSI8W8bULOYj3wJIqyRXNm4hDtlKkOBEFJUV7aNEscenes-app-batchexports--logs--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsxindex cf5eb6659a80..1d99b5d0cc4b 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx@@ -4,7 +4,7 @@ import { useRef } from 'react'import { IconList, IconNotification } from '@posthog/icons'import { LemonButton, LemonSkeleton, LemonTabs, Link, Spinner } from '@posthog/lemon-ui'-import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLog'+import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLogRow'import { ActivityLogSubscribeMenu } from 'lib/components/ActivityLog/ActivityLogSubscribeMenu'import { humanizeScope } from 'lib/components/ActivityLog/humanizeActivity'import { MemberSelect } from 'lib/components/MemberSelect'@@ -18,6 +18,7 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import {+ ActivityFilters,SidePanelActivityTab,sidePanelActivityLogic,} from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelActivityLogic'@@ -47,11 +48,8 @@ export const SidePanelActivityIcon = (props: { className?: string }): JSX.Elemen}export const SidePanelActivity = (): JSX.Element => {- const { activeTab, allActivity, allActivityResponseLoading, allActivityHasNext, activeFilters, contextFromPage } =- useValues(sidePanelActivityLogic)- const { setActiveTab, maybeLoadOlderActivity, setActiveFilters } = useActions(sidePanelActivityLogic)-- const { closeSidePanel } = useActions(sidePanelStateLogic)+ const { activeTab, contextFromPage } = useValues(sidePanelActivityLogic)+ const { setActiveTab } = useActions(sidePanelActivityLogic)const { user } = useValues(userLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -59,40 +57,11 @@ export const SidePanelActivity = (): JSX.Element => {const hasAccess = userHasAccess(AccessControlResourceType.ActivityLog, AccessControlLevel.Viewer)const lastScrollPositionRef = useRef(0)- const contentRef = useRef<HTMLDivElement | null>(null)- const handleScroll = (e: React.UIEvent<HTMLDivElement>): void => {- // If we are scrolling down then check if we are at the bottom of the list- if (e.currentTarget.scrollTop > lastScrollPositionRef.current) {- const scrollPosition = e.currentTarget.scrollTop + e.currentTarget.clientHeight- if (e.currentTarget.scrollHeight - scrollPosition < SCROLL_TRIGGER_OFFSET) {- maybeLoadOlderActivity()- }- }-- lastScrollPositionRef.current = e.currentTarget.scrollTop- }-- const hasItemContext = Boolean(contextFromPage?.scope && contextFromPage?.item_id)- const hasListContext = Boolean(contextFromPage?.scope && !contextFromPage?.item_id)- const hasAnyContext = hasItemContext || hasListContext+ const handleScroll = useLoadOlderActivityOnScroll(lastScrollPositionRef)if (!hasAccess) {- return (- <>- <SidePanelPaneHeader title="Team activity" />- <div className="flex flex-col items-center justify-center gap-3 p-6 text-center h-full">- <IconNotification className="text-5xl text-muted" />- <div>- <div className="font-semibold mb-1">Access denied</div>- <div className="text-xs text-muted-alt">- You don't have sufficient permissions to view activity logs. Please contact your project- administrator.- </div>- </div>- </div>- </>- )+ return <AccessDeniedPane />}return (@@ -127,153 +96,16 @@ export const SidePanelActivity = (): JSX.Element => {</div>{/* Controls */}- {activeTab === SidePanelActivityTab.All && hasAnyContext ? (- <div className="flex items-center justify-between gap-2 px-2 pb-2">- <div className="flex items-center gap-2">- <span>- Activity on{' '}- <strong>- {hasItemContext- ? `this ${humanizeScope(contextFromPage!.scope!, true).toLowerCase()}`- : `all ${humanizeScope(contextFromPage!.scope!).toLowerCase()}`}- </strong>- </span>- <ActivityLogSubscribeMenu- properties={[- {- key: 'scope',- type: PropertyFilterType.Event,- value: contextFromPage!.scope!,- operator: PropertyOperator.Exact,- },- ...(hasItemContext- ? [- {- key: 'item_id',- type: PropertyFilterType.Event as const,- value: contextFromPage!.item_id,- operator: PropertyOperator.Exact,- },- ]- : []),- ]}- onNavigate={closeSidePanel}- iconOnly- />- </div>- <MemberSelect- value={activeFilters?.user ?? null}- onChange={(user) =>- setActiveFilters({- ...activeFilters,- user: user?.id ?? undefined,- })- }- />- </div>+ {activeTab === SidePanelActivityTab.All && Boolean(contextFromPage?.scope) ? (+ <ActivityContextControls+ contextFromPage={contextFromPage!}+ hasItemContext={Boolean(contextFromPage?.item_id)}+ />) : null}- <div className="flex flex-col flex-1 overflow-hidden" ref={contentRef} onScroll={handleScroll}>+ <div className="flex flex-col flex-1 overflow-hidden" onScroll={handleScroll}><ScrollableShadows direction="vertical" innerClassName="p-2 deprecated-space-y-px">- {activeTab === SidePanelActivityTab.All ? (- hasAnyContext ? (- <>- {allActivityResponseLoading ? (- <LemonSkeleton className="h-12 my-2" repeat={10} fade />- ) : allActivity.length ? (- <>- {allActivity.map((logItem, index) => (- <ActivityLogRow logItem={logItem} key={index} />- ))}-- <div className="flex items-center justify-center h-10 gap-2 m-4 text-secondary">- {allActivityResponseLoading ? (- <>- <Spinner textColored /> Loading older activity- </>- ) : allActivityHasNext ? (- <LemonButton- type="secondary"- fullWidth- center- onClick={() => maybeLoadOlderActivity()}- >- Load more- </LemonButton>- ) : (- 'No more results'- )}- </div>- <div className="flex items-center justify-center pt-1">- <Link- to={urls.advancedActivityLogs()}- onClick={() => closeSidePanel()}- className="text-muted-alt text-xs"- >- or browse all activity logs- </Link>- </div>- </>- ) : (- <div className="flex flex-col items-center gap-2 p-6 text-center border border-dashed rounded">- <span>No activity yet</span>- {activeFilters?.user ? (- <LemonButton- size="small"- type="secondary"- onClick={() =>- setActiveFilters({- ...activeFilters,- user: undefined,- })- }- >- Clear user filter- </LemonButton>- ) : null}- <div className="flex flex-col items-center justify-center text-xs text-muted-alt">- <LemonButton- size="small"- type="secondary"- to={urls.advancedActivityLogs()}- data-attr="browse-all-activity-logs"- onClick={() => closeSidePanel()}- >- Browse all activity logs- </LemonButton>- </div>- </div>- )}- </>- ) : (- <div className="flex flex-col items-center justify-center gap-3 p-6 text-center h-full">- <IconList className="text-5xl text-muted" />- <div>- <div className="font-semibold mb-1">Activity is context-aware</div>- <div className="text-xs text-muted-alt">- Navigate to a page like dashboards or a specific dashboard to see- activity in this panel- </div>- </div>- <div className="flex items-center gap-2 text-xs text-muted-alt">- <div className="border-t flex-1" />- <span>or</span>- <div className="border-t flex-1" />- </div>- <LemonButton- size="small"- type="secondary"- to={urls.advancedActivityLogs()}- data-attr="browse-all-activity-logs"- onClick={() => closeSidePanel()}- >- Browse all activity logs- </LemonButton>- </div>- )- ) : activeTab === SidePanelActivityTab.Metalytics ? (- <SidePanelActivityMetalytics />- ) : null}+ <ActivityPanelBody activeTab={activeTab} /></ScrollableShadows></div></div>@@ -281,3 +113,225 @@ export const SidePanelActivity = (): JSX.Element => {</>)}++function useLoadOlderActivityOnScroll(+ lastScrollPositionRef: React.MutableRefObject<number>+): (e: React.UIEvent<HTMLDivElement>) => void {+ const { maybeLoadOlderActivity } = useActions(sidePanelActivityLogic)++ return (e) => {+ // If we are scrolling down then check if we are at the bottom of the list+ if (e.currentTarget.scrollTop > lastScrollPositionRef.current) {+ const scrollPosition = e.currentTarget.scrollTop + e.currentTarget.clientHeight+ if (e.currentTarget.scrollHeight - scrollPosition < SCROLL_TRIGGER_OFFSET) {+ maybeLoadOlderActivity()+ }+ }++ lastScrollPositionRef.current = e.currentTarget.scrollTop+ }+}++function AccessDeniedPane(): JSX.Element {+ return (+ <>+ <SidePanelPaneHeader title="Team activity" />+ <div className="flex flex-col items-center justify-center gap-3 p-6 text-center h-full">+ <IconNotification className="text-5xl text-muted" />+ <div>+ <div className="font-semibold mb-1">Access denied</div>+ <div className="text-xs text-muted-alt">+ You don't have sufficient permissions to view activity logs. Please contact your project+ administrator.+ </div>+ </div>+ </div>+ </>+ )+}++function ActivityContextControls({+ contextFromPage,+ hasItemContext,+}: {+ contextFromPage: ActivityFilters+ hasItemContext: boolean+}): JSX.Element {+ const { activeFilters } = useValues(sidePanelActivityLogic)+ const { setActiveFilters } = useActions(sidePanelActivityLogic)+ const { closeSidePanel } = useActions(sidePanelStateLogic)++ return (+ <div className="flex items-center justify-between gap-2 px-2 pb-2">+ <div className="flex items-center gap-2">+ <span>+ Activity on{' '}+ <strong>+ {hasItemContext+ ? `this ${humanizeScope(contextFromPage.scope!, true).toLowerCase()}`+ : `all ${humanizeScope(contextFromPage.scope!).toLowerCase()}`}+ </strong>+ </span>+ <ActivityLogSubscribeMenu+ properties={[+ {+ key: 'scope',+ type: PropertyFilterType.Event,+ value: contextFromPage.scope!,+ operator: PropertyOperator.Exact,+ },+ ...(hasItemContext+ ? [+ {+ key: 'item_id',+ type: PropertyFilterType.Event as const,+ value: contextFromPage.item_id,+ operator: PropertyOperator.Exact,+ },+ ]+ : []),+ ]}+ onNavigate={closeSidePanel}+ iconOnly+ />+ </div>+ <MemberSelect+ value={activeFilters?.user ?? null}+ onChange={(user) =>+ setActiveFilters({+ ...activeFilters,+ user: user?.id ?? undefined,+ })+ }+ />+ </div>+ )+}++function BrowseAllActivityLogs({ onClick }: { onClick: () => void }): JSX.Element {+ return (+ <LemonButton+ size="small"+ type="secondary"+ to={urls.advancedActivityLogs()}+ data-attr="browse-all-activity-logs"+ onClick={onClick}+ >+ Browse all activity logs+ </LemonButton>+ )+}++function NoActivityYet({ activeFilters }: { activeFilters: ActivityFilters | null }): JSX.Element {+ const { setActiveFilters } = useActions(sidePanelActivityLogic)+ const { closeSidePanel } = useActions(sidePanelStateLogic)++ return (+ <div className="flex flex-col items-center gap-2 p-6 text-center border border-dashed rounded">+ <span>No activity yet</span>+ {activeFilters?.user ? (+ <LemonButton+ size="small"+ type="secondary"+ onClick={() =>+ setActiveFilters({+ ...activeFilters,+ user: undefined,+ })+ }+ >+ Clear user filter+ </LemonButton>+ ) : null}+ <div className="flex flex-col items-center justify-center text-xs text-muted-alt">+ <BrowseAllActivityLogs onClick={closeSidePanel} />+ </div>+ </div>+ )+}++function NoPageContext(): JSX.Element {+ const { closeSidePanel } = useActions(sidePanelStateLogic)++ return (+ <div className="flex flex-col items-center justify-center gap-3 p-6 text-center h-full">+ <IconList className="text-5xl text-muted" />+ <div>+ <div className="font-semibold mb-1">Activity is context-aware</div>+ <div className="text-xs text-muted-alt">+ Navigate to a page like dashboards or a specific dashboard to see activity in this panel+ </div>+ </div>+ <div className="flex items-center gap-2 text-xs text-muted-alt">+ <div className="border-t flex-1" />+ <span>or</span>+ <div className="border-t flex-1" />+ </div>+ <BrowseAllActivityLogs onClick={closeSidePanel} />+ </div>+ )+}++function ActivityListFooter({ closeSidePanel }: { closeSidePanel: () => void }): JSX.Element {+ return (+ <div className="flex items-center justify-center pt-1">+ <Link to={urls.advancedActivityLogs()} onClick={closeSidePanel} className="text-muted-alt text-xs">+ or browse all activity logs+ </Link>+ </div>+ )+}++function ActivityList(): JSX.Element {+ const { allActivity, allActivityResponseLoading, allActivityHasNext, activeFilters } =+ useValues(sidePanelActivityLogic)+ const { maybeLoadOlderActivity } = useActions(sidePanelActivityLogic)+ const { closeSidePanel } = useActions(sidePanelStateLogic)++ if (allActivityResponseLoading) {+ return <LemonSkeleton className="h-12 my-2" repeat={10} fade />+ }++ if (!allActivity.length) {+ return <NoActivityYet activeFilters={activeFilters} />+ }++ return (+ <>+ {allActivity.map((logItem, index) => (+ <ActivityLogRow logItem={logItem} key={index} />+ ))}++ <div className="flex items-center justify-center h-10 gap-2 m-4 text-secondary">+ {allActivityResponseLoading ? (+ <>+ <Spinner textColored /> Loading older activity+ </>+ ) : allActivityHasNext ? (+ <LemonButton type="secondary" fullWidth center onClick={() => maybeLoadOlderActivity()}>+ Load more+ </LemonButton>+ ) : (+ 'No more results'+ )}+ </div>+ <ActivityListFooter closeSidePanel={closeSidePanel} />+ </>+ )+}++function ActivityPanelBody({ activeTab }: { activeTab: SidePanelActivityTab }): JSX.Element | null {+ const { contextFromPage } = useValues(sidePanelActivityLogic)++ const hasItemContext = Boolean(contextFromPage?.scope && contextFromPage?.item_id)+ const hasListContext = Boolean(contextFromPage?.scope && !contextFromPage?.item_id)+ const hasAnyContext = hasItemContext || hasListContext++ if (activeTab === SidePanelActivityTab.Metalytics) {+ return <SidePanelActivityMetalytics />+ }+ if (activeTab !== SidePanelActivityTab.All) {+ return null+ }+ return hasAnyContext ? <ActivityList /> : <NoPageContext />+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.scss b/frontend/src/lib/components/ActivityLog/ActivityLog.scssindex b45680b70503..2171a8b71d40 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.scss+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.scss@@ -73,6 +73,7 @@}}+ .ActivityLogRow__summary,.ActivityLogRow__description {ul.bullet-list {padding-left: 20px;diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsxindex 2989ca42bb29..d9be5d42d317 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx@@ -16,6 +16,11 @@ const meta: Meta<ActivityLogProps> = {title: 'Components/ActivityLog',component: ActivityLog,decorators: [+ (Story) => (+ <div className="w-[calc(100vw-2rem)]">+ <Story />+ </div>+ ),mswDecorator({get: {// TODO: setting available featues should be a decorator to make this easydiff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsxdeleted file mode 100644index 2be2cddfedb1..000000000000--- a/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx+++ /dev/null@@ -1,56 +0,0 @@-import '@testing-library/jest-dom'--import { fireEvent, render, screen } from '@testing-library/react'-import { Provider } from 'kea'--import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLog'-import { HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'-import { dayjs } from 'lib/dayjs'--import { initKeaTests } from '~/test/init'--describe('ActivityLogRow', () => {- beforeEach(() => {- initKeaTests()- })-- it('opens an item that has an expanded view on that view', () => {- const logItem: HumanizedActivityLogItem = {- name: 'peter',- description: <>changed the rollout</>,- created_at: dayjs('2022-02-05T16:28:39.594Z'),- expandedView: { label: 'Release conditions', content: <div>the release conditions</div> },- }-- render(- <Provider>- <ActivityLogRow logItem={logItem} />- </Provider>- )- fireEvent.click(screen.getByRole('button'))-- expect(screen.getByText('Release conditions').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')- expect(screen.getByText('the release conditions')).toBeInTheDocument()- })-- test.each([- ['mcp', 'via MCP'],- ['scout:self-driving-dwh', 'via scout self-driving-dwh'],- ['posthog-js/1.234.0', 'via posthog-js/1.234.0'],- ])('names %s as the client behind the change', (client, expected) => {- const logItem: HumanizedActivityLogItem = {- name: 'peter',- description: <>changed the rollout</>,- created_at: dayjs('2022-02-05T16:28:39.594Z'),- client,- }-- render(- <Provider>- <ActivityLogRow logItem={logItem} />- </Provider>- )-- expect(screen.getByText(expected)).toBeInTheDocument()- })-})diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsxindex a0c982f9abdf..a26a0a9619f5 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx@@ -1,32 +1,15 @@import './ActivityLog.scss'-import useSize from '@react-hook/size'-import clsx from 'clsx'import { useValues } from 'kea'-import { router } from 'kea-router'-import { Suspense, useEffect, useRef, useState } from 'react'-import { IconCollapse, IconExpand } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonTabs, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonDivider } from '@posthog/lemon-ui'-import { ActivityClientTag } from 'lib/components/ActivityLog/ActivityClientTag'-import {- ACTIVITY_SEARCH_PARAM,- ActivityLogLogicProps,- activityLogLogic,-} from 'lib/components/ActivityLog/activityLogLogic'-import { AgentAttribution } from 'lib/components/ActivityLog/AgentAttribution'-import { ActivityChange, HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'-import { TZLabel } from 'lib/components/TZLabel'+import { ActivityLogLogicProps, activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'import { FEATURE_FLAGS } from 'lib/constants'-import { IconLink } from 'lib/lemon-ui/icons'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userHasAccess } from 'lib/utils/accessControlUtils'-import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { lazyWithRetry } from 'lib/utils/retryImport'import { userLogic } from 'scenes/userLogic'import { AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'@@ -34,8 +17,7 @@ import { AccessControlLevel, AccessControlResourceType, AvailableFeature } fromimport { AccessDenied } from '../AccessDenied'import { PayGateMini } from '../PayGateMini/PayGateMini'import { ProductIntroduction } from '../ProductIntroduction/ProductIntroduction'--const MonacoDiffEditor = lazyWithRetry(() => import('../MonacoDiffEditor'))+import { ActivityLogRow } from './ActivityLogRow'export type ActivityLogProps = ActivityLogLogicProps & {startingPage?: number@@ -80,207 +62,6 @@ const Loading = (): JSX.Element => {)}-export type ActivityLogTabs = 'details' | 'extended description' | 'diff' | 'raw'--const ActivityLogDiff = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {- const changes = logItem.unprocessed?.detail.changes-- return (- <div className="flex flex-col deprecated-space-y-2 px-2 py-1">- <div className="flex flex-col deprecated-space-y-2">- {changes?.length ? (- changes.map((change, i) => {- return (- <JsonDiffViewer key={i} field={change.field} before={change.before} after={change.after} />- )- })- ) : (- <div className="text-secondary">This item has no changes to compare</div>- )}- </div>- </div>- )-}--interface JsonDiffViewerProps {- field: string | undefined- before: ActivityChange['before']- after: ActivityChange['after']-}--const JsonDiffViewer = ({ field, before, after }: JsonDiffViewerProps): JSX.Element => {- const containerRef = useRef<HTMLDivElement>(null)- const [width] = useSize(containerRef)- return (- <div ref={containerRef} className="flex flex-col space-y-2 w-full">- {field ? <h2>{field}</h2> : null}- <Suspense fallback={<Spinner className="text-2xl mx-auto my-4" />}>- <MonacoDiffEditor- original={JSON.stringify(before, null, 2)}- modified={JSON.stringify(after, null, 2)}- language="json"- width={width}- options={{- renderOverviewRuler: false,- scrollBeyondLastLine: false,- hideUnchangedRegions: {- enabled: true,- contextLineCount: 3,- minimumLineCount: 3,- revealLineCount: 20,- },- diffAlgorithm: 'advanced',- }}- />- </Suspense>- </div>- )-}--export const ActivityLogRow = ({- logItem,- highlighted,-}: {- logItem: HumanizedActivityLogItem- highlighted?: boolean-}): JSX.Element => {- const [isExpanded, setIsExpanded] = useState(false)- const [activeTab, setActiveTab] = useState<ActivityLogTabs>(logItem.expandedView ? 'details' : 'diff')- const rowRef = useRef<HTMLDivElement>(null)-- useEffect(() => {- if (highlighted && rowRef.current) {- rowRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' })- setIsExpanded(true)- }- }, [highlighted])-- const handleCopyLink = (): void => {- if (!logItem.id) {- return- }- const { pathname, search, hash } = router.values.currentLocation- const url = new URL(pathname, window.location.origin)- url.search = search || ''- url.hash = hash || ''- url.searchParams.delete(ACTIVITY_SEARCH_PARAM)- url.searchParams.set(ACTIVITY_SEARCH_PARAM, logItem.id)- void copyToClipboard(url.toString(), 'activity link')- }-- return (- <div- ref={rowRef}- className={clsx(- 'ActivityLogRow-wrapper flex flex-col px-1 py-0.5',- isExpanded && 'border rounded',- highlighted && 'ActivityLogRow--highlighted'- )}- >- <div- className={clsx('ActivityLogRow flex deprecated-space-x-2', logItem.unread && 'ActivityLogRow--unread')}- >- {/* Tooltip merges the trigger props onto its child element, and ProfilePicture drops props- it does not declare, so the trigger must land on the span instead of the avatar. */}- <Tooltip- title={- logItem.emailToReveal ? (- <span className="ph-no-capture">{logItem.emailToReveal}</span>- ) : undefined- }- >- <span className="flex shrink-0">- <ProfilePicture- showName={false}- user={{- first_name: logItem.isSystem || logItem.wasImpersonated ? logItem.name : undefined,- email: logItem.email ?? undefined,- }}- type={logItem.isSystem || logItem.wasImpersonated ? 'system' : 'person'}- size="xl"- />- </span>- </Tooltip>- <div className="ActivityLogRow__details flex-grow">- <div className="ActivityLogRow__description">{logItem.description}</div>- {logItem.extendedDescription && (- <div className="ActivityLogRow__description__extended">{logItem.extendedDescription}</div>- )}- <AgentAttribution logItem={logItem} />- <div className="text-secondary flex items-center gap-1.5">- <TZLabel time={logItem.created_at} />- {logItem.client && <ActivityClientTag client={logItem.client} />}- </div>- </div>- {logItem.id && (- <LemonButton- noPadding={true}- icon={<IconLink />}- onClick={handleCopyLink}- tooltip="Copy link to this activity"- className="ActivityLogRow__copy-link"- />- )}- <LemonButton- noPadding={true}- icon={isExpanded ? <IconCollapse /> : <IconExpand />}- onClick={() => setIsExpanded(!isExpanded)}- active={isExpanded}- />- </div>- {isExpanded && (- <div className="px-1 py-0.5">- <LemonTabs- activeKey={activeTab}- onChange={(key) => setActiveTab(key as ActivityLogTabs)}- tabs={[- logItem.expandedView- ? {- key: 'details',- label: logItem.expandedView.label,- content: logItem.expandedView.content,- }- : false,- logItem.extendedDescription- ? {- key: 'extended description',- label: 'Extended Description',- tooltip:- 'Some activities have a more detailed description that is not shown when collapsed.',- content: (- <div>- {logItem.extendedDescription- ? logItem.extendedDescription- : 'This item has no extended description'}- </div>- ),- }- : false,- {- key: 'diff',- label: 'Diff',- tooltip:- 'Show the diff of the changes made to the item. Each activity item could have more than one change.',- content: <ActivityLogDiff logItem={logItem} />,- },- {- key: 'raw',- label: 'Raw',- tooltip: 'Show the raw data of the activity item.',- content: (- <div>- <pre>{JSON.stringify(logItem.unprocessed, null, 2)}</pre>- </div>- ),- },- ]}- />- </div>- )}- </div>- )-}-export const ActivityLog = ({ scope, id, caption, startingPage = 1 }: ActivityLogProps): JSX.Element | null => {const { user } = useValues(userLogic)const { featureFlags } = useValues(featureFlagLogic)diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogChangeDiff.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogChangeDiff.tsxnew file mode 100644index 000000000000..2396f3b66c3a--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityLogChangeDiff.tsx@@ -0,0 +1,45 @@+import useSize from '@react-hook/size'+import { Suspense, useRef } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import { lazyWithRetry } from 'lib/utils/retryImport'++import { ActivityChange } from './humanizeActivity'++const MonacoDiffEditor = lazyWithRetry(() => import('../MonacoDiffEditor'))++interface ActivityLogChangeDiffProps {+ field: string | undefined+ before: ActivityChange['before']+ after: ActivityChange['after']+}++export const ActivityLogChangeDiff = ({ field, before, after }: ActivityLogChangeDiffProps): JSX.Element => {+ const containerRef = useRef<HTMLDivElement>(null)+ const [width] = useSize(containerRef)+ return (+ <div ref={containerRef} className="flex flex-col space-y-2 w-full">+ {field ? <h2>{field}</h2> : null}+ <Suspense fallback={<Spinner className="text-2xl mx-auto my-4" />}>+ <MonacoDiffEditor+ original={JSON.stringify(before, null, 2)}+ modified={JSON.stringify(after, null, 2)}+ language="json"+ width={width}+ options={{+ renderOverviewRuler: false,+ scrollBeyondLastLine: false,+ hideUnchangedRegions: {+ enabled: true,+ contextLineCount: 3,+ minimumLineCount: 3,+ revealLineCount: 20,+ },+ diffAlgorithm: 'advanced',+ }}+ />+ </Suspense>+ </div>+ )+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogDiff.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogDiff.tsxnew file mode 100644index 000000000000..d7317bcd839b--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityLogDiff.tsx@@ -0,0 +1,27 @@+import { ActivityLogChangeDiff } from './ActivityLogChangeDiff'+import { HumanizedActivityLogItem } from './humanizeActivity'++export const ActivityLogDiff = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {+ const changes = logItem.unprocessed?.detail.changes++ return (+ <div className="flex flex-col deprecated-space-y-2 px-2 py-1">+ <div className="flex flex-col deprecated-space-y-2">+ {changes?.length ? (+ changes.map((change, i) => {+ return (+ <ActivityLogChangeDiff+ key={i}+ field={change.field}+ before={change.before}+ after={change.after}+ />+ )+ })+ ) : (+ <div className="text-secondary">This item has no changes to compare</div>+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsxnew file mode 100644index 000000000000..c9e0dd05057c--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx@@ -0,0 +1,297 @@+import type { Meta, StoryObj } from '@storybook/react'++import { dayjs } from 'lib/dayjs'+import { dashboardActivityDescriber } from 'scenes/dashboard/dashboardActivityDescriber'++import { ActivityScope, InsightShortId } from '~/types'++import { ActivityLogRow } from './ActivityLogRow'+import { describerFor } from './describers'+import { ActivityLogItem, humanize } from './humanizeActivity'++const dashboardEvents: ActivityLogItem[] = [+ {+ id: '019f4c2a-0000-7000-8000-000000000001',+ activity: 'updated',+ scope: ActivityScope.DASHBOARD,+ item_id: '42',+ created_at: '2026-09-14T10:00:00Z',+ user: { first_name: 'Mia', last_name: 'Chen', email: '[email protected]' },+ client: 'mcp',+ detail: {+ name: 'Activation overview',+ merge: null,+ trigger: {+ job_type: 'agent',+ job_id: '019f4c2a-0000-7000-8000-0000000000aa',+ payload: { intent: 'Clarify which onboarding steps the report covers.' },+ },+ changes: [+ {+ type: ActivityScope.DASHBOARD,+ action: 'changed',+ field: 'description',+ before: 'Review setup progress for new workspaces.',+ after: 'Follow a new workspace from its first invitation through its first shared report. Use this dashboard during the onboarding review to spot stalled setup steps, compare completed checklists, and decide which help articles need clearer examples.',+ },+ ],+ },+ },+ {+ id: '019f4c2a-0000-7000-8000-000000000002',+ activity: 'created',+ scope: ActivityScope.DASHBOARD,+ item_id: '42',+ created_at: '2026-09-14T09:55:00Z',+ user: { first_name: 'Mia', last_name: 'Chen', email: '[email protected]' },+ client: 'mcp',+ detail: {+ name: 'Activation overview',+ merge: null,+ changes: null,+ trigger: {+ job_type: 'agent',+ job_id: '019f4c2a-0000-7000-8000-0000000000aa',+ payload: {+ intent: 'Create a dashboard for the onboarding review so the team can find where setup stops and check whether the new help articles make those steps easier to complete.',+ },+ },+ },+ },+]++const logItems = humanize(dashboardEvents, () => dashboardActivityDescriber, true)++const meta: Meta<typeof ActivityLogRow> = {+ title: 'Components/ActivityLogRow',+ component: ActivityLogRow,+ decorators: [+ (Story) => (+ <div className="w-[calc(100vw-2rem)] max-w-3xl">+ <Story />+ </div>+ ),+ ],+ parameters: { mockDate: '2026-09-14T12:00:00Z' },+}+export default meta+type Story = StoryObj<typeof ActivityLogRow>++export const DashboardChanges: Story = {+ render: () => (+ <div className="max-w-3xl space-y-2">+ {logItems.map((logItem) => (+ <ActivityLogRow key={logItem.id} logItem={logItem} />+ ))}+ </div>+ ),+}++export const NarrowDashboardChanges: Story = {+ ...DashboardChanges,+ parameters: { layout: 'padded', viewport: { defaultViewport: 'tablet' } },+ decorators: [+ (Story) => (+ <div className="w-full max-w-lg">+ <Story />+ </div>+ ),+ ],+}++export const HumanChange: Story = {+ args: {+ logItem: humanize(+ [{ ...dashboardEvents[0], client: null, detail: { ...dashboardEvents[0].detail, trigger: null } }],+ () => dashboardActivityDescriber+ )[0],+ },+}++export const LegacyDescription: Story = {+ args: {+ logItem: {+ name: 'Mia Chen',+ // Rows built by humanize() always carry the actor's email; without one the+ // avatar renders the unknown-lettermark placeholder, which the test runner+ // reads as a stuck loader.+ email: '[email protected]',+ description: (+ <>+ <strong>Mia Chen</strong> enabled <strong>onboarding-checklist</strong>+ </>+ ),+ created_at: dayjs('2026-09-14T10:00:00Z'),+ },+ },+}++export const ExpandedView: Story = {+ args: {+ logItem: {+ ...logItems[0],+ extendedDescription: <div>Last 7 days</div>,+ expandedView: { label: 'Filter details', content: <div>Onboarding events from the last 7 days</div> },+ },+ highlighted: true,+ },+}++const productEvents: ActivityLogItem[] = [+ {+ ...dashboardEvents[0],+ scope: ActivityScope.INSIGHT,+ detail: {+ ...dashboardEvents[0].detail,+ name: 'Weekly signups',+ short_id: 'example1' as InsightShortId,+ changes: [+ {+ type: ActivityScope.INSIGHT,+ action: 'changed',+ field: 'description',+ before: 'Count new signups.',+ after: 'Compare completed registrations by signup method each week. Include only people who finish email verification, and use the regional breakdown to check whether the new welcome page helps more people get started.',+ },+ ],+ },+ },+ {+ ...dashboardEvents[0],+ id: '019f4c2a-0000-7000-8000-000000000003',+ scope: ActivityScope.FEATURE_FLAG,+ client: null,+ detail: {+ name: 'welcome-page',+ merge: null,+ trigger: { job_type: 'scheduled_change', job_id: 'example-schedule', payload: {} },+ changes: [+ { type: ActivityScope.FEATURE_FLAG, action: 'changed', field: 'active', before: false, after: true },+ ],+ },+ },+ {+ ...dashboardEvents[0],+ id: '019f4c2a-0000-7000-8000-000000000004',+ scope: ActivityScope.SURVEY,+ client: null,+ detail: {+ name: 'Setup feedback',+ merge: null,+ trigger: null,+ changes: [+ {+ type: ActivityScope.SURVEY,+ action: 'changed',+ field: 'description',+ before: '',+ after: 'Ask new workspace owners which setup step could use a clearer explanation.',+ },+ {+ type: ActivityScope.SURVEY,+ action: 'changed',+ field: 'start_date',+ before: null,+ after: '2026-09-14T10:00:00Z',+ },+ ],+ },+ },+ {+ ...dashboardEvents[0],+ id: '019f4c2a-0000-7000-8000-000000000005',+ scope: ActivityScope.ORGANIZATION_INVITE,+ activity: 'created',+ client: null,+ detail: {+ name: null,+ merge: null,+ trigger: null,+ changes: null,+ context: {+ organization_name: 'Example workspace',+ target_email: '[email protected]',+ level: 'member',+ inviter_user_name: 'Example inviter',+ inviter_user_email: '[email protected]',+ },+ },+ },+ {+ ...dashboardEvents[0],+ id: '019f4c2a-0000-7000-8000-000000000006',+ scope: ActivityScope.BATCH_EXPORT,+ client: null,+ detail: {+ name: 'Daily event archive',+ merge: null,+ trigger: null,+ changes: [+ {+ type: ActivityScope.BATCH_EXPORT,+ action: 'changed',+ field: 'interval',+ before: 'hour',+ after: 'day',+ },+ {+ type: ActivityScope.BATCH_EXPORT,+ action: 'changed',+ field: 'timezone',+ before: 'UTC',+ after: 'Europe/London',+ },+ ],+ },+ },+ {+ ...dashboardEvents[0],+ id: '019f4c2a-0000-7000-8000-000000000007',+ scope: ActivityScope.INSIGHT,+ activity: 'share_login_failed',+ user: undefined,+ client: null,+ detail: {+ name: 'Weekly signups',+ short_id: 'example1' as InsightShortId,+ merge: null,+ trigger: null,+ changes: [+ {+ type: ActivityScope.INSIGHT,+ action: 'changed',+ field: 'share_login',+ after: { client_ip: '192.0.2.1' },+ },+ ],+ },+ },+]++export const AcrossProducts: Story = {+ parameters: {+ testOptions: {+ // Anonymous actors keep their unknown lettermark, which the runner otherwise treats as a loader.+ waitForLoadersToDisappear: false,+ waitForSelector: '.ActivityLogRow-wrapper:nth-child(6) .ActivityLogRow__summary',+ },+ },+ render: () => (+ <div className="max-w-3xl space-y-2">+ {humanize(productEvents, describerFor).map((logItem) => (+ <ActivityLogRow key={logItem.id} logItem={logItem} />+ ))}+ </div>+ ),+}++export const NarrowAcrossProducts: Story = {+ ...AcrossProducts,+ decorators: [+ (Story) => (+ <div className="w-full max-w-lg">+ <Story />+ </div>+ ),+ ],+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogRow.test.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogRow.test.tsxnew file mode 100644index 000000000000..3922cc566d01--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityLogRow.test.tsx@@ -0,0 +1,124 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Provider } from 'kea'++import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLogRow'+import { HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'+import { dayjs } from 'lib/dayjs'++import { initKeaTests } from '~/test/init'++describe('ActivityLogRow', () => {+ afterEach(cleanup)++ beforeEach(() => {+ initKeaTests()+ })++ it.each([false, true])('preserves custom detail tabs with a structured summary: %s', (withSummary) => {+ const logItem: HumanizedActivityLogItem = {+ name: 'peter',+ description: <>changed the rollout</>,+ created_at: dayjs('2022-02-05T16:28:39.594Z'),+ expandedView: { label: 'Release conditions', content: <div>the release conditions</div> },+ summary: withSummary+ ? { actor: <strong>peter</strong>, action: 'Changed the rollout', target: 'onboarding-checklist' }+ : undefined,+ }++ render(+ <Provider>+ <ActivityLogRow logItem={logItem} />+ </Provider>+ )+ fireEvent.click(screen.getByLabelText('Expand activity details'))++ expect(screen.getByText('Release conditions').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByText('the release conditions')).toBeInTheDocument()+ fireEvent.click(screen.getByText('Raw'))+ fireEvent.click(screen.getByLabelText('Collapse activity details'))+ fireEvent.click(screen.getByLabelText('Expand activity details'))+ expect(screen.getByText('Raw').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')+ })++ it('renders the actor once above the action and keeps the value out of bold text', () => {+ const logItem: HumanizedActivityLogItem = {+ description: 'Mia Chen changed the description to Review workspace setup on Activation overview',+ summary: {+ actor: <strong>Mia Chen</strong>,+ action: 'Updated the description',+ target: 'Activation overview',+ preview: 'Review workspace setup',+ },+ created_at: dayjs(),+ client: 'mcp',+ }+ render(+ <Provider>+ <ActivityLogRow logItem={logItem} />+ </Provider>+ )++ const actor = screen.getByText('Mia Chen')+ const source = screen.getByText('via MCP')+ const action = screen.getByText('Updated the description')+ expect(actor.compareDocumentPosition(source) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(source.compareDocumentPosition(action) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(screen.queryByText(logItem.description as string)).not.toBeInTheDocument()+ expect(screen.getByText('Review workspace setup').closest('strong, b')).toBeNull()+ expect(action).toHaveClass('line-clamp-2')++ fireEvent.click(screen.getByLabelText('Expand activity details'))+ expect(screen.getByText('Diff').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByText('This item has no changes to compare')).toBeInTheDocument()+ expect(action).not.toHaveClass('line-clamp-2')+ })++ it('keeps a specialized actor sentence when no structured summary is available', () => {+ render(+ <Provider>+ <ActivityLogRow+ logItem={{+ name: 'A user',+ description: (+ <>+ <strong>Anonymous user</strong> authenticated to the shared dashboard+ </>+ ),+ created_at: dayjs(),+ client: 'mcp',+ }}+ />+ </Provider>+ )++ const actor = screen.getByText('Anonymous user')+ expect(actor).toBeInTheDocument()+ expect(+ actor.compareDocumentPosition(screen.getByText('via MCP')) & Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy()+ expect(screen.queryByText('A user')).not.toBeInTheDocument()+ })++ test.each([+ ['mcp', 'via MCP'],+ ['scout:self-driving-dwh', 'via scout self-driving-dwh'],+ ['posthog-js/1.234.0', 'via posthog-js/1.234.0'],+ ])('names %s as the client behind the change', (client, expected) => {+ const logItem: HumanizedActivityLogItem = {+ name: 'peter',+ description: <>changed the rollout</>,+ created_at: dayjs('2022-02-05T16:28:39.594Z'),+ client,+ }++ render(+ <Provider>+ <ActivityLogRow logItem={logItem} />+ </Provider>+ )++ expect(screen.getByText(expected)).toBeInTheDocument()+ })+})diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsxnew file mode 100644index 000000000000..e214363e6456--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx@@ -0,0 +1,249 @@+import './ActivityLog.scss'++import clsx from 'clsx'+import { router } from 'kea-router'+import { useEffect, useId, useRef, useState } from 'react'++import { IconCollapse, IconExpand } from '@posthog/icons'+import { LemonButton, LemonTabs, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { IconLink } from 'lib/lemon-ui/icons'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { copyToClipboard } from 'lib/utils/copyToClipboard'++import { ActivityClientTag } from './ActivityClientTag'+import { ActivityLogDiff } from './ActivityLogDiff'+import { ACTIVITY_SEARCH_PARAM } from './activityLogLogic'+import { AgentAttribution } from './AgentAttribution'+import { HumanizedActivityLogItem } from './humanizeActivity'++type ActivityLogTabs = 'details' | 'extended description' | 'diff' | 'raw'++// the expanded panel only re-renders on tab change, so keep the tab list apart from the row body+function ExpandedDetails({+ logItem,+ detailsId,+ activeTab,+ onTabChange,+}: {+ logItem: HumanizedActivityLogItem+ detailsId: string+ activeTab: ActivityLogTabs+ onTabChange: (tab: ActivityLogTabs) => void+}): JSX.Element {+ const tabs = [+ logItem.expandedView && {+ key: 'details' as const,+ label: logItem.expandedView.label,+ content: logItem.expandedView.content,+ },+ logItem.extendedDescription && {+ key: 'extended description' as const,+ label: 'Extended Description',+ tooltip: 'Some activities have a more detailed description that is not shown when collapsed.',+ content: <div>{logItem.extendedDescription}</div>,+ },+ {+ key: 'diff' as const,+ label: 'Diff',+ tooltip:+ 'Show the diff of the changes made to the item. Each activity item could have more than one change.',+ content: <ActivityLogDiff logItem={logItem} />,+ },+ {+ key: 'raw' as const,+ label: 'Raw',+ tooltip: 'Show the raw data of the activity item.',+ content: (+ <div>+ <pre>{JSON.stringify(logItem.unprocessed, null, 2)}</pre>+ </div>+ ),+ },+ ].filter(Boolean) as { key: ActivityLogTabs; label: string; content: JSX.Element; tooltip?: string }[]++ return (+ <div id={detailsId} className="min-w-0 px-1 py-0.5 [&_pre]:whitespace-pre-wrap [&_pre]:break-words">+ <LemonTabs activeKey={activeTab} onChange={onTabChange} tabs={tabs} />+ </div>+ )+}++function RowSummary({ logItem, isExpanded }: { logItem: HumanizedActivityLogItem; isExpanded: boolean }): JSX.Element {+ if (!logItem.summary) {+ return <div className="ActivityLogRow__description">{logItem.description}</div>+ }++ return (+ <>+ <div+ className={clsx(+ 'ActivityLogRow__summary font-semibold first-letter:uppercase',+ !isExpanded && 'line-clamp-2 focus-within:line-clamp-none'+ )}+ >+ {logItem.summary.action}+ </div>+ <div className="text-secondary">{logItem.summary.target}</div>+ {logItem.summary.preview && (+ <div className={clsx('mt-2 text-secondary font-normal', !isExpanded && 'line-clamp-2')}>+ {logItem.summary.preview}+ </div>+ )}+ </>+ )+}++function RowBody({ logItem, isExpanded }: { logItem: HumanizedActivityLogItem; isExpanded: boolean }): JSX.Element {+ return (+ <div className="ActivityLogRow__details min-w-0 flex-1">+ {logItem.summary && <RowHeading logItem={logItem} />}+ <RowSummary logItem={logItem} isExpanded={isExpanded} />+ {logItem.extendedDescription && (+ <div className="ActivityLogRow__description__extended">{logItem.extendedDescription}</div>+ )}+ <div className="mt-2 empty:hidden">+ <AgentAttribution logItem={logItem} truncateIntent={!isExpanded} />+ </div>+ {!logItem.summary && <RowHeading logItem={logItem} />}+ </div>+ )+}++function ExpandButton({+ isExpanded,+ onToggle,+ detailsId,+}: {+ isExpanded: boolean+ onToggle: () => void+ detailsId: string+}): JSX.Element {+ return (+ <LemonButton+ noPadding={true}+ icon={isExpanded ? <IconCollapse /> : <IconExpand />}+ onClick={onToggle}+ active={isExpanded}+ aria-label={isExpanded ? 'Collapse activity details' : 'Expand activity details'}+ aria-expanded={isExpanded}+ aria-controls={isExpanded ? detailsId : undefined}+ data-attr="activity-log-expand"+ />+ )+}++function useCopyActivityLink(id?: string): () => void {+ return (): void => {+ if (!id) {+ return+ }+ const { pathname, search, hash } = router.values.currentLocation+ const url = new URL(pathname, window.location.origin)+ url.search = search || ''+ url.hash = hash || ''+ url.searchParams.delete(ACTIVITY_SEARCH_PARAM)+ url.searchParams.set(ACTIVITY_SEARCH_PARAM, id)+ void copyToClipboard(url.toString(), 'activity link')+ }+}++function CopyLinkButton({ onCopy }: { onCopy: () => void }): JSX.Element {+ return (+ <LemonButton+ noPadding={true}+ icon={<IconLink />}+ onClick={onCopy}+ tooltip="Copy link to this activity"+ className="ActivityLogRow__copy-link"+ aria-label="Copy link to this activity"+ />+ )+}++function RowHeading({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {+ return (+ <div className={clsx('flex flex-wrap items-center gap-x-2 gap-y-0.5', logItem.summary ? 'mb-1.5' : 'mt-1.5')}>+ {logItem.summary?.actor}+ {logItem.client && <ActivityClientTag client={logItem.client} />}+ <span className={clsx('text-secondary text-xs', logItem.summary && '@min-[35rem]:ml-auto')}>+ <TZLabel time={logItem.created_at} />+ </span>+ </div>+ )+}++function RowActor({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {+ // Tooltip merges the trigger props onto its child element, and ProfilePicture drops props+ // it does not declare, so the trigger must land on the span instead of the avatar.+ return (+ <Tooltip+ title={logItem.emailToReveal ? <span className="ph-no-capture">{logItem.emailToReveal}</span> : undefined}+ >+ <span className="flex shrink-0 self-start">+ <ProfilePicture+ showName={false}+ user={{+ first_name: logItem.isSystem || logItem.wasImpersonated ? logItem.name : undefined,+ email: logItem.email ?? undefined,+ }}+ type={logItem.isSystem || logItem.wasImpersonated ? 'system' : 'person'}+ size="lg"+ />+ </span>+ </Tooltip>+ )+}++export const ActivityLogRow = ({+ logItem,+ highlighted,+}: {+ logItem: HumanizedActivityLogItem+ highlighted?: boolean+}): JSX.Element => {+ const [isExpanded, setIsExpanded] = useState(false)+ const [activeTab, setActiveTab] = useState<ActivityLogTabs>(logItem.expandedView ? 'details' : 'diff')+ const rowRef = useRef<HTMLDivElement>(null)+ const detailsId = useId()++ useEffect(() => {+ if (highlighted && rowRef.current) {+ rowRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' })+ setIsExpanded(true)+ }+ }, [highlighted])++ const handleCopyLink = useCopyActivityLink(logItem.id)++ return (+ <div+ ref={rowRef}+ className={clsx(+ 'ActivityLogRow-wrapper flex flex-col px-1 py-0.5 @container',+ isExpanded && 'border rounded',+ highlighted && 'ActivityLogRow--highlighted'+ )}+ >+ <div className={clsx('ActivityLogRow flex gap-2 py-3', logItem.unread && 'ActivityLogRow--unread')}>+ <RowActor logItem={logItem} />+ <RowBody logItem={logItem} isExpanded={isExpanded} />+ {logItem.id && <CopyLinkButton onCopy={handleCopyLink} />}+ <ExpandButton+ isExpanded={isExpanded}+ onToggle={() => setIsExpanded(!isExpanded)}+ detailsId={detailsId}+ />+ </div>+ {isExpanded && (+ <ExpandedDetails+ logItem={logItem}+ detailsId={detailsId}+ activeTab={activeTab}+ onTabChange={(key) => setActiveTab(key)}+ />+ )}+ </div>+ )+}diff --git a/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsxindex 4f7542e9d3c3..95aa14225467 100644--- a/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx+++ b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx@@ -1,3 +1,5 @@+import clsx from 'clsx'+import { Tooltip } from '@posthog/lemon-ui'import { Link } from 'lib/lemon-ui/Link'@@ -8,7 +10,13 @@ import { parseAgentAttribution } from './parseAgentAttribution'export const AGENT_INTENT_TOOLTIP = 'Self-reported by the agent in the x-posthog-intent request header'-export function AgentAttribution({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element | null {+export function AgentAttribution({+ logItem,+ truncateIntent = false,+}: {+ logItem: HumanizedActivityLogItem+ truncateIntent?: boolean+}): JSX.Element | null {const attribution = parseAgentAttribution(logItem)if (!attribution) {return null@@ -17,7 +25,7 @@ export function AgentAttribution({ logItem }: { logItem: HumanizedActivityLogItereturn (<div className="text-secondary text-xs flex flex-col gap-0.5" data-attr="activity-log-agent-attribution">{attribution.intent && (- <div>+ <div className={clsx(truncateIntent && 'line-clamp-1')}><Tooltip title={AGENT_INTENT_TOOLTIP}><span className="underline decoration-dotted">Agent intent</span></Tooltip>{' '}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/changeDescriptions.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/changeDescriptions.tsxnew file mode 100644index 000000000000..63979746ca63--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/changeDescriptions.tsx@@ -0,0 +1,66 @@+// Change fragments that several activity describers share, for fields more than+// one scope can change (tags, description).+import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'+import { pluralize } from 'lib/utils/strings'++import { ActivityChange, ChangeMapping, Description } from '../humanizeActivity'++/** Describes added/removed string lists rendered as inline tags, e.g. tags or evaluation contexts. */+export function describeListChanges(+ change: ActivityChange | undefined,+ singular: string,+ plural: string+): ChangeMapping {+ const before = (change?.before as string[] | null) ?? []+ const after = (change?.after as string[] | null) ?? []+ const added = after.filter((t) => before.indexOf(t) === -1)+ const removed = before.filter((t) => after.indexOf(t) === -1)++ const changes: Description[] = []+ if (added.length) {+ changes.push(+ <>+ added {pluralize(added.length, singular, plural, false)}{' '}+ <ObjectTags tags={added} saving={false} style={{ display: 'inline' }} staticOnly />+ </>+ )+ }+ if (removed.length) {+ changes.push(+ <>+ removed {pluralize(removed.length, singular, plural, false)}{' '}+ <ObjectTags tags={removed} saving={false} style={{ display: 'inline' }} staticOnly />+ </>+ )+ }++ return { description: changes }+}++export function describeTagChanges(change?: ActivityChange): ChangeMapping {+ return describeListChanges(change, 'tag', 'tags')+}++export function summarizeDescriptionChange(change?: ActivityChange): Description[] {+ if (!change?.after) {+ return ['cleared the description']+ }+ return [change.before ? 'updated the description' : 'added the description']+}++export function describeDescriptionChange(+ change: ActivityChange | undefined,+ asNotification: boolean | undefined,+ scopeNoun: string+): ChangeMapping {+ return {+ summary: summarizeDescriptionChange(change),+ preview: typeof change?.after === 'string' ? change.after : undefined,+ description: [+ <>+ changed the description {asNotification && ` of the ${scopeNoun} `}to{' '}+ <strong>"{change?.after as string}"</strong>+ </>,+ ],+ }+}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/describeChangeMappings.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/describeChangeMappings.tsxnew file mode 100644index 000000000000..93c1feddb331--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/describeChangeMappings.tsx@@ -0,0 +1,46 @@+import {+ ActivityLogItem,+ ActivityLogUserName,+ ChangeMapping,+ Description,+ ExpandedView,+ ExtendedDescription,+ HumanizedChange,+ activityLogSummary,+} from '../humanizeActivity'+import { SentenceList } from '../SentenceList'++export function describeChangeMappings(+ logItem: ActivityLogItem,+ mappings: ChangeMapping[],+ target: Description,+ defaultSuffix: Description,+ actor: JSX.Element = <ActivityLogUserName logItem={logItem} />+): HumanizedChange | null {+ const descriptions: Description[] = []+ const summaries: Description[] = []+ let preview: string | undefined+ let suffix = defaultSuffix+ let extendedDescription: ExtendedDescription+ let expandedView: ExpandedView | undefined++ for (const change of mappings) {+ descriptions.push(...(change.description ?? []))+ summaries.push(...(change.summary ?? change.description ?? []))+ preview = change.preview ?? preview+ suffix = change.suffix || suffix+ extendedDescription = change.extendedDescription || extendedDescription+ expandedView = change.expandedView || expandedView+ }++ if (!descriptions.length) {+ return null+ }++ return {+ summary: activityLogSummary(logItem, <SentenceList listParts={summaries} />, target, preview, actor),+ description: <SentenceList listParts={descriptions} prefix={actor} suffix={suffix} />,+ extendedDescription,+ expandedView,+ }+}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/describeMappedChanges.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/describeMappedChanges.tsxnew file mode 100644index 000000000000..a8c61dfba85e--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/describeMappedChanges.tsx@@ -0,0 +1,28 @@+import { ActivityChange, ActivityLogItem, ChangeMapping, Description, HumanizedChange } from '../humanizeActivity'+import { describeChangeMappings } from './describeChangeMappings'++export function describeMappedChanges(+ logItem: ActivityLogItem,+ mapping: Record<+ string,+ (change: ActivityChange, logItem: ActivityLogItem, asNotification?: boolean) => ChangeMapping | null+ >,+ target: Description,+ defaultSuffix: Description,+ asNotification?: boolean+): HumanizedChange | null {+ const mappings: ChangeMapping[] = []++ for (const change of logItem.detail.changes || []) {+ if (!change?.field || !Object.hasOwn(mapping, change.field)) {+ continue+ }++ const processedChange = mapping[change.field](change, logItem, asNotification)+ if (processedChange) {+ mappings.push(processedChange)+ }+ }++ return describeChangeMappings(logItem, mappings, target, defaultSuffix)+}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.test.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.test.tsxindex 3cdc7009cf6e..13dbf6d77c94 100644--- a/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.test.tsx+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.test.tsx@@ -57,7 +57,17 @@ describe('instanceSettingActivityDescriber', () => {['cleared', '<redacted>', '<unset>'],['updated', '<unset>', '<unset>'],])('renders a secret %s transition without leaking sentinels', (verb, before, after) => {- const text = describedText(makeLogItem('EMAIL_HOST_PASSWORD', before, after))+ const item = makeLogItem('EMAIL_HOST_PASSWORD', before, after)+ const text = describedText(item)+ const { summary } = instanceSettingActivityDescriber(item)+ expect(+ render(+ <>+ {summary?.action} {summary?.target}+ </>+ ).container.textContent+ ).toMatch(new RegExp(`^${verb} the instance setting EMAIL_HOST_PASSWORD$`, 'i'))+ expect(summary?.preview).toBeUndefined()expect(text).toContain(`${verb} instance setting EMAIL_HOST_PASSWORD`)expect(text).not.toContain('<redacted>')expect(text).not.toContain('<unset>')diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.tsxindex 40a94f18bfcf..31800ae8e006 100644--- a/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.tsx+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/instanceSettingActivityDescriber.tsx@@ -3,6 +3,7 @@ import {ActivityLogUserName,Describer,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -50,6 +51,7 @@ export const instanceSettingActivityDescriber: Describer = (if (transition) {return {+ summary: activityLogSummary(logItem, `${transition} the instance setting`, <code>{key}</code>),description: (<>{actor} {transition} instance setting <code>{key}</code>@@ -62,6 +64,7 @@ export const instanceSettingActivityDescriber: Describer = (// echo the raw sentinel into the audit log.if (isSentinel(change.before) || isSentinel(change.after)) {return {+ summary: activityLogSummary(logItem, 'Updated the instance setting', <code>{key}</code>),description: (<>{actor} updated instance setting <code>{key}</code>@@ -71,6 +74,12 @@ export const instanceSettingActivityDescriber: Describer = (}return {+ summary: activityLogSummary(+ logItem,+ 'Changed the instance setting',+ <code>{key}</code>,+ JSON.stringify(change.after)+ ),description: (<>{actor} changed instance setting <code>{key}</code> from <code>{JSON.stringify(change.before)}</code> to{' '}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/shortIdActivityLink.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/shortIdActivityLink.tsxnew file mode 100644index 000000000000..8a8395f46ad0--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/shortIdActivityLink.tsx@@ -0,0 +1,14 @@+import { Link } from 'lib/lemon-ui/Link'++import { InsightShortId } from '~/types'++import { ActivityLogItem } from '../humanizeActivity'++export function shortIdActivityLink(+ logItem: ActivityLogItem | undefined,+ urlForId: (id: InsightShortId) => string+): JSX.Element {+ const name = logItem?.detail.name+ const shortId = logItem?.detail.short_id+ return shortId ? <Link to={urlForId(shortId)}>{name || 'unknown'}</Link> : name ? <>{name}</> : <i>Untitled</i>+}diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsxindex fcef0bf7a784..3553382ba75c 100644--- a/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'@@ -105,6 +106,7 @@ export function tagActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity == 'created') {return {+ summary: activityLogSummary(logItem, 'Created the tag', nameOrId(logItem?.detail?.name, logItem?.item_id)),description: (<><ActivityLogUserName logItem={logItem} /> created the tag{' '}@@ -116,6 +118,7 @@ export function tagActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the tag', nameOrId(logItem?.detail?.name, logItem?.item_id)),description: (<><ActivityLogUserName logItem={logItem} /> deleted the tag{' '}@@ -127,6 +130,7 @@ export function tagActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity == 'updated') {return {+ summary: activityLogSummary(logItem, 'Updated the tag', nameOrId(logItem?.detail?.name, logItem?.item_id)),description: (<><ActivityLogUserName logItem={logItem} /> updated the tag{' '}@@ -147,6 +151,13 @@ function taggedItemActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Added tag <strong>{tagName}</strong>+ </>,+ relatedObjectDesc+ ),description: (<><ActivityLogUserName logItem={logItem} /> tagged {relatedObjectDesc} with tag{' '}@@ -158,6 +169,13 @@ function taggedItemActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Removed tag <strong>{tagName}</strong>+ </>,+ relatedObjectDesc+ ),description: (<><ActivityLogUserName logItem={logItem} /> removed tag <strong>{tagName}</strong>{' '}diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsxindex 55b07af65024..08a998a878aa 100644--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.feature-flag.test.tsx@@ -70,6 +70,7 @@ describe('the activity log logic', () => {const text = render(<>{actual[0].description}</>).container.textContentexpect(text).toContain(expected)expect(text).not.toContain('rollout')+ expect(render(<>{actual[0].summary?.action}</>).container.textContent?.toLowerCase()).toBe(expected)})it('can handle change of key', async () => {diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.insight.test.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.insight.test.tsxindex f2f42c047f09..845872b9650c 100644--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.insight.test.tsx+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.insight.test.tsx@@ -336,6 +336,9 @@ describe('the activity log logic', () => {expect(render(<>{actual[0].description}</>).container).toHaveTextContent('peter changed the description to "changed" on test insight')+ expect(actual[0].summary?.preview).toBe('changed')+ expect(render(<>{actual[0].summary?.action}</>).container).toHaveTextContent(/^added the description$/)+ expect(render(<>{actual[0].summary?.target}</>).container).toHaveTextContent('test insight')})it('can handle change of favorited', async () => {diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsxindex a277add36c15..87ea6676f9f3 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx@@ -1,9 +1,25 @@import { render } from '@testing-library/react'-import { ActivityLogItem, ActivityLogUserName, userNameForLogItem } from 'lib/components/ActivityLog/humanizeActivity'+import {+ ActivityChange,+ ActivityLogItem,+ ActivityLogUserName,+ Describer,+ Description,+ userNameForLogItem,+} from 'lib/components/ActivityLog/humanizeActivity'+import { cohortActivityDescriber } from 'scenes/cohorts/activityDescriptions'+import { dashboardActivityDescriber } from 'scenes/dashboard/dashboardActivityDescriber'+import { dataManagementActivityDescriber } from 'scenes/data-management/dataManagementDescribers'+import { notebookActivityDescriber } from 'scenes/notebooks/Notebook/notebookActivityDescriber'+import { insightActivityDescriber } from 'scenes/saved-insights/activityDescriptions'+import { surveyActivityDescriber } from 'scenes/surveys/surveyActivityDescriber'+import { teamActivityDescriber } from 'scenes/team-activity/teamActivityDescriber'import { ActivityScope } from '~/types'+import { actionActivityDescriber } from 'products/actions/frontend/actionActivityDescriber'+describe('humanizeActivity', () => {const makeLogItem = (overrides: Partial<ActivityLogItem>): ActivityLogItem => ({activity: 'updated',@@ -13,6 +29,138 @@ describe('humanizeActivity', () => {...overrides,})+ it.each<{+ scope: ActivityScope+ activity?: string+ describer: Describer+ changes: Partial<ActivityChange>[]+ action: string+ description: string+ preview?: string+ }>([+ {+ scope: ActivityScope.NOTEBOOK,+ describer: notebookActivityDescriber,+ changes: [+ { field: 'content', after: {} },+ { field: 'version', after: 2 },+ ],+ action: 'changed content',+ description: 'A user changed content on Example',+ },+ {+ scope: ActivityScope.TEAM,+ describer: teamActivityDescriber,+ changes: [+ { field: 'session_recording_opt_in', after: true },+ { field: 'effective_membership_level', after: 1 },+ ],+ action: 'enabled session recording',+ description: 'A user enabled session recording on Example',+ },+ {+ scope: ActivityScope.EVENT_DEFINITION,+ activity: 'changed',+ describer: dataManagementActivityDescriber,+ changes: [+ { field: 'description', after: '' },+ { field: 'verified', after: true },+ ],+ action: 'cleared the description, and marked as verified',+ description: 'A user changed description to "", and marked Example as verified',+ preview: '',+ },+ {+ scope: ActivityScope.ACTION,+ describer: actionActivityDescriber,+ changes: [+ { field: 'description', before: null, after: 'Match sign-ups' },+ { field: 'name', before: 'Original', after: 'Example' },+ ],+ action: 'added the description, and changed the name from "Original" to "Example"',+ description:+ 'A user added description "Match sign-ups", and changed the name from "Original" to "Example" on action Example',+ preview: 'Match sign-ups',+ },+ ])('preserves the summary and notification for mapped $scope changes', (testCase) => {+ const logItem = makeLogItem({+ scope: testCase.scope,+ activity: testCase.activity ?? 'updated',+ detail: {+ merge: null,+ trigger: null,+ name: 'Example',+ changes: [...testCase.changes, {}, { field: 'unknown_field' }].map((change) => ({+ type: testCase.scope,+ action: 'changed',+ ...change,+ })),+ },+ })+ const result = testCase.describer(logItem, true)+ const text = (value: Description | undefined): string =>+ (render(<>{value}</>).container.textContent || '').replace(/\s+/g, ' ').trim()++ expect(text(result.description)).toBe(testCase.description)+ expect(text(result.summary?.action)).toBe(testCase.action)+ expect(text(result.summary?.target)).toContain('Example')+ expect(result.summary?.preview).toBe(testCase.preview)+ })++ it.each([+ ['name', 'Original', 'Example', 'renamed "Original" to "Example"'],+ ['derived_name', 'Original', 'Example', 'renamed "Original" to "Example"'],+ ['deleted', false, true, 'deleted the insight'],+ ['deleted', true, false, 'restored the insight'],+ ['short_id', 'old-id', 'new-id', 'changed the short id to "new-id"'],+ ['favorited', false, true, 'favorited the insight'],+ ['favorited', true, false, 'unfavorited the insight'],+ ])('uses the same insight %s headline in the main log and side panel', (field, before, after, expected) => {+ const logItem = makeLogItem({+ scope: ActivityScope.INSIGHT,+ detail: {+ merge: null,+ trigger: null,+ name: 'Example',+ changes: [{ type: ActivityScope.INSIGHT, action: 'changed', field: field as string, before, after }],+ },+ })+ for (const asNotification of [false, true]) {+ const { summary } = insightActivityDescriber(logItem, asNotification)++ expect(render(<>{summary?.action}</>).container.textContent).toBe(expected)+ expect(render(<>{summary?.target}</>).container.textContent).toBe('Example')+ }+ })++ it.each<{ scope: ActivityScope; describer: Describer; activity?: string }>([+ { scope: ActivityScope.DASHBOARD, describer: dashboardActivityDescriber },+ { scope: ActivityScope.INSIGHT, describer: insightActivityDescriber },+ { scope: ActivityScope.COHORT, describer: cohortActivityDescriber },+ { scope: ActivityScope.SURVEY, describer: surveyActivityDescriber },+ { scope: ActivityScope.EVENT_DEFINITION, describer: dataManagementActivityDescriber, activity: 'changed' },+ { scope: ActivityScope.ACTION, describer: actionActivityDescriber },+ ])('uses shared description wording for $scope', ({ scope, describer, activity }) => {+ for (const [before, after, expected] of [+ [null, 'Example description', 'added the description'],+ ['Old description', 'Example description', 'updated the description'],+ ['Old description', '', 'cleared the description'],+ ]) {+ const logItem = makeLogItem({+ scope,+ activity: activity ?? 'updated',+ detail: {+ name: 'Example',+ merge: null,+ trigger: null,+ changes: [{ type: scope, action: 'changed', field: 'description', before, after }],+ },+ })++ expect(render(<>{describer(logItem).summary?.action}</>).container.textContent).toBe(expected)+ }+ })+describe('userNameForLogItem', () => {it.each([[diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsxindex 6a63c86de896..9edd5a6ac073 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx@@ -66,17 +66,24 @@ export type Description = string | JSX.Element | nullexport type ExtendedDescription = JSX.Element | undefined// content too large to sit inline with the sentence, shown as its own tab once the row is expandedexport type ExpandedView = { label: string; content: JSX.Element }+export type ActivityLogSummary = {+ actor: JSX.Element+ action: Description+ target: Description+ preview?: string+}export type ChangeMapping = {description: Description[] | null+ summary?: Description[]+ preview?: stringextendedDescription?: ExtendedDescriptionexpandedView?: ExpandedViewsuffix?: string | JSX.Element | null // to override the default suffix}export type HumanizedChange = {- description: Description | nullextendedDescription?: ExtendedDescriptionexpandedView?: ExpandedView-}+} & ({ description: Exclude<Description, null>; summary: ActivityLogSummary } | { description: null; summary?: never })export type HumanizedActivityLogItem = {id?: string@@ -89,6 +96,7 @@ export type HumanizedActivityLogItem = {/** SDK, integration, or scout that triggered this action. Self-reported through the x-posthog-client header, except for a scout, which the server names. */client?: string | nulldescription: Description+ summary?: ActivityLogSummaryextendedDescription?: ExtendedDescription // e.g. an insight's filters summaryexpandedView?: ExpandedView // e.g. a flag's release conditions after the changecreated_at: dayjs.Dayjs@@ -124,7 +132,7 @@ export function humanize(if (!describer) {continue}- const { description, extendedDescription, expandedView } = describer(logItem, asNotification)+ const { description, summary, extendedDescription, expandedView } = describer(logItem, asNotification)if (description !== null) {const impersonatedUserName = logItem.user ? fullName(logItem.user) : undefined@@ -139,6 +147,7 @@ export function humanize(wasImpersonated: logItem.was_impersonated,client: logItem.client,description,+ summary,extendedDescription,expandedView,created_at: dayjs(logItem.created_at),@@ -195,6 +204,16 @@ export function ActivityLogUserName({ logItem }: { logItem: ActivityLogItem }):return <UserNameWithEmail name={userNameForLogItem(logItem)} email={actorEmailForLogItem(logItem)} />}+export function activityLogSummary(+ logItem: ActivityLogItem,+ action: Description,+ target: Description,+ preview?: string,+ actor: JSX.Element = <ActivityLogUserName logItem={logItem} />+): ActivityLogSummary {+ return { actor, action, target, preview }+}+const NO_PLURAL_SCOPES: ActivityScope[] = [ActivityScope.DATA_MANAGEMENT]// Keep in sync with SCOPE_DISPLAY_NAMES in ee/hogai/context/activity_log/context.py@@ -236,6 +255,46 @@ export function humanizeActivity(activity: string): string {return activity.charAt(0).toUpperCase() + activity.slice(1)}+const SIMPLE_ACTIVITY_VERBS: Record<string, string> = {+ deleted: 'deleted',+ created: 'created',+ restored: 'restored',+ updated: 'updated',+}++function describeComment(+ logItem: ActivityLogItem,+ asNotification: boolean,+ resource: string | JSX.Element+): HumanizedChange {+ const description =+ logItem.scope === 'Comment' ? (+ <>+ <ActivityLogUserName logItem={logItem} /> replied to a {humanizeScope(logItem.scope, true)}+ </>+ ) : (+ <>+ <ActivityLogUserName logItem={logItem} /> commented+ {asNotification ? <> on a {humanizeScope(logItem.scope, true)}</> : null}+ </>+ )+ const commentContent = logItem.detail.changes?.[0].after as string | undefined++ return {+ description,+ summary: activityLogSummary(+ logItem,+ logItem.scope === 'Comment' ? 'Replied to a comment' : 'Added a comment',+ resource+ ),+ extendedDescription: commentContent ? (+ <div className="border rounded bg-surface-primary p-4">+ <LemonMarkdown lowKeyHeadings>{commentContent}</LemonMarkdown>+ </div>+ ) : undefined,+ }+}+export function defaultDescriber(logItem: ActivityLogItem,asNotification = false,@@ -243,41 +302,13 @@ export function defaultDescriber(): HumanizedChange {resource = resource || logItem.detail.name || `a ${humanizeScope(logItem.scope, true)}`- if (logItem.activity == 'deleted') {+ const verb = SIMPLE_ACTIVITY_VERBS[logItem.activity]+ if (verb) {return {+ summary: activityLogSummary(logItem, humanizeActivity(verb), resource),description: (<>- <ActivityLogUserName logItem={logItem} /> deleted <b>{resource}</b>- </>- ),- }- }-- if (logItem.activity == 'created') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> created <b>{resource}</b>- </>- ),- }- }-- if (logItem.activity == 'restored') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> restored <b>{resource}</b>- </>- ),- }- }-- if (logItem.activity == 'updated') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> updated <b>{resource}</b>+ <ActivityLogUserName logItem={logItem} /> {verb} <b>{resource}</b></>),}@@ -285,6 +316,7 @@ export function defaultDescriber(if (logItem.activity == 'copied_to_project') {return {+ summary: activityLogSummary(logItem, 'Copied to another project', resource),description: (<><ActivityLogUserName logItem={logItem} /> copied <b>{resource}</b> to another project@@ -294,32 +326,7 @@ export function defaultDescriber(}if (logItem.activity == 'commented') {- let description: JSX.Element | string-- if (logItem.scope === 'Comment') {- description = (- <>- <ActivityLogUserName logItem={logItem} /> replied to a {humanizeScope(logItem.scope, true)}- </>- )- } else {- description = (- <>- <ActivityLogUserName logItem={logItem} /> commented- {asNotification ? <> on a {humanizeScope(logItem.scope, true)}</> : null}- </>- )- }- const commentContent = logItem.detail.changes?.[0].after as string | undefined-- return {- description,- extendedDescription: commentContent ? (- <div className="border rounded bg-surface-primary p-4">- <LemonMarkdown lowKeyHeadings>{commentContent}</LemonMarkdown>- </div>- ) : undefined,- }+ return describeComment(logItem, asNotification, resource)}return { description: null }diff --git a/frontend/src/scenes/authentication/shared/activityDescriptions.tsx b/frontend/src/scenes/authentication/shared/activityDescriptions.tsxindex 6f7ce2ab2bd8..491abcb7f74e 100644--- a/frontend/src/scenes/authentication/shared/activityDescriptions.tsx+++ b/frontend/src/scenes/authentication/shared/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -18,6 +19,12 @@ export function userActivityDescriber(logItem: ActivityLogItem, asNotification?:const reauthSensitiveOps = context?.reauthreturn {+ summary: activityLogSummary(+ logItem,+ reauthSensitiveOps ? 'Re-authenticated for sensitive operations' : 'Logged in',+ 'Account',+ `Using ${loginMethod}`+ ),description: (<><ActivityLogUserName logItem={logItem} /> logged in using {loginMethod}@@ -29,6 +36,7 @@ export function userActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity === 'logged_out') {return {+ summary: activityLogSummary(logItem, 'Logged out', 'Account'),description: (<><ActivityLogUserName logItem={logItem} /> logged outdiff --git a/frontend/src/scenes/billing/activityDescriptions.tsx b/frontend/src/scenes/billing/activityDescriptions.tsxindex c700211a0fc2..a4b1e9c2d900 100644--- a/frontend/src/scenes/billing/activityDescriptions.tsx+++ b/frontend/src/scenes/billing/activityDescriptions.tsx@@ -3,6 +3,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -60,6 +61,12 @@ export function billingActivityDescriber(logItem: ActivityLogItem, asNotificatioconst detail = describeChanges(logItem.detail.changes || [])return {+ summary: activityLogSummary(+ logItem,+ action,+ <Link to={urls.organizationBilling()}>Billing</Link>,+ detail ?? undefined+ ),description: (<><ActivityLogUserName logItem={logItem} /> {action} in{' '}diff --git a/frontend/src/scenes/cohorts/activityDescriptions.tsx b/frontend/src/scenes/cohorts/activityDescriptions.tsxindex 9b46f5d2fd39..b610b9007d72 100644--- a/frontend/src/scenes/cohorts/activityDescriptions.tsx+++ b/frontend/src/scenes/cohorts/activityDescriptions.tsx@@ -1,14 +1,15 @@+import { summarizeDescriptionChange } from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'import {ActivityChange,ActivityLogItem,ActivityLogUserName,ChangeMapping,- Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'-import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -44,12 +45,20 @@ const cohortFieldMapping: Record<string, (change?: ActivityChange) => ChangeMappconst before = (change?.before as string | null | undefined) || ''const after = (change?.after as string | null | undefined) || ''if (!before && after) {- return { description: [<>added a description</>] }+ return {+ description: [<>added a description</>],+ summary: summarizeDescriptionChange(change),+ preview: after,+ }}if (before && !after) {- return { description: [<>cleared the description</>] }+ return { description: [<>cleared the description</>], summary: summarizeDescriptionChange(change) }+ }+ return {+ description: [<>updated the description</>],+ summary: summarizeDescriptionChange(change),+ preview: after,}- return { description: [<>updated the description</>] }},filters: function onFilters(change) {const before = countCohortCriteria(change?.before as CohortType['filters'])@@ -103,6 +112,48 @@ const cohortFieldMapping: Record<string, (change?: ActivityChange) => ChangeMapplast_error_at: () => null,}+function describeCohortField(change: ActivityChange): ChangeMapping | null {+ const handler = cohortFieldMapping[change.field!]+ if (handler) {+ return handler(change)+ }+ // unknown field — surface it generically rather than dumping JSON+ return {+ description: [+ <>+ updated <strong>{change.field}</strong>+ </>,+ ],+ }+}++function describeCohortUpdate(+ logItem: ActivityLogItem,+ asNotification: boolean | undefined,+ cohortLink: string | JSX.Element+): HumanizedChange | null {+ const detailChanges = logItem.detail.changes || []+ // is_static and cohort_type both render as "changed the cohort type to X" — when a flip+ // co-emits both, drop is_static so we don't print the line twice.+ const fieldsPresent = new Set(detailChanges.map((change) => change?.field))+ const mappings = detailChanges.flatMap((change) => {+ if (!change?.field || (change.field === 'is_static' && fieldsPresent.has('cohort_type'))) {+ return []+ }+ const result = describeCohortField(change)+ return result?.description ? [result] : []+ })+ return describeChangeMappings(+ logItem,+ mappings,+ cohortLink,+ <>+ on {asNotification ? 'the cohort ' : ''}+ {cohortLink}+ </>+ )+}+export function cohortActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'Cohort') {console.error('cohort describer received a non-cohort activity')@@ -114,6 +165,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity == 'created') {return {+ summary: activityLogSummary(logItem, 'Created the cohort', cohortLink),description: (<>{actor} created the cohort: {cohortLink}@@ -124,6 +176,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the cohort', cohortLink),description: (<>{actor} deleted the cohort: {cohortLink}@@ -134,6 +187,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity == 'restored') {return {+ summary: activityLogSummary(logItem, 'Restored the cohort', cohortLink),description: (<>{actor} restored the cohort: {cohortLink}@@ -144,6 +198,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity == 'persons_added_manually') {return {+ summary: activityLogSummary(logItem, 'Added people to the cohort', cohortLink),description: (<>{actor} added users to the cohort: {cohortLink}@@ -154,6 +209,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity == 'person_removed_manually') {return {+ summary: activityLogSummary(logItem, 'Removed a person from the cohort', cohortLink),description: (<>{actor} removed a user from the cohort: {cohortLink}@@ -163,50 +219,12 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotification}if (logItem.activity == 'updated') {- const detailChanges = logItem.detail.changes || []- // is_static and cohort_type both render as "changed the cohort type to X" — when a flip- // co-emits both, drop is_static so we don't print the line twice.- const fieldsPresent = new Set(detailChanges.map((c) => c?.field))- const changes: Description[] = []- for (const change of detailChanges) {- if (!change?.field) {- continue- }- if (change.field === 'is_static' && fieldsPresent.has('cohort_type')) {- continue- }- const handler = cohortFieldMapping[change.field]- const result = handler ? handler(change) : null- if (result?.description) {- changes.push(...result.description)- } else if (!handler) {- // unknown field — surface it generically rather than dumping JSON- changes.push(- <>- updated <strong>{change.field}</strong>- </>- )- }+ const changes = describeCohortUpdate(logItem, asNotification, cohortLink)+ if (changes) {+ return changes}-- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={actor}- suffix={- <>- on {asNotification ? 'the cohort ' : ''}- {cohortLink}- </>- }- />- ),- }- }-return {+ summary: activityLogSummary(logItem, 'Updated the cohort', cohortLink),description: (<>{actor} updated the cohort: {cohortLink}diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.test.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.test.tsxnew file mode 100644index 000000000000..c7eff4b6d054--- /dev/null+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.test.tsx@@ -0,0 +1,159 @@+import '@testing-library/jest-dom'++import { cleanup, render } from '@testing-library/react'++import { ActivityLogItem, humanize } from 'lib/components/ActivityLog/humanizeActivity'++import { initKeaTests } from '~/test/init'+import { ActivityScope } from '~/types'++import { dashboardActivityDescriber } from './dashboardActivityDescriber'++describe('dashboardActivityDescriber', () => {+ afterEach(cleanup)++ beforeEach(() => {+ initKeaTests()+ })++ const makeLogItem = (after: string | null): ActivityLogItem => ({+ activity: 'updated',+ scope: ActivityScope.DASHBOARD,+ item_id: '42',+ created_at: '2026-09-14T10:00:00Z',+ user: { first_name: 'Mia', last_name: 'Chen', email: '[email protected]' },+ detail: {+ name: 'Activation overview',+ merge: null,+ trigger: null,+ changes: [{ type: ActivityScope.DASHBOARD, action: 'changed', field: 'description', after }],+ },+ })++ it.each([+ ['Compare completed setup checklists across new workspaces.', 'added the description'],+ ['', 'cleared the description'],+ [null, 'cleared the description'],+ ])('separates the description preview from the action for %p', (after, action) => {+ const logItem = makeLogItem(after)+ const [item] = humanize([logItem], () => dashboardActivityDescriber, true)++ expect(render(<>{item.summary?.action}</>).container).toHaveTextContent(action)+ expect(item.summary?.preview).toBe(after ?? undefined)+ expect(render(<>{item.summary?.target}</>).getByText('Activation overview')).toHaveAttribute(+ 'href',+ expect.stringContaining('/dashboard/42')+ )+ expect(render(<>{item.description}</>).container).toHaveTextContent(+ `Mia Chen changed the description of the dashboard to "${after ?? ''}" on the dashboard Activation overview`+ )+ })++ it('keeps other described changes alongside the preview and omits excluded fields', () => {+ const logItem = makeLogItem('Review workspace setup.')+ logItem.detail.changes!.push(+ { type: ActivityScope.DASHBOARD, action: 'changed', field: 'pinned', before: false, after: true },+ { type: ActivityScope.DASHBOARD, action: 'changed', field: 'last_refresh', after: '2026-09-14' }+ )+ const { summary } = dashboardActivityDescriber(logItem)++ expect(render(<>{summary?.action}</>).container).toHaveTextContent(+ /^added the description, and pinned the dashboard$/+ )+ expect(summary?.preview).toBe('Review workspace setup.')+ })++ it.each(['tiles', 'last_refresh', 'last_accessed_at', undefined])(+ 'keeps the fallback row when an update only changes %p',+ (field) => {+ const logItem = makeLogItem(null)+ logItem.detail.changes = field+ ? [{ type: ActivityScope.DASHBOARD, action: 'changed', field, after: null }]+ : []++ for (const asNotification of [false, true]) {+ const [item] = humanize([logItem], () => dashboardActivityDescriber, asNotification)++ expect(item).toBeTruthy()+ expect(item.summary?.action).toBe('Updated')+ expect(render(<>{item.description}</>).container).toHaveTextContent(+ 'Mia Chen updated Activation overview'+ )+ }+ }+ )++ it.each([false, true])('retains a row after a malformed field with prior changes: %p', (hasPriorChange) => {+ const logItem = makeLogItem(null)+ logItem.detail.changes = [{ type: ActivityScope.DASHBOARD, action: 'changed', field: 'filters', after: null }]+ if (hasPriorChange) {+ logItem.detail.changes.unshift({+ type: ActivityScope.DASHBOARD,+ action: 'changed',+ field: 'pinned',+ after: true,+ })+ }+ const consoleError = jest.spyOn(console, 'error').mockImplementation()+ try {+ const [item] = humanize([logItem], () => dashboardActivityDescriber)++ expect(item).toBeTruthy()+ expect(render(<>{item.summary?.action}</>).container).toHaveTextContent(+ hasPriorChange ? /^pinned the dashboard$/ : /^Updated$/+ )+ expect(render(<>{item.description}</>).container).toHaveTextContent(+ hasPriorChange ? 'Mia Chen pinned Activation overview' : 'Mia Chen updated Activation overview'+ )+ } finally {+ consoleError.mockRestore()+ }+ })++ it.each([false, true])('keeps both dashboard names in the headline with notifications: %p', (asNotification) => {+ const logItem = makeLogItem(null)+ logItem.detail.changes = [+ {+ type: ActivityScope.DASHBOARD,+ action: 'changed',+ field: 'name',+ before: 'Workspace setup',+ after: 'Activation overview',+ },+ ]+ const { summary } = dashboardActivityDescriber(logItem, asNotification)++ expect(render(<>{summary?.action}</>).container).toHaveTextContent(+ /^renamed "Workspace setup" to "Activation overview"$/+ )+ expect(render(<>{summary?.target}</>).getByText('Activation overview')).toHaveAttribute(+ 'href',+ expect.stringContaining('/dashboard/42')+ )+ })++ it.each([+ [{ user: { first_name: '', last_name: '', email: '[email protected]' } }, '[email protected]'],+ [{ is_system: true }, 'PostHog'],+ [{ activity: 'share_login_success' }, 'Anonymous user'],+ [{ activity: 'share_login_failed' }, 'Anonymous user'],+ [{ was_impersonated: true }, 'PostHog Support (as Mia Chen)'],+ ])('preserves actor attribution in summaries for %p', (overrides, name) => {+ const { summary } = dashboardActivityDescriber({ ...makeLogItem('Review setup.'), ...overrides })++ expect(render(<>{summary?.actor}</>).container).toHaveTextContent(name)+ })++ it('provides a creation summary without a value preview', () => {+ const { summary, description } = dashboardActivityDescriber({+ ...makeLogItem(null),+ activity: 'created',+ })++ expect(summary?.action).toBe('Created the dashboard')+ expect(summary?.preview).toBeUndefined()+ expect(render(<>{description}</>).container).toHaveTextContent(+ 'Mia Chen created the dashboard Activation overview'+ )+ })+})diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsxindex fcb1e75630bc..00ba3b23e3e8 100644--- a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx@@ -7,26 +7,30 @@ import {DASHBOARD_TILE_SPACING_LABELS,} from '@posthog/products-dashboards/frontend/dashboardCustomization'+import {+ describeDescriptionChange,+ describeTagChanges,+} from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'import {ActivityChange,ActivityLogItem,+ ActivityLogSummary,ActivityLogUserName,ChangeMapping,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'-import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import {BreakdownSummary,DateRangeSummary,PropertiesSummary,VariablesSummary,} from 'lib/components/Cards/InsightCard/InsightDetails'-import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { isKeyOf } from 'lib/utils/guards'-import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { DashboardType } from '~/types'@@ -41,6 +45,15 @@ function nameAndLink(logItem?: ActivityLogItem): JSX.Element {)}+function dashboardSummary(logItem: ActivityLogItem, action: Description, preview?: string): ActivityLogSummary {+ return {+ actor: <ActivityLogUserName logItem={logItem} />,+ action,+ target: <>Dashboard · {nameAndLink(logItem)}</>,+ preview,+ }+}+const dashboardActionsMapping: Record<keyof DashboardType,(change?: ActivityChange, logItem?: ActivityLogItem, asNotification?: boolean) => ChangeMapping | null@@ -54,6 +67,11 @@ const dashboardActionsMapping: Record<</>,],suffix: <></>,+ summary: [+ <>+ renamed "{change?.before}" to "{change?.after}"+ </>,+ ],}},deleted: function onSoftDelete(change, logItem, asNotification) {@@ -67,44 +85,13 @@ const dashboardActionsMapping: Record<</>,],suffix: <>{nameAndLink(logItem)}</>,+ summary: [`${describeChange} the dashboard`],}},description: function onDescription(change, _, asNotification) {- return {- description: [- <>- changed the description {asNotification && ' of the dashboard '}to{' '}- <strong>"{change?.after as string}"</strong>- </>,- ],- }- },- tags: function onTags(change) {- const tagsBefore = change?.before as string[]- const tagsAfter = change?.after as string[]- const addedTags = tagsAfter.filter((t) => tagsBefore.indexOf(t) === -1)- const removedTags = tagsBefore.filter((t) => tagsAfter.indexOf(t) === -1)-- const changes: Description[] = []- if (addedTags.length) {- changes.push(- <>- added {pluralize(addedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={addedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }- if (removedTags.length) {- changes.push(- <>- removed {pluralize(removedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={removedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }-- return { description: changes }+ return describeDescriptionChange(change, asNotification, 'dashboard')},+ tags: describeTagChanges,pinned: function onPinned(change, logItem, asNotification) {const isFavoriteAfter = detectBoolean(change?.after)return {@@ -116,6 +103,7 @@ const dashboardActionsMapping: Record<</>,],suffix: <>{nameAndLink(logItem)}</>,+ summary: [isFavoriteAfter ? 'pinned the dashboard' : 'unpinned the dashboard'],}},filters: function onChangedFilters(change, logItem) {@@ -189,134 +177,148 @@ const dashboardActionsMapping: Record<},}-export function dashboardActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {- if (logItem.scope != 'Dashboard') {- console.error('dashboard describer received a non-dashboard activity')- return { description: null }+function describeSingleChange(+ change: ActivityChange | undefined,+ logItem: ActivityLogItem,+ asNotification: boolean | undefined+): ChangeMapping | null {+ // dashboard updates have to have a "field" to be described+ if (!change?.field || !isKeyOf(change.field, dashboardActionsMapping)) {+ return null}+ return dashboardActionsMapping[change.field](change, logItem, asNotification)+}- if (logItem.activity == 'created') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> created the dashboard {nameAndLink(logItem)}- </>- ),+function describeUpdatedDashboard(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ const mappings: ChangeMapping[] = []+ try {+ for (const change of logItem.detail.changes || []) {+ const processedChange = describeSingleChange(change, logItem, asNotification)+ if (processedChange) {+ mappings.push(processedChange)+ }}+ } catch (e) {+ console.error('Error while summarizing dashboard update', e)+ posthog.captureException(e)}- if (logItem.activity == 'updated') {- let changes: Description[] = []- let extendedDescription: JSX.Element | undefined- let changeSuffix: Description = (+ return (+ describeChangeMappings(+ logItem,+ mappings,+ <>Dashboard · {nameAndLink(logItem)}</>,<>on {asNotification && ' the dashboard '}{nameAndLink(logItem)}</>- )-- try {- for (const change of logItem.detail.changes || []) {- if (!change?.field || !isKeyOf(change.field, dashboardActionsMapping)) {- continue // dashboard updates have to have a "field" to be described- }-- const actionHandler = dashboardActionsMapping[change.field]- const processedChange = actionHandler(change, logItem, asNotification)- if (processedChange === null) {- continue // // unexpected log from backend is indescribable- }-- const { description, extendedDescription: _extendedDescription, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }- if (_extendedDescription) {- extendedDescription = _extendedDescription- }- if (suffix) {- changeSuffix = suffix- }- }- } catch (e) {- console.error('Error while summarizing dashboard update', e)- posthog.captureException(e)- }+ ) ?? defaultDescriber(logItem, asNotification, nameAndLink(logItem))+ )+}- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- extendedDescription,- }- }- }+function describeShareLogin(logItem: ActivityLogItem, succeeded: boolean): HumanizedChange {+ const afterData = logItem.detail.changes?.[0]?.after as any+ const clientIp = afterData?.client_ip || 'unknown IP'- if (logItem.activity === 'sharing enabled') {+ if (succeeded) {+ const passwordNote = afterData?.password_note || 'unknown password'return {+ summary: activityLogSummary(+ logItem,+ 'Authenticated to the shared dashboard',+ nameAndLink(logItem),+ `From ${clientIp}, using password ${passwordNote}`,+ <strong>Anonymous user</strong>+ ),description: (<>- <ActivityLogUserName logItem={logItem} /> shared {asNotification ? 'your' : 'the'} dashboard{' '}- {nameAndLink(logItem)}+ <strong>Anonymous user</strong> successfully authenticated to shared dashboard{' '}+ <b>{nameAndLink(logItem)}</b> from {clientIp} using password <strong>{passwordNote}</strong></>),}}+ return {+ summary: activityLogSummary(+ logItem,+ 'Failed to authenticate to the shared dashboard',+ nameAndLink(logItem),+ `From ${clientIp}`,+ <strong>Anonymous user</strong>+ ),+ description: (+ <>+ <strong>Anonymous user</strong> failed to authenticate to shared dashboard <b>{nameAndLink(logItem)}</b>{' '}+ from {clientIp}+ </>+ ),+ }+}- if (logItem.activity === 'sharing disabled') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> deleted shared link for {asNotification ? 'your' : 'the'}{' '}- dashboard {nameAndLink(logItem)}- </>- ),- }+const SHARING_SUMMARIES: Record<string, string> = {+ 'sharing enabled': 'Shared the dashboard',+ 'sharing disabled': 'Deleted the shared link',+ 'access token refreshed': 'Refreshed the shared link',+}++const SHARING_SENTENCES: Record<string, string> = {+ 'sharing enabled': 'shared',+ 'sharing disabled': 'deleted shared link for',+ 'access token refreshed': 'refreshed the shared link for',+}++const dashboardActivitySentences: Record<+ string,+ (logItem: ActivityLogItem, asNotification?: boolean) => HumanizedChange+> = {+ created: (logItem) => ({+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> created the dashboard {nameAndLink(logItem)}+ </>+ ),+ summary: dashboardSummary(logItem, 'Created the dashboard'),+ }),+ 'sharing enabled': describeSharingActivity,+ 'sharing disabled': describeSharingActivity,+ 'access token refreshed': describeSharingActivity,+}++function describeSharingActivity(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ const sentence = SHARING_SENTENCES[logItem.activity]+ const summary = SHARING_SUMMARIES[logItem.activity]+ return {+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> {sentence} {asNotification ? 'your' : 'the'} dashboard{' '}+ {nameAndLink(logItem)}+ </>+ ),+ summary: dashboardSummary(logItem, summary),}+}- if (logItem.activity === 'access token refreshed') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> refreshed the shared link for{' '}- {asNotification ? 'your' : 'the'} dashboard {nameAndLink(logItem)}- </>- ),- }+export function dashboardActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ if (logItem.scope != 'Dashboard') {+ console.error('dashboard describer received a non-dashboard activity')+ return { description: null }}- if (logItem.activity === 'share_login_success') {- const afterData = logItem.detail.changes?.[0]?.after as any- const clientIp = afterData?.client_ip || 'unknown IP'- const passwordNote = afterData?.password_note || 'unknown password'+ if (logItem.activity == 'updated') {+ return describeUpdatedDashboard(logItem, asNotification)+ }- return {- description: (- <>- <strong>Anonymous user</strong> successfully authenticated to shared dashboard{' '}- <b>{nameAndLink(logItem)}</b> from {clientIp} using password <strong>{passwordNote}</strong>- </>- ),- }+ const sentenceDescriber = dashboardActivitySentences[logItem.activity]+ if (sentenceDescriber) {+ return sentenceDescriber(logItem, asNotification)}- if (logItem.activity === 'share_login_failed') {- const afterData = logItem.detail.changes?.[0]?.after as any- const clientIp = afterData?.client_ip || 'unknown IP'+ if (logItem.activity === 'share_login_success') {+ return describeShareLogin(logItem, true)+ }- return {- description: (- <>- <strong>Anonymous user</strong> failed to authenticate to shared dashboard{' '}- <b>{nameAndLink(logItem)}</b> from {clientIp}- </>- ),- }+ if (logItem.activity === 'share_login_failed') {+ return describeShareLogin(logItem, false)}return defaultDescriber(logItem, asNotification, nameAndLink(logItem))diff --git a/frontend/src/scenes/data-management/dataManagementDescribers.tsx b/frontend/src/scenes/data-management/dataManagementDescribers.tsxindex d8588a018668..1bcf8a236e35 100644--- a/frontend/src/scenes/data-management/dataManagementDescribers.tsx+++ b/frontend/src/scenes/data-management/dataManagementDescribers.tsx@@ -1,3 +1,5 @@+import { summarizeDescriptionChange } from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeMappedChanges } from 'lib/components/ActivityLog/activityDescriptions/describeMappedChanges'import {ActivityChange,ActivityLogItem,@@ -5,10 +7,10 @@ import {ChangeMapping,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'-import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { IconVerifiedEvent } from 'lib/lemon-ui/icons'import { Link } from 'lib/lemon-ui/Link'@@ -23,6 +25,8 @@ const dataManagementActionsMapping: Record<> = {description: (change) => {return {+ summary: summarizeDescriptionChange(change),+ preview: typeof change?.after === 'string' ? change.after : undefined,description: [<>changed description to <strong>"{change?.after as string}"</strong>@@ -59,6 +63,11 @@ const dataManagementActionsMapping: Record<verified: (change, logItem) => {const verified = detectBoolean(change?.after)return {+ summary: [+ <>+ marked as {verified ? 'verified' : 'unverified'} {verified && <IconVerifiedEvent />}+ </>,+ ],description: [<>marked {nameAndLink(logItem)} as <strong>{verified ? 'verified' : 'unverified'}</strong>{' '}@@ -99,49 +108,30 @@ export function dataManagementActivityDescriber(logItem: ActivityLogItem, asNoti}if (logItem.activity == 'changed') {- let changes: Description[] = []- let changeSuffix: Description = (+ const changes = describeMappedChanges(+ logItem,+ dataManagementActionsMapping,+ <>+ <DescribeType logItem={logItem} />: {nameAndLink(logItem)}+ </>,<>on <DescribeType logItem={logItem} /> {nameAndLink(logItem)}</>)-- for (const change of logItem.detail.changes || []) {- if (!change?.field || !dataManagementActionsMapping[change.field]) {- continue // updates have to have a "field" to be described- }-- const actionHandler = dataManagementActionsMapping[change.field]- const processedChange = actionHandler(change, logItem)- if (processedChange === null) {- continue // // unexpected log from backend is indescribable- }-- const { description, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }-- if (suffix) {- changeSuffix = suffix- }- }-- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- }+ if (changes) {+ return changes}}if (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Deleted the <DescribeType logItem={logItem} />+ </>,+ nameAndLink(logItem)+ ),description: (<><ActivityLogUserName logItem={logItem} /> deleted <DescribeType logItem={logItem} />{' '}diff --git a/frontend/src/scenes/data-pipelines/batch-exports/activityDescriptions.tsx b/frontend/src/scenes/data-pipelines/batch-exports/activityDescriptions.tsxindex 7f62315bf76b..de9006c80e32 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/activityDescriptions.tsx+++ b/frontend/src/scenes/data-pipelines/batch-exports/activityDescriptions.tsx@@ -3,8 +3,10 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -244,6 +246,7 @@ export function batchExportActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'created') {return {+ summary: activityLogSummary(logItem, 'Created the batch export', exportName),description: (<><ActivityLogUserName logItem={logItem} /> created batch export {exportName}@@ -255,6 +258,7 @@ export function batchExportActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.detail?.changes?.some((change) => change.field === 'deleted')) {const displayName = logItem.detail.name || '(unnamed export)'return {+ summary: activityLogSummary(logItem, 'Deleted the batch export', displayName),description: (<><ActivityLogUserName logItem={logItem} /> deleted batch export <strong>{displayName}</strong>@@ -303,6 +307,7 @@ export function batchExportActivityDescriber(logItem: ActivityLogItem, asNotificif (changes.length === 0) {return {+ summary: activityLogSummary(logItem, 'Updated the batch export', exportName),description: (<><ActivityLogUserName logItem={logItem} /> updated batch export {exportName}@@ -312,6 +317,11 @@ export function batchExportActivityDescriber(logItem: ActivityLogItem, asNotific}return {+ summary: activityLogSummary(+ logItem,+ <SentenceList listParts={changes.map((change) => change.inlist)} />,+ exportName+ ),description:changes.length === 1 ? (<>diff --git a/frontend/src/scenes/data-pipelines/batch-imports/activityDescriptions.tsx b/frontend/src/scenes/data-pipelines/batch-imports/activityDescriptions.tsxindex 1a61abf30d28..2106ba1eca36 100644--- a/frontend/src/scenes/data-pipelines/batch-imports/activityDescriptions.tsx+++ b/frontend/src/scenes/data-pipelines/batch-imports/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -28,6 +29,7 @@ const getDisplayName = (logItem: ActivityLogItem): string => {export function batchImportActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.activity == 'created') {return {+ summary: activityLogSummary(logItem, 'Created the import', getDisplayName(logItem)),description: (<><ActivityLogUserName logItem={logItem} /> created <strong>{getDisplayName(logItem)}</strong>@@ -38,6 +40,7 @@ export function batchImportActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the import', getDisplayName(logItem)),description: (<><ActivityLogUserName logItem={logItem} /> deleted <strong>{getDisplayName(logItem)}</strong>@@ -48,6 +51,7 @@ export function batchImportActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'updated') {return {+ summary: activityLogSummary(logItem, 'Updated the import', getDisplayName(logItem)),description: (<><ActivityLogUserName logItem={logItem} /> updated <strong>{getDisplayName(logItem)}</strong>diff --git a/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx b/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsxindex b16c37628de4..1c5b59c63c65 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx@@ -3,6 +3,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'@@ -159,6 +160,83 @@ function describeChange(change: ActivityChange): JSX.Element | null {return <>changed {humanizeField(change.field)}</>}+function describeSavedQueryUpdate(logItem: ActivityLogItem, user: JSX.Element, viewName: JSX.Element): HumanizedChange {+ const changes = logItem.detail?.changes ?? []+ const parts = changes.map(describeChange).filter((p): p is JSX.Element => p !== null)+ return {+ summary: activityLogSummary(+ logItem,+ <SentenceList listParts={parts.length ? parts : ['Updated the view']} />,+ viewName+ ),+ description: (+ <SentenceList+ listParts={parts.length > 0 ? parts : [<>updated the view</>]}+ prefix={user}+ suffix={<>on {viewName}</>}+ />+ ),+ }+}++function describeMaterializationEnabled(+ logItem: ActivityLogItem,+ user: JSX.Element,+ viewName: JSX.Element+): HumanizedChange {+ const changes = logItem.detail?.changes ?? []+ const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')+ const parts: JSX.Element[] = [<>enabled materialization for {viewName}</>]+ if (freqChange) {+ const after = humanizeInterval(freqChange.after as string | null)+ parts.push(+ <>+ with sync frequency <strong>{after}</strong>+ </>+ )+ }+ return {+ summary: activityLogSummary(+ logItem,+ 'Enabled materialization',+ viewName,+ freqChange ? `Sync frequency: ${humanizeInterval(freqChange.after as string | null)}` : undefined+ ),+ description: <SentenceList listParts={parts} prefix={user} />,+ }+}++function describeSyncFrequencyReset(+ logItem: ActivityLogItem,+ user: JSX.Element,+ viewName: JSX.Element+): HumanizedChange {+ const changes = logItem.detail?.changes ?? []+ const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')+ const after = freqChange ? humanizeInterval(freqChange.after as string | null) : 'default'+ return {+ summary: activityLogSummary(logItem, <>Reset sync frequency to {after}</>, viewName),+ description: (+ <SentenceList+ listParts={[+ <>+ auto-reset sync frequency to <strong>{after}</strong> for {viewName}+ </>,+ ]}+ prefix={user}+ />+ ),+ }+}++const SAVED_QUERY_EVENTS = new Map([+ ['created', { action: 'Created the view', description: 'created' }],+ ['deleted', { action: 'Deleted the view', description: 'deleted' }],+ ['sync_triggered', { action: 'Triggered an ad-hoc sync', description: 'triggered an ad-hoc sync on' }],+ ['sync_cancelled', { action: 'Canceled a running sync', description: 'cancelled a running sync on' }],+ ['materialization_disabled', { action: 'Disabled materialization', description: 'disabled materialization for' }],+])+export function dataWarehouseSavedQueryActivityDescriber(logItem: ActivityLogItem,asNotification?: boolean@@ -170,82 +248,33 @@ export function dataWarehouseSavedQueryActivityDescriber(const user = <ActivityLogUserName logItem={logItem} />const viewName = logItem.detail?.name ? <strong>{logItem.detail.name}</strong> : <i>a view</i>-- if (logItem.activity === 'created') {- return {- description: <SentenceList listParts={[<>created {viewName}</>]} prefix={user} />,- }- }-- if (logItem.activity === 'updated') {- const changes = logItem.detail?.changes ?? []- const parts = changes.map(describeChange).filter((p): p is JSX.Element => p !== null)+ const event = SAVED_QUERY_EVENTS.get(logItem.activity)+ if (event) {return {+ summary: activityLogSummary(logItem, event.action, viewName),description: (<SentenceList- listParts={parts.length > 0 ? parts : [<>updated the view</>]}+ listParts={[+ <>+ {event.description} {viewName}+ </>,+ ]}prefix={user}- suffix={<>on {viewName}</>}/>),}}- if (logItem.activity === 'sync_triggered') {- return {- description: <SentenceList listParts={[<>triggered an ad-hoc sync on {viewName}</>]} prefix={user} />,- }- }-- if (logItem.activity === 'sync_cancelled') {- return {- description: <SentenceList listParts={[<>cancelled a running sync on {viewName}</>]} prefix={user} />,- }+ if (logItem.activity === 'updated') {+ return describeSavedQueryUpdate(logItem, user, viewName)}if (logItem.activity === 'materialization_enabled') {- const changes = logItem.detail?.changes ?? []- const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')- const parts: JSX.Element[] = [<>enabled materialization for {viewName}</>]- if (freqChange) {- const after = humanizeInterval(freqChange.after as string | null)- parts.push(- <>- with sync frequency <strong>{after}</strong>- </>- )- }- return { description: <SentenceList listParts={parts} prefix={user} /> }- }-- if (logItem.activity === 'materialization_disabled') {- return {- description: <SentenceList listParts={[<>disabled materialization for {viewName}</>]} prefix={user} />,- }+ return describeMaterializationEnabled(logItem, user, viewName)}if (logItem.activity === 'sync_frequency_reset') {- const changes = logItem.detail?.changes ?? []- const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')- const after = freqChange ? humanizeInterval(freqChange.after as string | null) : 'default'- return {- description: (- <SentenceList- listParts={[- <>- auto-reset sync frequency to <strong>{after}</strong> for {viewName}- </>,- ]}- prefix={user}- />- ),- }- }-- if (logItem.activity === 'deleted') {- return {- description: <SentenceList listParts={[<>deleted {viewName}</>]} prefix={user} />,- }+ return describeSyncFrequencyReset(logItem, user, viewName)}return defaultDescriber(logItem, asNotification, viewName)diff --git a/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx b/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsxindex a9055f5e6344..e6ead855df1b 100644--- a/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx+++ b/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx@@ -374,6 +374,11 @@ describe('experimentActivityDescriber', () => {const text = textOf(result)expect(text).toContain('stopped experiment')expect(text).toContain('completed it as')+ const summaryText = render(<>{result.summary?.action}</>).container.textContent || ''+ expect(summaryText).toContain('stopped experiment')+ expect(summaryText).toContain('completed it as')+ expect(summaryText).not.toMatch(/ (for|to|from|on)$/)+ expect(render(<>{result.summary?.target}</>).container.querySelector('a')).not.toBeNull()expect(text).not.toContain('status')expect(text).not.toContain('conclusion comment')const extended = render(<>{result.extendedDescription}</>).container.textContentdiff --git a/frontend/src/scenes/experiments/experimentActivityDescriber.tsx b/frontend/src/scenes/experiments/experimentActivityDescriber.tsxindex 512ee9dfe0b6..eb4549c71486 100644--- a/frontend/src/scenes/experiments/experimentActivityDescriber.tsx+++ b/frontend/src/scenes/experiments/experimentActivityDescriber.tsx@@ -1,6 +1,13 @@import { match } from 'ts-pattern'-import { ActivityLogItem, ActivityLogUserName, HumanizedChange } from 'lib/components/ActivityLog/humanizeActivity'+import {+ ActivityChange,+ ActivityLogDetail,+ ActivityLogItem,+ ActivityLogUserName,+ HumanizedChange,+ activityLogSummary,+} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { ExperimentStatus } from '~/types'@@ -92,6 +99,87 @@ const appendPreposition = (item: string | JSX.Element): string | JSX.Element =>)}+function getConclusionComment(+ changes: ActivityChange[],+ isExperiment: boolean+): {+ conclusionComment?: string+ conclusionCommentRemoved: boolean+} {+ const conclusionCommentChange = isExperiment+ ? changes.find((change) => change.field === 'conclusion_comment')+ : undefined+ const conclusionComment =+ typeof conclusionCommentChange?.after === 'string' && conclusionCommentChange.after.trim()+ ? conclusionCommentChange.after+ : undefined+ const conclusionCommentRemoved =+ !conclusionComment &&+ typeof conclusionCommentChange?.before === 'string' &&+ Boolean(conclusionCommentChange.before.trim())++ return { conclusionComment, conclusionCommentRemoved }+}++function getExperimentUpdateParts(updateLogDetail: ActivityLogDetail, isExperiment: boolean): (string | JSX.Element)[] {+ const changes = updateLogDetail.changes || []+ let listParts: (string | JSX.Element)[]+ if (changes.length === 0) {+ listParts = ['updated']+ } else if (isExperiment) {+ // Flatten each change into one or more parts. The preposition is appended+ // exactly once below — to the final part — so the SentenceList reads+ // "changed A, changed B, and changed C for Experiment Name" instead of+ // duplicating prepositions inside each clause.+ listParts = changes.flatMap((change) => humanizeExperimentChange(getExperimentChangeDescription(change)))+ } else {+ listParts = changes+ .map((change) =>+ match(updateLogDetail.type)+ .with('shared_metric', () => getSharedMetricChangeDescription(change))+ .with('holdout', () => getHoldoutChangeDescription(change))+ .otherwise(() => null)+ )+ .filter((part): part is string | JSX.Element => part !== null)+ }++ return listParts+}++function describeExperimentUpdate(+ logItem: ActivityLogItem,+ listParts: (string | JSX.Element)[],+ hasExperimentChanges: boolean,+ conclusionComment: string | undefined+): HumanizedChange {+ const { detail: updateLogDetail, item_id } = logItem+ const summaryParts = [...listParts]++ if (hasExperimentChanges && listParts.length > 0) {+ const lastIndex = listParts.length - 1+ listParts[lastIndex] = appendPreposition(listParts[lastIndex])+ }++ const suffix = match(updateLogDetail.type)+ .with('shared_metric', () => nameOrLinkToSharedMetric(updateLogDetail.name, item_id))+ .with('holdout', () => <strong>{updateLogDetail.name}</strong>)+ .otherwise(() => nameOrLinkToExperiment(updateLogDetail.name, item_id))++ return {+ summary: activityLogSummary(+ logItem,+ <SentenceList listParts={summaryParts.length ? summaryParts : ['Updated']} />,+ suffix+ ),+ description: (+ <SentenceList prefix={<ActivityLogUserName logItem={logItem} />} listParts={listParts} suffix={suffix} />+ ),+ extendedDescription: conclusionComment ? (+ <blockquote className="border-l-2 pl-2 text-secondary">{conclusionComment}</blockquote>+ ) : undefined,+ }+}+export const experimentActivityDescriber = (logItem: ActivityLogItem): HumanizedChange => {/*** Item types: `shared_metric`, `saved_metric_config`, `holdout`, or the `null` default for experiments.@@ -101,6 +189,13 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanizedreturn match(logItem).with({ activity: 'created', detail: { type: 'saved_metric_config' } }, () => {return {+ summary: activityLogSummary(+ logItem,+ 'Added a shared metric',+ <>+ {logItem.detail.name} to {nameOrLinkToExperiment('experiment', logItem.item_id)}+ </>+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -117,6 +212,13 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'updated', detail: { type: 'saved_metric_config' } }, () => {return {+ summary: activityLogSummary(+ logItem,+ 'Updated the shared metric configuration',+ <>+ {logItem.detail.name} on {nameOrLinkToExperiment('experiment', logItem.item_id)}+ </>+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -133,6 +235,7 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'created', detail: { type: 'holdout' } }, () => {return {+ summary: activityLogSummary(logItem, 'Created an experiment holdout', logItem.detail.name || 'Holdout'),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -147,6 +250,20 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized* we handle both experiments and shared metrics creation here.*/return {+ summary: activityLogSummary(+ logItem,+ isSharedMetric ? (+ 'Created a shared metric'+ ) : (+ <>+ Created a <StatusTag status={ExperimentStatus.Draft} /> experiment+ </>+ ),+ (isSharedMetric ? nameOrLinkToSharedMetric : nameOrLinkToExperiment)(+ logItem.detail.name,+ logItem.item_id+ )+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -173,6 +290,7 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized* from false to true, the experiment has been deleted.*/return {+ summary: activityLogSummary(logItem, 'Deleted the experiment', logItem.detail.name || 'Experiment'),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -184,6 +302,13 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'deleted', detail: { type: 'saved_metric_config' } }, () => {return {+ summary: activityLogSummary(+ logItem,+ 'Removed the shared metric',+ <>+ {logItem.detail.name} from {nameOrLinkToExperiment('experiment', logItem.item_id)}+ </>+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -203,6 +328,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized* Shared metrics are not soft deleted.*/return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the shared metric',+ logItem.detail.name || 'Shared metric'+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -217,6 +347,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized* Holdouts are not soft deleted.*/return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the experiment holdout',+ logItem.detail.name || 'Holdout'+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -228,6 +363,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'deleted' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the experiment',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -239,6 +379,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'restored' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(+ logItem,+ 'Restored the experiment',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -250,6 +395,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'paused' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(+ logItem,+ 'Paused the experiment',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -261,6 +411,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'resumed' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(+ logItem,+ 'Resumed the experiment',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -272,6 +427,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'reset' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(+ logItem,+ 'Reset the experiment',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -284,6 +444,11 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized.with({ activity: 'variant_shipped' }, ({ item_id, detail }) => {const variantKey = detail.changes?.find((change) => change.field === 'shipped_variant')?.afterreturn {+ summary: activityLogSummary(+ logItem,+ typeof variantKey === 'string' ? <>Shipped variant {variantKey}</> : 'Shipped a variant',+ nameOrLinkToExperiment(detail.name, item_id)+ ),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -303,6 +468,7 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'exposure_frozen' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(logItem, 'Froze exposure', nameOrLinkToExperiment(detail.name, item_id)),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -314,6 +480,7 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}).with({ activity: 'exposure_unfrozen' }, ({ item_id, detail }) => {return {+ summary: activityLogSummary(logItem, 'Unfroze exposure', nameOrLinkToExperiment(detail.name, item_id)),description: (<SentenceListprefix={<ActivityLogUserName logItem={logItem} />}@@ -323,52 +490,21 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized),}})- .with({ activity: 'updated' }, ({ item_id, detail: updateLogDetail }) => {+ .with({ activity: 'updated' }, ({ detail: updateLogDetail }) => {/*** This is the catch all for all experiment updates*/const changes = updateLogDetail.changes || []- const isExperiment =- updateLogDetail.type !== 'shared_metric' &&- updateLogDetail.type !== 'holdout' &&- updateLogDetail.type !== 'saved_metric_config'+ const isExperiment = !['shared_metric', 'holdout', 'saved_metric_config'].includes(+ updateLogDetail.type ?? ''+ )- const conclusionCommentChange = isExperiment- ? changes.find((change) => change.field === 'conclusion_comment')- : undefined- const conclusionComment =- typeof conclusionCommentChange?.after === 'string' && conclusionCommentChange.after.trim()- ? conclusionCommentChange.after- : undefined- const conclusionCommentRemoved =- !conclusionComment &&- typeof conclusionCommentChange?.before === 'string' &&- Boolean(conclusionCommentChange.before.trim())+ const { conclusionComment, conclusionCommentRemoved } = getConclusionComment(changes, isExperiment)+ let listParts = getExperimentUpdateParts(updateLogDetail, isExperiment)+ const hasExperimentChanges = isExperiment && changes.length > 0- let listParts: (string | JSX.Element)[]- if (changes.length === 0) {- listParts = ['updated']- } else if (isExperiment) {- // Flatten each change into one or more parts. The preposition is appended- // exactly once below — to the final part — so the SentenceList reads- // "changed A, changed B, and changed C for Experiment Name" instead of- // duplicating prepositions inside each clause.- listParts = changes.flatMap((change) =>- humanizeExperimentChange(getExperimentChangeDescription(change))- )- } else {- listParts = changes- .map((change) =>- match(updateLogDetail.type)- .with('shared_metric', () => getSharedMetricChangeDescription(change))- .with('holdout', () => getHoldoutChangeDescription(change))- .otherwise(() => null)- )- .filter((part): part is string | JSX.Element => part !== null)- }-- if (isExperiment && changes.length > 0 && listParts.length === 0) {+ if (hasExperimentChanges && listParts.length === 0) {if (conclusionComment) {// A comment-only edit still gets a row; the comment renders below it.listParts = ['changed the conclusion']@@ -380,31 +516,15 @@ export const experimentActivityDescriber = (logItem: ActivityLogItem): Humanized}}- if (isExperiment && changes.length > 0 && listParts.length > 0) {- const lastIndex = listParts.length - 1- listParts[lastIndex] = appendPreposition(listParts[lastIndex])- }-- const suffix = match(updateLogDetail.type)- .with('shared_metric', () => nameOrLinkToSharedMetric(updateLogDetail.name, item_id))- .with('holdout', () => <strong>{updateLogDetail.name}</strong>)- .otherwise(() => nameOrLinkToExperiment(updateLogDetail.name, item_id))-- return {- description: (- <SentenceList- prefix={<ActivityLogUserName logItem={logItem} />}- listParts={listParts}- suffix={suffix}- />- ),- extendedDescription: conclusionComment ? (- <blockquote className="border-l-2 pl-2 text-secondary">{conclusionComment}</blockquote>- ) : undefined,- }+ return describeExperimentUpdate(logItem, listParts, hasExperimentChanges, conclusionComment)}).otherwise(() => {return {+ summary: activityLogSummary(+ logItem,+ 'Performed an unknown action',+ nameOrLinkToExperiment(logItem.detail.name, logItem.item_id)+ ),description: <UnknownAction logItem={logItem} />,}})diff --git a/frontend/src/scenes/exports/activityDescriptions.tsx b/frontend/src/scenes/exports/activityDescriptions.tsxindex 4bf3c784c6e6..13f8661f1a13 100644--- a/frontend/src/scenes/exports/activityDescriptions.tsx+++ b/frontend/src/scenes/exports/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -21,6 +22,11 @@ export function exportedAssetActivityDescriber(logItem: ActivityLogItem, asNotif}return {+ summary: activityLogSummary(+ logItem,+ `Exported as ${formatLabel}`,+ <Link to={urls.exports()}>{logItem.detail.name || 'Export'}</Link>+ ),description: (<><ActivityLogUserName logItem={logItem} /> exported {asNotification ? 'your ' : ''}diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsxindex b8ef30b831c4..0e9e93f2a1eb 100644--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx@@ -1,18 +1,24 @@import { Fragment } from 'react'+import {+ describeListChanges,+ describeTagChanges,+} from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'import {ActivityChange,ActivityLogItem,+ Describer,ActivityLogUserName,ChangeMapping,Description,ExpandedView,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'-import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'import { Link } from 'lib/lemon-ui/Link'import { pluralize } from 'lib/utils/strings'@@ -258,9 +264,10 @@ const featureFlagActionsMapping: Record<keyof FeatureFlagType,(change?: ActivityChange, logItem?: ActivityLogItem) => ChangeMapping | null> = {- name: function onName() {+ name: function onName(change) {return {description: [<>changed the description</>],+ preview: typeof change?.after === 'string' ? change.after : undefined,}},active: function onActive(change, logItem) {@@ -415,6 +422,11 @@ const featureFlagActionsMapping: Record<const changeAfter = change?.after as stringreturn {description: [<>changed flag key on {changeBefore} to</>],+ summary: [+ <>+ Changed the flag key from {changeBefore} to {changeAfter}+ </>,+ ],suffix: <>{nameOrLinkToFlag(logItem?.item_id, changeAfter)}</>,}},@@ -461,58 +473,8 @@ const featureFlagActionsMapping: Record<],}},- tags: function onTags(change) {- const tagsBefore = change?.before as string[]- const tagsAfter = change?.after as string[]- const addedTags = tagsAfter.filter((t) => tagsBefore.indexOf(t) === -1)- const removedTags = tagsBefore.filter((t) => tagsAfter.indexOf(t) === -1)-- const changes: Description[] = []- if (addedTags.length) {- changes.push(- <>- added {pluralize(addedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={addedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }- if (removedTags.length) {- changes.push(- <>- removed {pluralize(removedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={removedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }-- return { description: changes }- },- evaluation_contexts: function onEvaluationContexts(change) {- const contextsBefore = (change?.before as string[]) || []- const contextsAfter = (change?.after as string[]) || []- const addedContexts = contextsAfter.filter((c) => contextsBefore.indexOf(c) === -1)- const removedContexts = contextsBefore.filter((c) => contextsAfter.indexOf(c) === -1)-- const changes: Description[] = []- if (addedContexts.length) {- changes.push(- <>- added {pluralize(addedContexts.length, 'evaluation context', 'evaluation contexts', false)}{' '}- <ObjectTags tags={addedContexts} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }- if (removedContexts.length) {- changes.push(- <>- removed {pluralize(removedContexts.length, 'evaluation context', 'evaluation contexts', false)}{' '}- <ObjectTags tags={removedContexts} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }-- return { description: changes }- },+ tags: describeTagChanges,+ evaluation_contexts: (change) => describeListChanges(change, 'evaluation context', 'evaluation contexts'),// fields that are excluded on the backendid: excludedFieldHandler,created_at: excludedFieldHandler,@@ -553,6 +515,182 @@ const getActorName = (logItem: ActivityLogItem): JSX.Element => {return <ActivityLogUserName logItem={logItem} />}+// A referenced cohort's conditions changed: the flag's own fields are untouched+// (only its version moved), so describe the cohort change instead of a field diff.+// job_type must stay in sync with COHORT_CONDITIONS_UPDATED_JOB_TYPE in+// products/feature_flags/backend/flag_version_sync.py.+function describeLinkedCohortUpdate(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ const { cohort_id, cohort_name } = logItem.detail.trigger?.payload ?? {}+ return {+ summary: activityLogSummary(+ logItem,+ <>+ Changed the conditions of linked cohort{' '}+ {cohort_id ? (+ <Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>+ ) : (+ cohort_name || 'unknown'+ )}+ </>,+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ undefined,+ getActorName(logItem)+ ),+ description: (+ <SentenceList+ listParts={[+ <Fragment key="cohort-conditions-updated">+ changed the conditions of linked cohort{' '}+ {cohort_id ? (+ <Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>+ ) : (+ <span>{cohort_name || 'unknown'}</span>+ )}+ </Fragment>,+ ]}+ prefix={getActorName(logItem)}+ suffix={+ <>+ on {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>+ }+ />+ ),+ }+}++// A flag this one depends on changed its definition: same story as above, only+// this flag's version moved. job_type must stay in sync with+// FLAG_DEPENDENCY_UPDATED_JOB_TYPE in+// products/feature_flags/backend/flag_version_sync.py.+function describeLinkedFlagUpdate(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ const { flag_id, flag_key } = logItem.detail.trigger?.payload ?? {}+ return {+ summary: activityLogSummary(+ logItem,+ <>+ Changed the definition of linked flag{' '}+ {flag_id ? (+ <Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>+ ) : (+ flag_key || 'unknown'+ )}+ </>,+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ undefined,+ getActorName(logItem)+ ),+ description: (+ <SentenceList+ listParts={[+ <Fragment key="flag-dependency-updated">+ changed the definition of linked flag{' '}+ {flag_id ? (+ <Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>+ ) : (+ <span>{flag_key || 'unknown'}</span>+ )}+ </Fragment>,+ ]}+ prefix={getActorName(logItem)}+ suffix={+ <>+ on {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>+ }+ />+ ),+ }+}++// The experiment exposure freeze rewrites the flag's filters to pin enrollment to a+// snapshot cohort; without the trigger check the rewrite reads as a manual targeting+// edit. job_type must stay in sync with the Trigger in+// products/experiments/backend/experiment_service.py.+function describeExposureFrozen(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Restricted the release conditions to the exposure freeze snapshot cohort',+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ undefined,+ getActorName(logItem)+ ),+ description: (+ <SentenceList+ listParts={['restricted the release conditions to the exposure freeze snapshot cohort']}+ prefix={getActorName(logItem)}+ suffix={+ <>+ on {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>+ }+ />+ ),+ }+}++function describeExposureUnfrozen(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Removed the exposure freeze restriction',+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ undefined,+ getActorName(logItem)+ ),+ description: (+ <SentenceList+ listParts={['removed the exposure freeze restriction']}+ prefix={getActorName(logItem)}+ suffix={+ <>+ from {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>+ }+ />+ ),+ }+}++const FLAG_TRIGGER_DESCRIBERS = new Map<string, Describer>([+ ['cohort_conditions_updated', describeLinkedCohortUpdate],+ ['flag_dependency_updated', describeLinkedFlagUpdate],+ ['experiment_exposure_frozen', describeExposureFrozen],+ ['experiment_exposure_unfrozen', describeExposureUnfrozen],+])++function describeFlagFieldChanges(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange | null {+ const mappings: ChangeMapping[] = []+ for (const change of logItem.detail.changes || []) {+ if (!change?.field) {+ continue+ }+ const handler = featureFlagActionsMapping[change.field as keyof FeatureFlagType]+ if (!handler) {+ console.error({ field: change.field, change }, 'No activity describer found for feature flag field')+ }+ const result = handler ? handler(change, logItem) : null+ if (result) {+ mappings.push(result)+ }+ }+ return describeChangeMappings(+ logItem,+ mappings,+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ <>+ on {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>,+ getActorName(logItem)+ )+}+export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'FeatureFlag') {console.error('feature flag describer received a non-feature flag activity')@@ -561,6 +699,13 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:if (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the feature flag',+ nameOrLinkToFlag(logItem.item_id, logItem.detail.name),+ undefined,+ getActorName(logItem)+ ),description: (<SentenceListlistParts={[<>created a new feature flag:</>]}@@ -572,140 +717,13 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:}if (logItem.activity == 'updated') {- // A referenced cohort's conditions changed: the flag's own fields are untouched- // (only its version moved), so describe the cohort change instead of a field diff.- // job_type must stay in sync with COHORT_CONDITIONS_UPDATED_JOB_TYPE in- // products/feature_flags/backend/flag_version_sync.py.- if (logItem.detail.trigger?.job_type === 'cohort_conditions_updated') {- const { cohort_id, cohort_name } = logItem.detail.trigger.payload ?? {}- return {- description: (- <SentenceList- listParts={[- <Fragment key="cohort-conditions-updated">- changed the conditions of linked cohort{' '}- {cohort_id ? (- <Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>- ) : (- <span>{cohort_name || 'unknown'}</span>- )}- </Fragment>,- ]}- prefix={getActorName(logItem)}- suffix={- <>- on {asNotification && ' the flag '}- {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}- </>- }- />- ),- }- }- // A flag this one depends on changed its definition: same story as above, only- // this flag's version moved. job_type must stay in sync with- // FLAG_DEPENDENCY_UPDATED_JOB_TYPE in- // products/feature_flags/backend/flag_version_sync.py.- if (logItem.detail.trigger?.job_type === 'flag_dependency_updated') {- const { flag_id, flag_key } = logItem.detail.trigger.payload ?? {}- return {- description: (- <SentenceList- listParts={[- <Fragment key="flag-dependency-updated">- changed the definition of linked flag{' '}- {flag_id ? (- <Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>- ) : (- <span>{flag_key || 'unknown'}</span>- )}- </Fragment>,- ]}- prefix={getActorName(logItem)}- suffix={- <>- on {asNotification && ' the flag '}- {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}- </>- }- />- ),- }- }- // The experiment exposure freeze rewrites the flag's filters to pin enrollment to a- // snapshot cohort; without the trigger check the rewrite reads as a manual targeting- // edit. job_type must stay in sync with the Trigger in- // products/experiments/backend/experiment_service.py.- if (logItem.detail.trigger?.job_type === 'experiment_exposure_frozen') {- return {- description: (- <SentenceList- listParts={['restricted the release conditions to the exposure freeze snapshot cohort']}- prefix={getActorName(logItem)}- suffix={- <>- on {asNotification && ' the flag '}- {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}- </>- }- />- ),- }- }- if (logItem.detail.trigger?.job_type === 'experiment_exposure_unfrozen') {- return {- description: (- <SentenceList- listParts={['removed the exposure freeze restriction']}- prefix={getActorName(logItem)}- suffix={- <>- from {asNotification && ' the flag '}- {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}- </>- }- />- ),- }- }- let changes: Description[] = []- let changeSuffix: Description = (- <>- on {asNotification && ' the flag '}- {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}- </>- )- let expandedView: ExpandedView | undefined-- for (const change of logItem.detail.changes || []) {- if (!change?.field) {- continue // feature flag updates have to have a "field" to be described- }-- const fieldHandler = featureFlagActionsMapping[change.field as keyof FeatureFlagType]- if (!fieldHandler) {- console.error({ field: change.field, change }, 'No activity describer found for feature flag field')- }- const possibleLogItem = fieldHandler ? fieldHandler(change, logItem) : null- if (possibleLogItem) {- const { description, suffix, expandedView: view } = possibleLogItem- if (description) {- changes = changes.concat(description)- }- if (suffix) {- changeSuffix = suffix- }- if (view) {- expandedView = view- }- }+ const describeTrigger = FLAG_TRIGGER_DESCRIBERS.get(logItem.detail.trigger?.job_type ?? '')+ if (describeTrigger) {+ return describeTrigger(logItem, asNotification)}-- if (changes.length) {- return {- description: <SentenceList listParts={changes} prefix={getActorName(logItem)} suffix={changeSuffix} />,- expandedView,- }+ const changes = describeFlagFieldChanges(logItem, asNotification)+ if (changes) {+ return changes}const updateChanges = logItem.detail.changes || []diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsxnew file mode 100644index 000000000000..134d7c9768ca--- /dev/null+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsx@@ -0,0 +1,66 @@+import { render } from '@testing-library/react'++import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'++import { ActivityScope } from '~/types'++import { hogFunctionActivityDescriber } from './activityDescriptions'++describe('hogFunctionActivityDescriber', () => {+ it.each<{+ name: string+ changes: Partial<ActivityChange>[]+ summary: string+ notification: string+ }>([+ {+ name: 'coalesces masked draft fields',+ changes: [+ { field: 'draft', before: 'masked', after: 'masked' },+ { field: 'draft_encrypted_inputs', before: 'masked', after: 'masked' },+ ],+ summary: 'changed the staged changes',+ notification: 'A user changed the staged changes on the hog function: Example destination',+ },+ {+ name: 'describes only changed inputs',+ changes: [+ {+ field: 'inputs',+ before: { region: { value: 'west' }, format: { value: 'json' } },+ after: { region: { value: 'east' }, format: { value: 'json' } },+ },+ ],+ summary: 'updated input: region',+ notification: 'A user updated the input region for the hog function: Example destination',+ },+ {+ name: 'retains source-code links and multi-change notifications',+ changes: [+ { field: 'hog', before: 'return 1', after: 'return 2' },+ { field: 'enabled', before: false, after: true },+ ],+ summary: 'updated source code, and enabled the hog function',+ notification:+ 'A user updated the hog function: Example destinationupdated source codeenabled the hog function',+ },+ ])('$name', ({ changes, summary, notification }) => {+ const logItem: ActivityLogItem = {+ activity: 'updated',+ scope: ActivityScope.HOG_FUNCTION,+ created_at: '2026-01-01T00:00:00Z',+ detail: {+ name: 'Example destination',+ merge: null,+ trigger: null,+ changes: changes.map((change) => ({ type: ActivityScope.HOG_FUNCTION, action: 'changed', ...change })),+ },+ }+ const result = hogFunctionActivityDescriber(logItem)+ const text = (element: React.ReactNode): string =>+ (render(<>{element}</>).container.textContent || '').replace(/\s+/g, ' ').trim()++ expect(text(result.summary?.action)).toBe(summary)+ expect(text(result.description)).toBe(notification)+ })+})diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsxindex 8008063f8cbe..c0e9ef2d441d 100644--- a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx@@ -1,11 +1,14 @@import { Suspense } from 'react'import {+ ActivityChange,ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'import { Link } from 'lib/lemon-ui/Link'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -61,6 +64,150 @@ export function DiffLink({ before, after, language, children }: DiffLinkProps):)}+type HogFunctionChange = { inline: string | JSX.Element; inlist: string | JSX.Element }++function describeHogFunctionInputs(change: ActivityChange): HogFunctionChange {+ const beforeValues = isObject(change.before) ? (change.before as Record<string, { value?: unknown }>) : {}+ const afterValues = isObject(change.after) ? (change.after as Record<string, { value?: unknown }>) : {}++ const changedFields = Object.entries(afterValues)+ .map(([key, value]) => {+ const before = JSON.stringify(beforeValues[key]?.value)+ const after = JSON.stringify(value?.value)++ if (before !== after) {+ return (+ <DiffLink key={key} before={before} after={after}>+ {key}+ </DiffLink>+ )+ }+ return null+ })+ .filter((x): x is JSX.Element => !!x)++ const changedSpans: JSX.Element[] = []+ for (let index = 0; index < changedFields.length; index++) {+ if (index !== 0 && index === changedFields.length - 1) {+ changedSpans.push(<>{' and '}</>)+ } else if (index > 0) {+ changedSpans.push(<>{', '}</>)+ }+ changedSpans.push(changedFields[index])+ }++ const inputOrInputs = changedFields.length === 1 ? 'input' : 'inputs'++ return {+ inline: (+ <>+ updated the {inputOrInputs} {changedSpans} for+ </>+ ),+ inlist: (+ <>+ updated {inputOrInputs}: {changedSpans}+ </>+ ),+ }+}++function describeHogFunctionCode(change: ActivityChange, field: string): HogFunctionChange {+ const code = (+ <DiffLink+ language={field === 'hog' ? 'hog' : 'json'}+ before={typeof change.before === 'string' ? change.before : JSON.stringify(change.before, null, 2)}+ after={typeof change.after === 'string' ? change.after : JSON.stringify(change.after, null, 2)}+ >+ {field === 'hog' ? 'source code' : field === 'inputs_schema' ? 'inputs schema' : field}+ </DiffLink>+ )++ return { inline: <>updated {code} for</>, inlist: <>updated {code}</> }+}++const HOG_FUNCTION_DIFF_FIELDS = new Set(['inputs_schema', 'filters', 'hog', 'name', 'description', 'masking'])++function describeHogFunctionField(change: ActivityChange, objectNoun: string): HogFunctionChange {+ if (change.field && HOG_FUNCTION_DIFF_FIELDS.has(change.field)) {+ return describeHogFunctionCode(change, change.field)+ }+ switch (change.field) {+ case 'encrypted_inputs':+ return { inline: 'updated encrypted inputs for', inlist: 'updated encrypted inputs' }+ case 'inputs':+ return describeHogFunctionInputs(change)+ case 'deleted': {+ const verb = change.after ? 'deleted' : 'undeleted'+ return { inline: verb, inlist: `${verb} the ${objectNoun}` }+ }+ case 'enabled': {+ const verb = change.after ? 'enabled' : 'disabled'+ return { inline: verb, inlist: `${verb} the ${objectNoun}` }+ }+ case 'priority':+ return {+ inline: (+ <>+ changed priority from {change.before} to {change.after} for{' '}+ </>+ ),+ inlist: (+ <>+ changed priority from {change.before} to {change.after} for{' '}+ </>+ ),+ }+ default:+ return {+ inline: `updated unknown field: ${change.field}`,+ inlist: `updated unknown field: ${change.field}`,+ }+ }+}++function describeHogFunctionUpdate(logItem: ActivityLogItem, objectNoun: string): HumanizedChange {+ const changes: HogFunctionChange[] = []+ for (const change of logItem.detail.changes ?? []) {+ // Both are masked server-side, so there is nothing to diff — say the staged config+ // changed and let the reader open it in the builder. A staged edit usually touches+ // both fields, so collapse them into one entry.+ if (change.field === 'draft' || change.field === 'draft_encrypted_inputs') {+ if (!changes.some((c) => c.inlist === STAGED_CHANGES)) {+ changes.push({ inline: `${STAGED_CHANGES} on`, inlist: STAGED_CHANGES })+ }+ continue+ }+ changes.push(describeHogFunctionField(change, objectNoun))+ }+ const functionName = nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name)++ return {+ summary: activityLogSummary(+ logItem,+ <SentenceList+ listParts={changes.length ? changes.map((change) => change.inlist) : [`Updated the ${objectNoun}`]}+ />,+ functionName+ ),+ description:+ changes.length == 1 ? (+ <>+ <ActivityLogUserName logItem={logItem} /> {changes[0].inline} the {objectNoun}: {functionName}+ </>+ ) : (+ <div>+ <ActivityLogUserName logItem={logItem} /> updated the {objectNoun}: {functionName}+ <ul className="ml-5 list-disc">+ {changes.map((c, i) => (+ <li key={i}>{c.inlist}</li>+ ))}+ </ul>+ </div>+ ),+ }+}+export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'HogFunction') {console.error('HogFunction describer received a non-HogFunction activity')@@ -72,6 +219,11 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ `Created the ${objectNoun}`,+ nameOrLinkToHogFunction(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the {objectNoun}:{' '}@@ -83,6 +235,11 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ `Deleted the ${objectNoun}`,+ logItem.detail.name || 'Untitled hog function'+ ),description: (<><ActivityLogUserName logItem={logItem} /> deleted the {objectNoun}: {logItem.detail.name}@@ -95,6 +252,7 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotificconst functionName = nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name)return {+ summary: activityLogSummary(logItem, `Restored the ${objectNoun}`, functionName),description: (<><ActivityLogUserName logItem={logItem} /> restored the {objectNoun}: {functionName}@@ -111,6 +269,11 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotific}if (logItem.activity in draftActivities) {return {+ summary: activityLogSummary(+ logItem,+ `${draftActivities[logItem.activity]} the ${objectNoun}`,+ nameOrLinkToHogFunction(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> {draftActivities[logItem.activity]} the {objectNoun}:{' '}@@ -121,160 +284,7 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotific}if (logItem.activity == 'updated') {- const changes: { inline: string | JSX.Element; inlist: string | JSX.Element }[] = []- for (const change of logItem.detail.changes ?? []) {- switch (change.field) {- case 'encrypted_inputs': {- changes.push({- inline: 'updated encrypted inputs for',- inlist: 'updated encrypted inputs',- })- break- }- // Both are masked server-side, so there is nothing to diff — say the staged config- // changed and let the reader open it in the builder. A staged edit usually touches- // both fields, so collapse them into one entry.- case 'draft':- case 'draft_encrypted_inputs': {- if (!changes.some((c) => c.inlist === STAGED_CHANGES)) {- changes.push({ inline: `${STAGED_CHANGES} on`, inlist: STAGED_CHANGES })- }- break- }- case 'inputs': {- const beforeValues = isObject(change.before)- ? (change.before as Record<string, { value?: unknown }>)- : {}- const afterValues = isObject(change.after)- ? (change.after as Record<string, { value?: unknown }>)- : {}-- const changedFields = Object.entries(afterValues)- .map(([key, value]) => {- const before = JSON.stringify(beforeValues[key]?.value)- const after = JSON.stringify(value?.value)-- if (before !== after) {- return (- <DiffLink key={key} before={before} after={after}>- {key}- </DiffLink>- )- }- return null- })- .filter((x): x is JSX.Element => !!x)-- const changedSpans: JSX.Element[] = []- for (let index = 0; index < changedFields.length; index++) {- if (index !== 0 && index === changedFields.length - 1) {- changedSpans.push(<>{' and '}</>)- } else if (index > 0) {- changedSpans.push(<>{', '}</>)- }- changedSpans.push(changedFields[index])- }-- const inputOrInputs = changedFields.length === 1 ? 'input' : 'inputs'- changes.push({- inline: (- <>- updated the {inputOrInputs} {changedSpans} for- </>- ),- inlist: (- <>- updated {inputOrInputs}: {changedSpans}- </>- ),- })- break- }- case 'inputs_schema':- case 'filters':- case 'hog':- case 'name':- case 'description':- case 'masking': {- const code = (- <DiffLink- language={change.field === 'hog' ? 'hog' : 'json'}- before={- typeof change.before === 'string'- ? change.before- : JSON.stringify(change.before, null, 2)- }- after={- typeof change.after === 'string' ? change.after : JSON.stringify(change.after, null, 2)- }- >- {change.field === 'hog'- ? 'source code'- : change.field === 'inputs_schema'- ? 'inputs schema'- : change.field}- </DiffLink>- )- changes.push({ inline: <>updated {code} for</>, inlist: <>updated {code}</> })- break- }- case 'deleted': {- if (change.after) {- changes.push({ inline: 'deleted', inlist: `deleted the ${objectNoun}` })- } else {- changes.push({ inline: 'undeleted', inlist: `undeleted the ${objectNoun}` })- }- break- }- case 'enabled': {- if (change.after) {- changes.push({ inline: 'enabled', inlist: `enabled the ${objectNoun}` })- } else {- changes.push({ inline: 'disabled', inlist: `disabled the ${objectNoun}` })- }- break- }- case 'priority': {- changes.push({- inline: (- <>- changed priority from {change.before} to {change.after} for{' '}- </>- ),- inlist: (- <>- changed priority from {change.before} to {change.after} for{' '}- </>- ),- })- break- }- default:- changes.push({- inline: `updated unknown field: ${change.field}`,- inlist: `updated unknown field: ${change.field}`,- })- }- }- const functionName = nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name)-- return {- description:- changes.length == 1 ? (- <>- <ActivityLogUserName logItem={logItem} /> {changes[0].inline} the {objectNoun}: {functionName}- </>- ) : (- <div>- <ActivityLogUserName logItem={logItem} /> updated the {objectNoun}: {functionName}- <ul className="ml-5 list-disc">- {changes.map((c, i) => (- <li key={i}>{c.inlist}</li>- ))}- </ul>- </div>- ),- }+ return describeHogFunctionUpdate(logItem, objectNoun)}return defaultDescriber(logItem, asNotification, nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name))}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookActivityDescriber.tsx b/frontend/src/scenes/notebooks/Notebook/notebookActivityDescriber.tsxindex 40d044721604..c441c60e6f92 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookActivityDescriber.tsx+++ b/frontend/src/scenes/notebooks/Notebook/notebookActivityDescriber.tsx@@ -1,14 +1,12 @@+import { describeMappedChanges } from 'lib/components/ActivityLog/activityDescriptions/describeMappedChanges'+import { shortIdActivityLink } from 'lib/components/ActivityLog/activityDescriptions/shortIdActivityLink'import {ActivityChange,ActivityLogItem,- ActivityLogUserName,ChangeMapping,- Description,HumanizedChange,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'-import { SentenceList } from 'lib/components/ActivityLog/SentenceList'-import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'import { ActivityScope } from '~/types'@@ -25,16 +23,6 @@ const notebookActionsMapping: Record<},}-function nameAndLink(logItem?: ActivityLogItem): JSX.Element {- return logItem?.detail?.short_id ? (- <Link to={urls.notebook(logItem.detail.short_id)}>{logItem?.detail.name || 'unknown'}</Link>- ) : logItem?.detail.name ? (- <>{logItem?.detail.name}</>- ) : (- <i>Untitled</i>- )-}-export function notebookActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope !== ActivityScope.NOTEBOOK) {console.error('notebook describer received a non-Notebook activity')@@ -42,42 +30,16 @@ export function notebookActivityDescriber(logItem: ActivityLogItem, asNotificati}if (logItem.activity == 'changed' || logItem.activity == 'updated') {- let changes: Description[] = []- let changeSuffix: Description = <>on {nameAndLink(logItem)}</>-- for (const change of logItem.detail.changes || []) {- if (!change?.field || !notebookActionsMapping[change.field]) {- continue // not all notebook fields are describable- }-- const actionHandler = notebookActionsMapping[change.field]- const processedChange = actionHandler(change, logItem)- if (processedChange === null) {- continue // // unexpected log from backend is indescribable- }-- const { description, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }-- if (suffix) {- changeSuffix = suffix- }- }-- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- }+ const changes = describeMappedChanges(+ logItem,+ notebookActionsMapping,+ shortIdActivityLink(logItem, urls.notebook),+ <>on {shortIdActivityLink(logItem, urls.notebook)}</>+ )+ if (changes) {+ return changes}}- return defaultDescriber(logItem, asNotification, nameAndLink(logItem))+ return defaultDescriber(logItem, asNotification, shortIdActivityLink(logItem, urls.notebook))}diff --git a/frontend/src/scenes/product-tours/activityDescriptions.tsx b/frontend/src/scenes/product-tours/activityDescriptions.tsxindex f87043344134..b4820d56294a 100644--- a/frontend/src/scenes/product-tours/activityDescriptions.tsx+++ b/frontend/src/scenes/product-tours/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -20,6 +21,11 @@ export function productTourActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the product tour',+ nameOrLinkToTour(logItem?.item_id, logItem?.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the product tour:{' '}@@ -31,6 +37,11 @@ export function productTourActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'updated') {return {+ summary: activityLogSummary(+ logItem,+ 'Updated the product tour',+ nameOrLinkToTour(logItem?.item_id, logItem?.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated the product tour:{' '}@@ -42,6 +53,11 @@ export function productTourActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the product tour',+ nameOrLinkToTour(logItem?.item_id, logItem?.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> deleted the product tour:{' '}diff --git a/frontend/src/scenes/saved-insights/activityDescriptions.tsx b/frontend/src/scenes/saved-insights/activityDescriptions.tsxindex 5f82f3ff5dc1..5fe5c4624823 100644--- a/frontend/src/scenes/saved-insights/activityDescriptions.tsx+++ b/frontend/src/scenes/saved-insights/activityDescriptions.tsx@@ -1,13 +1,18 @@import posthog from 'posthog-js'import { Fragment } from 'react'+import {+ describeDescriptionChange,+ describeTagChanges,+} from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'import {ActivityChange,ActivityLogItem,ActivityLogUserName,ChangeMapping,- Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'@@ -17,10 +22,8 @@ import {PropertiesSummary,SeriesSummary,} from 'lib/components/Cards/InsightCard/InsightDetails'-import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { Link } from 'lib/lemon-ui/Link'import { areObjectValuesEmpty } from 'lib/utils/objects'-import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { HogQLQuery, InsightQueryNode, QuerySchema } from '~/queries/schema/schema-general'@@ -64,21 +67,32 @@ const linkToDashboard = (dashboard: BareDashboardLink): JSX.Element => (</div>)+function describeInsightRename(+ change?: ActivityChange,+ logItem?: ActivityLogItem,+ asNotification?: boolean+): ChangeMapping {+ return {+ description: [+ <>+ renamed {asNotification && 'the insight '}"{change?.before}" to{' '}+ <strong>"{nameOrLinkToInsight(logItem?.detail.short_id, change?.after as string)}"</strong>+ </>,+ ],+ summary: [+ <>+ renamed "{change?.before}" to "{change?.after}"+ </>,+ ],+ suffix: <></>,+ }+}+const insightActionsMapping: Record<keyof InsightModel,(change?: ActivityChange, logItem?: ActivityLogItem, asNotification?: boolean) => ChangeMapping | null> = {- name: function onName(change, logItem, asNotification) {- return {- description: [- <>- renamed {asNotification && 'the insight '}"{change?.before}" to{' '}- <strong>"{nameOrLinkToInsight(logItem?.detail.short_id, change?.after as string)}"</strong>- </>,- ],- suffix: <></>,- }- },+ name: describeInsightRename,filters: function onChangedFilter(change) {const filtersAfter = change?.after as Partial<FilterType>@@ -110,6 +124,7 @@ const insightActionsMapping: Record<const isDeleted = detectBoolean(change?.after)const describeChange = isDeleted ? 'deleted' : 'restored'return {+ summary: [`${describeChange} the insight`],description: [<>{describeChange}@@ -121,38 +136,27 @@ const insightActionsMapping: Record<},short_id: function onShortId(change, _, asNotification) {return {- description: [+ summary: [<>- changed the short id {asNotification && ' of the insight '}to{' '}- <strong>"{change?.after as string}"</strong>+ changed the short id to <strong>"{change?.after as string}"</strong></>,],- }- },- derived_name: function onDerivedName(change, logItem, asNotification) {- return {description: [<>- renamed {asNotification && ' the insight '}"{change?.before}" to{' '}- <strong>"{nameOrLinkToInsight(logItem?.detail.short_id, change?.after as string)}"</strong>+ changed the short id {asNotification && ' of the insight '}to{' '}+ <strong>"{change?.after as string}"</strong></>,],- suffix: <></>,}},+ derived_name: describeInsightRename,description: function onDescription(change, _, asNotification) {- return {- description: [- <>- changed the description {asNotification && ' of the insight '}to{' '}- <strong>"{change?.after as string}"</strong>- </>,- ],- }+ return describeDescriptionChange(change, asNotification, 'insight')},favorited: function onFavorited(change, logItem, asNotification) {const isFavoriteAfter = detectBoolean(change?.after)return {+ summary: [isFavoriteAfter ? 'favorited the insight' : 'unfavorited the insight'],description: [<><div className="highlighted-activity">@@ -163,32 +167,7 @@ const insightActionsMapping: Record<suffix: <>{nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)}</>,}},- tags: function onTags(change) {- const tagsBefore = change?.before as string[]- const tagsAfter = change?.after as string[]- const addedTags = tagsAfter.filter((t) => tagsBefore.indexOf(t) === -1)- const removedTags = tagsBefore.filter((t) => tagsAfter.indexOf(t) === -1)-- const changes: Description[] = []- if (addedTags.length) {- changes.push(- <>- added {pluralize(addedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={addedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }- if (removedTags.length) {- changes.push(- <>- removed {pluralize(removedTags.length, 'tag', 'tags', false)}{' '}- <ObjectTags tags={removedTags} saving={false} style={{ display: 'inline' }} staticOnly />- </>- )- }-- return { description: changes }- },+ tags: describeTagChanges,dashboards: function onDashboardsChange(change, logItem, asNotification) {const dashboardsBefore = (change?.before as DashboardLink[]).map(unboxBareLink)const dashboardsAfter = (change?.after as DashboardLink[]).map(unboxBareLink)@@ -228,7 +207,28 @@ const insightActionsMapping: Record</>) : null- return { description: [addedSentence, removedSentence], suffix: <></> }+ return {+ description: [addedSentence, removedSentence],+ summary: [+ addedDashboards.length ? (+ <SentenceList+ prefix="added to"+ listParts={addedDashboards.map((dashboard) => (+ <Fragment key={dashboard.id}>{linkToDashboard(dashboard)}</Fragment>+ ))}+ />+ ) : null,+ removedDashboards.length ? (+ <SentenceList+ prefix="removed from"+ listParts={removedDashboards.map((dashboard) => (+ <Fragment key={dashboard.id}>{linkToDashboard(dashboard)}</Fragment>+ ))}+ />+ ) : null,+ ],+ suffix: <></>,+ }},alerts: () => null,// fields that are excluded on the backend@@ -276,164 +276,203 @@ function summarizeQueryChanges(query: InsightQueryNode | HogQLQuery): ChangeMapp}}-export function insightActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {- if (logItem.scope != 'Insight') {- console.error('insight describer received a non-insight activity')- return { description: null }- }-- if (logItem.activity == 'created') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> created the insight:{' '}- {nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)}- </>- ),+function describeInsightUpdate(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange | null {+ const mappings: ChangeMapping[] = []+ try {+ for (const change of logItem.detail.changes || []) {+ const handler = insightActionsMapping[change.field as keyof InsightModel]+ if (!change?.field || !handler) {+ continue+ }+ const result = handler(change, logItem, asNotification)+ if (result) {+ mappings.push(result)+ }}+ } catch (e) {+ console.error('Error while summarizing insight update', e)+ posthog.captureException(e)}+ return describeChangeMappings(+ logItem,+ mappings,+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name),+ <>+ on {asNotification && ' the insight '}+ {nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)}+ </>+ )+}- if (logItem.activity == 'deleted') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> deleted {asNotification ? 'your' : 'the'} insight:{' '}- {logItem.detail.name}- </>- ),- }+function describeInsightAuthentication(logItem: ActivityLogItem): HumanizedChange {+ const afterData = logItem.detail.changes?.[0]?.after as any+ const clientIp = afterData?.client_ip || 'unknown IP'+ const passwordNote = afterData?.password_note || 'unknown password'++ return {+ summary: activityLogSummary(+ logItem,+ 'Authenticated to the shared insight',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name),+ `From ${clientIp} using password ${passwordNote}`,+ <strong>Anonymous user</strong>+ ),+ description: (+ <>+ <strong>Anonymous user</strong> successfully authenticated to shared insight{' '}+ {nameOrLinkToInsight(logItem?.detail.short_id, logItem.detail.name)} from {clientIp} using password{' '}+ <strong>{passwordNote}</strong>+ </>+ ),}+}- if (logItem.activity == 'exported for opengraph image') {- return {- description: (- <>- <strong>PostHog</strong> exported {asNotification ? 'your' : 'the'} insight: {logItem.detail.name}{' '}- as an image for the shared insight link.- </>- ),- }+function describeInsightAuthenticationFailure(logItem: ActivityLogItem): HumanizedChange {+ const afterData = logItem.detail.changes?.[0]?.after as any+ const clientIp = afterData?.client_ip || 'unknown IP'++ return {+ summary: activityLogSummary(+ logItem,+ 'Failed to authenticate to the shared insight',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name),+ `From ${clientIp}`,+ <strong>Anonymous user</strong>+ ),+ description: (+ <>+ <strong>Anonymous user</strong> failed to authenticate to shared insight{' '}+ {nameOrLinkToInsight(logItem?.detail.short_id, logItem.detail.name)} from {clientIp}+ </>+ ),}+}- if (logItem.activity == 'sharing enabled') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> shared {asNotification ? 'your' : 'the'} insight:{' '}- {logItem.detail.name}.- </>- ),- }+function describeInsightExport(logItem: ActivityLogItem): HumanizedChange {+ const exportFormat = logItem.detail.changes?.[0]?.after+ let exportType = 'in an unknown format'+ if (typeof exportFormat === 'string') {+ exportType = exportFormat.split('/')[1]}- if (logItem.activity == 'sharing disabled') {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> deleted shared link for {asNotification ? 'your' : 'the'}{' '}- insight: {logItem.detail.name}.- </>- ),- }+ return {+ summary: activityLogSummary(+ logItem,+ `Exported as ${exportType}`,+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> exported{' '}+ {nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)} as a {exportType}+ </>+ ),}+}- if (logItem.activity == 'updated') {- let changes: Description[] = []- let extendedDescription: JSX.Element | undefined- let changeSuffix: Description = (+function describeInsightCreated(logItem: ActivityLogItem): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Created the insight',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name)+ ),+ description: (<>- on {asNotification && ' the insight '}+ <ActivityLogUserName logItem={logItem} /> created the insight:{' '}{nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)}</>- )-- try {- for (const change of logItem.detail.changes || []) {- const insightAction = insightActionsMapping[change.field as keyof InsightModel]- if (!change?.field || !insightAction) {- continue // insight updates have to have a "field" to be described- }+ ),+ }+}- const actionHandler = insightAction- const processedChange = actionHandler(change, logItem, asNotification)- if (processedChange === null) {- continue // unexpected log from backend is indescribable- }+function describeInsightDeleted(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(logItem, 'Deleted the insight', logItem.detail.name || 'Insight'),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> deleted {asNotification ? 'your' : 'the'} insight:{' '}+ {logItem.detail.name}+ </>+ ),+ }+}- const { description, extendedDescription: _extendedDescription, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }- if (_extendedDescription) {- extendedDescription = _extendedDescription- }- if (suffix) {- changeSuffix = suffix- }- }- } catch (e) {- console.error('Error while summarizing insight update', e)- posthog.captureException(e)- }+function describeInsightPreviewExport(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Exported a preview image for the shared link',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name),+ undefined,+ <strong>PostHog</strong>+ ),+ description: (+ <>+ <strong>PostHog</strong> exported {asNotification ? 'your' : 'the'} insight: {logItem.detail.name} as an+ image for the shared insight link.+ </>+ ),+ }+}- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- extendedDescription,- }- }+function describeInsightSharingEnabled(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Enabled sharing',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> shared {asNotification ? 'your' : 'the'} insight:{' '}+ {logItem.detail.name}.+ </>+ ),}- if (logItem.activity === 'exported') {- const exportFormat = logItem.detail.changes?.[0]?.after- let exportType = 'in an unknown format'- if (typeof exportFormat === 'string') {- exportType = exportFormat.split('/')[1]- }+}- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> exported{' '}- {nameOrLinkToInsight(logItem?.detail.short_id, logItem?.detail.name)} as a {exportType}- </>- ),- }+function describeInsightSharingDisabled(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the shared link',+ nameOrLinkToInsight(logItem.detail.short_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> deleted shared link for {asNotification ? 'your' : 'the'}{' '}+ insight: {logItem.detail.name}.+ </>+ ),}+}- if (logItem.activity === 'share_login_success') {- const afterData = logItem.detail.changes?.[0]?.after as any- const clientIp = afterData?.client_ip || 'unknown IP'- const passwordNote = afterData?.password_note || 'unknown password'+const INSIGHT_ACTIVITY_DESCRIBERS = new Map<+ string,+ (logItem: ActivityLogItem, asNotification?: boolean) => HumanizedChange | null+>([+ ['created', describeInsightCreated],+ ['deleted', describeInsightDeleted],+ ['exported for opengraph image', describeInsightPreviewExport],+ ['sharing enabled', describeInsightSharingEnabled],+ ['sharing disabled', describeInsightSharingDisabled],+ ['updated', describeInsightUpdate],+ ['exported', describeInsightExport],+ ['share_login_success', describeInsightAuthentication],+ ['share_login_failed', describeInsightAuthenticationFailure],+])- return {- description: (- <>- <strong>Anonymous user</strong> successfully authenticated to shared insight{' '}- {nameOrLinkToInsight(logItem?.detail.short_id, logItem.detail.name)} from {clientIp} using password{' '}- <strong>{passwordNote}</strong>- </>- ),- }+export function insightActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ if (logItem.scope != 'Insight') {+ console.error('insight describer received a non-insight activity')+ return { description: null }}- if (logItem.activity === 'share_login_failed') {- const afterData = logItem.detail.changes?.[0]?.after as any- const clientIp = afterData?.client_ip || 'unknown IP'-- return {- description: (- <>- <strong>Anonymous user</strong> failed to authenticate to shared insight{' '}- {nameOrLinkToInsight(logItem?.detail.short_id, logItem.detail.name)} from {clientIp}- </>- ),- }+ const describer = INSIGHT_ACTIVITY_DESCRIBERS.get(logItem.activity)+ const description = describer?.(logItem, asNotification)+ if (description) {+ return description}return defaultDescriber(diff --git a/frontend/src/scenes/session-recordings/activityDescription.tsx b/frontend/src/scenes/session-recordings/activityDescription.tsxindex 30fc944a9db2..6ede7ed7576a 100644--- a/frontend/src/scenes/session-recordings/activityDescription.tsx+++ b/frontend/src/scenes/session-recordings/activityDescription.tsx@@ -2,11 +2,35 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { ActivityScope } from '~/types'+function describeReplayAuthentication(logItem: ActivityLogItem): HumanizedChange {+ const afterData = logItem.detail.changes?.[0]?.after as any+ const clientIp = afterData?.client_ip || 'unknown IP'+ const passwordNote = afterData?.password_note || 'unknown password'++ return {+ summary: activityLogSummary(+ logItem,+ 'Authenticated to the shared recording',+ logItem.detail?.name || 'Session recording',+ `From ${clientIp}, using password ${passwordNote}`,+ <strong>Anonymous user</strong>+ ),+ description: (+ <>+ <strong>Anonymous user</strong> successfully authenticated to shared session recording{' '}+ <b>{logItem.detail?.name || 'session recording'}</b> from {clientIp} using password{' '}+ <strong>{passwordNote}</strong>+ </>+ ),+ }+}+export function replayActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope !== ActivityScope.REPLAY) {console.error('replay describer received a non-replay activity')@@ -15,6 +39,11 @@ export function replayActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'bulk_deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Bulk deleted session recordings',+ logItem.detail?.name || 'Session recordings'+ ),description: (<><ActivityLogUserName logItem={logItem} /> bulk deleted{' '}@@ -25,19 +54,7 @@ export function replayActivityDescriber(logItem: ActivityLogItem, asNotification}if (logItem.activity === 'share_login_success') {- const afterData = logItem.detail.changes?.[0]?.after as any- const clientIp = afterData?.client_ip || 'unknown IP'- const passwordNote = afterData?.password_note || 'unknown password'-- return {- description: (- <>- <strong>Anonymous user</strong> successfully authenticated to shared session recording{' '}- <b>{logItem.detail?.name || 'session recording'}</b> from {clientIp} using password{' '}- <strong>{passwordNote}</strong>- </>- ),- }+ return describeReplayAuthentication(logItem)}if (logItem.activity === 'share_login_failed') {@@ -45,6 +62,13 @@ export function replayActivityDescriber(logItem: ActivityLogItem, asNotificationconst clientIp = afterData?.client_ip || 'unknown IP'return {+ summary: activityLogSummary(+ logItem,+ 'Failed to authenticate to the shared recording',+ logItem.detail?.name || 'Session recording',+ `From ${clientIp}`,+ <strong>Anonymous user</strong>+ ),description: (<><strong>Anonymous user</strong> failed to authenticate to shared session recording{' '}diff --git a/frontend/src/scenes/settings/organization/activityDescriptions.test.tsx b/frontend/src/scenes/settings/organization/activityDescriptions.test.tsxindex 14836ee5dd17..93eb9b57ea1d 100644--- a/frontend/src/scenes/settings/organization/activityDescriptions.test.tsx+++ b/frontend/src/scenes/settings/organization/activityDescriptions.test.tsx@@ -35,8 +35,14 @@ describe('organizationActivityDescriber', () => {// Base UI marks the element it merges the tooltip trigger onto. Opening the popup is not// reliable in jsdom because of the hover delay, so assert on the trigger instead.const renderInviterName = (context: Record<string, any>, overrides?: Partial<ActivityLogItem>): HTMLElement => {- const { description } = organizationActivityDescriber(makeInviteLogItem(context, overrides))+ const { description, summary } = organizationActivityDescriber(makeInviteLogItem(context, overrides))+ const actor = render(<>{summary?.actor}</>).container+ const inviter = within(actor).getByText('Ada Lovelace')+ expect(inviter.classList.contains('ph-no-capture')).toBe(true)const { container } = render(description as JSX.Element)+ expect(inviter.hasAttribute('data-base-ui-tooltip-trigger')).toBe(+ within(container).getByText('Ada Lovelace').hasAttribute('data-base-ui-tooltip-trigger')+ )return within(container).getByText('Ada Lovelace')}diff --git a/frontend/src/scenes/settings/organization/activityDescriptions.tsx b/frontend/src/scenes/settings/organization/activityDescriptions.tsxindex c21453fb5b20..4dbb698e06c8 100644--- a/frontend/src/scenes/settings/organization/activityDescriptions.tsx+++ b/frontend/src/scenes/settings/organization/activityDescriptions.tsx@@ -1,9 +1,12 @@import {ActivityLogItem,ActivityLogUserName,+ Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { UserNameWithEmail } from 'lib/components/ActivityLog/UserNameWithEmail'import { OrganizationMembershipLevel } from 'lib/constants'import { Link } from 'lib/lemon-ui/Link'@@ -29,6 +32,11 @@ export function organizationActivityDescriber(logItem: ActivityLogItem, asNotifi}if (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the organization',+ nameOrLinkToOrganization(logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the organization{' '}@@ -39,11 +47,13 @@ export function organizationActivityDescriber(logItem: ActivityLogItem, asNotifi}if (logItem.activity == 'deleted') {+ const organizationName = logItem.detail.name || 'Organization'return {+ summary: activityLogSummary(logItem, 'Deleted the organization', organizationName),description: (<><ActivityLogUserName logItem={logItem} /> deleted the organization{' '}- <strong>{logItem.detail.name || 'Organization'}</strong>+ <strong>{organizationName}</strong></>),}@@ -61,6 +71,7 @@ export function organizationActivityDescriber(logItem: ActivityLogItem, asNotifi)return {+ summary: activityLogSummary(logItem, changeDescription, nameOrLinkToOrganization(logItem.detail.name)),description: (<><ActivityLogUserName logItem={logItem} /> {changeDescription} for organization{' '}@@ -70,6 +81,11 @@ export function organizationActivityDescriber(logItem: ActivityLogItem, asNotifi}} else if (changes.length > 1) {return {+ summary: activityLogSummary(+ logItem,+ <>Updated {changes.length} organization settings</>,+ nameOrLinkToOrganization(logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated <strong>{changes.length} settings</strong> for@@ -91,6 +107,14 @@ function organizationMembershipActivityDescriber(logItem: ActivityLogItem, asNotif (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Added an organization member',+ <>+ <UserNameWithEmail name={userName} email={userEmail} /> in{' '}+ {nameOrLinkToOrganization(organizationName)}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> added user{' '}@@ -105,6 +129,14 @@ function organizationMembershipActivityDescriber(logItem: ActivityLogItem, asNotif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Removed an organization member',+ <>+ <UserNameWithEmail name={userName} email={userEmail} /> in{' '}+ {nameOrLinkToOrganization(organizationName)}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> removed user{' '}@@ -128,6 +160,16 @@ function organizationMembershipActivityDescriber(logItem: ActivityLogItem, asNotmembershipLevelToName.get(levelChange.after as OrganizationMembershipLevel) || levelChange.afterreturn {+ summary: activityLogSummary(+ logItem,+ <>+ Changed role from {String(beforeLevel)} to {String(afterLevel)}+ </>,+ <>+ <UserNameWithEmail name={userName} email={userEmail} /> in{' '}+ {nameOrLinkToOrganization(organizationName)}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> changed{' '}@@ -142,6 +184,14 @@ function organizationMembershipActivityDescriber(logItem: ActivityLogItem, asNot}return {+ summary: activityLogSummary(+ logItem,+ 'Updated organization membership',+ <>+ <UserNameWithEmail name={userName} email={userEmail} /> in{' '}+ {nameOrLinkToOrganization(organizationName)}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated{' '}@@ -174,6 +224,15 @@ function organizationInviteActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ <>Sent an invitation to join as {level}</>,+ <>+ {targetEmail} in {nameOrLinkToOrganization(organizationName)}+ </>,+ undefined,+ inviter+ ),description: (<>{inviter} sent an invitation to <strong>{targetEmail}</strong> to join organization{' '}@@ -185,6 +244,15 @@ function organizationInviteActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Revoked the invitation',+ <>+ {targetEmail} in {nameOrLinkToOrganization(organizationName)}+ </>,+ undefined,+ inviter+ ),description: (<>{inviter} revoked the invitation for <strong>{targetEmail}</strong> to join organization{' '}@@ -206,6 +274,15 @@ function organizationInviteActivityDescriber(logItem: ActivityLogItem, asNotific)return {+ summary: activityLogSummary(+ logItem,+ <>{changeDescription} for the invitation</>,+ <>+ {targetEmail} in {nameOrLinkToOrganization(organizationName)}+ </>,+ undefined,+ inviter+ ),description: (<>{inviter} {changeDescription} for the invitation sent to <strong>{targetEmail}</strong> to join@@ -215,6 +292,15 @@ function organizationInviteActivityDescriber(logItem: ActivityLogItem, asNotific}} else if (changes.length > 1) {return {+ summary: activityLogSummary(+ logItem,+ <>Updated {changes.length} invitation settings</>,+ <>+ {targetEmail} in {nameOrLinkToOrganization(organizationName)}+ </>,+ undefined,+ inviter+ ),description: (<>{inviter} updated <strong>{changes.length} settings</strong> for the invitation sent to{' '}@@ -228,65 +314,79 @@ function organizationInviteActivityDescriber(logItem: ActivityLogItem, asNotificreturn defaultDescriber(logItem, asNotification)}-export function organizationDomainActivityDescriber(- logItem: ActivityLogItem,- asNotification?: boolean-): HumanizedChange {- const context = logItem.detail.context- const domainName = context?.domain || 'unknown domain'-- if (logItem.activity === 'updated') {- const changes = logItem.detail.changes || []- const hasScimEnabledChange = changes.some((c) => c.field === 'SCIM provisioning')+function describeOrganizationDomainUpdate(logItem: ActivityLogItem, domainName: string): HumanizedChange | null {+ const changes = logItem.detail.changes || []+ const hasScimEnabledChange = changes.some((c) => c.field === 'SCIM provisioning')- const descriptions: JSX.Element[] = []- for (const change of changes) {- if (change.field === 'SCIM provisioning') {- descriptions.push(- <>- {change.after ? 'enabled' : 'disabled'} <strong>SCIM provisioning</strong> for domain{' '}- <strong>{domainName}</strong>- </>- )- } else if (change.field === 'scim_bearer_token') {- if (!hasScimEnabledChange) {- descriptions.push(- <>- rotated the <strong>SCIM bearer token</strong> for domain <strong>{domainName}</strong>- </>- )- }- } else {+ const descriptions: JSX.Element[] = []+ const summaryChanges: Description[] = []+ for (const change of changes) {+ if (change.field === 'SCIM provisioning') {+ summaryChanges.push(change.after ? 'Enabled SCIM provisioning' : 'Disabled SCIM provisioning')+ descriptions.push(+ <>+ {change.after ? 'enabled' : 'disabled'} <strong>SCIM provisioning</strong> for domain{' '}+ <strong>{domainName}</strong>+ </>+ )+ } else if (change.field === 'scim_bearer_token') {+ if (!hasScimEnabledChange) {+ summaryChanges.push('Rotated the SCIM bearer token')descriptions.push(<>- updated <strong>{change.field}</strong> for domain <strong>{domainName}</strong>+ rotated the <strong>SCIM bearer token</strong> for domain <strong>{domainName}</strong></>)}+ } else {+ summaryChanges.push(<>Updated {change.field}</>)+ descriptions.push(+ <>+ updated <strong>{change.field}</strong> for domain <strong>{domainName}</strong>+ </>+ )}+ }- if (descriptions.length > 0) {- return {- description: (- <>- <ActivityLogUserName logItem={logItem} />{' '}- {descriptions.length === 1 ? (- descriptions[0]- ) : (- <ul>- {descriptions.map((d, i) => (- <li key={i}>{d}</li>- ))}- </ul>- )}- </>- ),- }+ if (descriptions.length > 0) {+ return {+ summary: activityLogSummary(logItem, <SentenceList listParts={summaryChanges} />, domainName),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} />{' '}+ {descriptions.length === 1 ? (+ descriptions[0]+ ) : (+ <ul>+ {descriptions.map((d, i) => (+ <li key={i}>{d}</li>+ ))}+ </ul>+ )}+ </>+ ),+ }+ }+ return null+}++export function organizationDomainActivityDescriber(+ logItem: ActivityLogItem,+ asNotification?: boolean+): HumanizedChange {+ const context = logItem.detail.context+ const domainName = context?.domain || 'unknown domain'++ if (logItem.activity === 'updated') {+ const result = describeOrganizationDomainUpdate(logItem, domainName)+ if (result) {+ return result}}if (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the domain', domainName),description: (<><ActivityLogUserName logItem={logItem} /> deleted domain <strong>{domainName}</strong>@@ -297,6 +397,7 @@ export function organizationDomainActivityDescriber(if (logItem.activity === 'created') {return {+ summary: activityLogSummary(logItem, 'Added the domain', domainName),description: (<><ActivityLogUserName logItem={logItem} /> added domain <strong>{domainName}</strong>@@ -319,6 +420,7 @@ export function legalDocumentActivityDescriber(logItem: ActivityLogItem, asNotifif (logItem.activity === 'created') {return {+ summary: activityLogSummary(logItem, `Generated ${article} ${documentType}`, companyName),description: (<><ActivityLogUserName logItem={logItem} /> generated {article} <strong>{documentType}</strong> for{' '}@@ -330,6 +432,7 @@ export function legalDocumentActivityDescriber(logItem: ActivityLogItem, asNotifif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, `Deleted ${article} ${documentType}`, companyName),description: (<><ActivityLogUserName logItem={logItem} /> deleted {article} <strong>{documentType}</strong> for{' '}diff --git a/frontend/src/scenes/settings/project/activityDescriptions.tsx b/frontend/src/scenes/settings/project/activityDescriptions.tsxindex 1c870a417005..3ecb09467eed 100644--- a/frontend/src/scenes/settings/project/activityDescriptions.tsx+++ b/frontend/src/scenes/settings/project/activityDescriptions.tsx@@ -3,6 +3,7 @@ import {ActivityLogUserName,Describer,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -27,6 +28,13 @@ export const projectSecretAPIKeyActivityDescriber: Describer = (logItem: Activitif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the project secret API key',+ <>+ {keyName} for {scopeName}+ </>+ ),description: (<>{actor} created project secret API key {keyName} for {scopeName}@@ -40,6 +48,13 @@ export const projectSecretAPIKeyActivityDescriber: Describer = (logItem: Activitif (rolled) {return {+ summary: activityLogSummary(+ logItem,+ 'Rolled the project secret API key',+ <>+ {keyName} for {scopeName}+ </>+ ),description: (<>{actor} rolled project secret API key {keyName} for {scopeName}@@ -49,6 +64,13 @@ export const projectSecretAPIKeyActivityDescriber: Describer = (logItem: Activit}return {+ summary: activityLogSummary(+ logItem,+ 'Updated the project secret API key',+ <>+ {keyName} for {scopeName}+ </>+ ),description: (<>{actor} updated project secret API key {keyName} for {scopeName}@@ -59,6 +81,13 @@ export const projectSecretAPIKeyActivityDescriber: Describer = (logItem: Activitif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the project secret API key',+ <>+ {keyName} for {scopeName}+ </>+ ),description: (<>{actor} deleted project secret API key {keyName} for {scopeName}diff --git a/frontend/src/scenes/settings/user/activityDescriptions.tsx b/frontend/src/scenes/settings/user/activityDescriptions.tsxindex 71c7b6dd36a1..a9534de47e3d 100644--- a/frontend/src/scenes/settings/user/activityDescriptions.tsx+++ b/frontend/src/scenes/settings/user/activityDescriptions.tsx@@ -3,6 +3,7 @@ import {ActivityLogUserName,Describer,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -29,6 +30,13 @@ export const personalAPIKeyActivityDescriber: Describer = (logItem: ActivityLogIif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the personal API key',+ <>+ {getKeyTitle()} · {getScopeDescription()}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> created personal API key <strong>{getKeyTitle()}</strong>{' '}@@ -40,6 +48,13 @@ export const personalAPIKeyActivityDescriber: Describer = (logItem: ActivityLogIif (logItem.activity === 'revoked') {return {+ summary: activityLogSummary(+ logItem,+ 'Revoked the personal API key',+ <>+ {getKeyTitle()} · {getScopeDescription()}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> revoked access for personal API key{' '}@@ -54,6 +69,13 @@ export const personalAPIKeyActivityDescriber: Describer = (logItem: ActivityLogIif (rolledChangeDescription) {return {+ summary: activityLogSummary(+ logItem,+ 'Rolled the personal API key',+ <>+ {getKeyTitle()} · {getScopeDescription()}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> rolled personal API key{' '}@@ -64,6 +86,13 @@ export const personalAPIKeyActivityDescriber: Describer = (logItem: ActivityLogI}return {+ summary: activityLogSummary(+ logItem,+ 'Updated the personal API key',+ <>+ {getKeyTitle()} · {getScopeDescription()}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated personal API key <strong>{getKeyTitle()}</strong>{' '}@@ -75,6 +104,13 @@ export const personalAPIKeyActivityDescriber: Describer = (logItem: ActivityLogIif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the personal API key',+ <>+ {getKeyTitle()} · {getScopeDescription()}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> deleted personal API key <strong>{getKeyTitle()}</strong>{' '}@@ -122,6 +158,12 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLoif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Registered the OAuth application',+ appName,+ `Scope ceiling: ${after.join(', ')}`+ ),description: (<>{actor} registered OAuth application <strong>{appName}</strong> with scope ceiling{' '}@@ -134,6 +176,12 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLoif (logItem.activity === 'updated') {if (after.length === 0 && before.length > 0) {return {+ summary: activityLogSummary(+ logItem,+ 'Removed the scope ceiling',+ appName,+ `Previously ${before.join(', ')}. Default unprivileged scopes now apply.`+ ),description: (<>{actor} removed the scope ceiling on <strong>{appName}</strong> (was{' '}@@ -145,6 +193,7 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLoif (before.length === 0 && after.length > 0) {return {+ summary: activityLogSummary(logItem, 'Set the scope ceiling', appName, after.join(', ')),description: (<>{actor} set the scope ceiling on <strong>{appName}</strong> to <ScopeList scopes={after} />@@ -158,6 +207,12 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLoif (added.length > 0 && removed.length > 0) {return {+ summary: activityLogSummary(+ logItem,+ 'Changed the scope ceiling',+ appName,+ `Added ${added.join(', ')}; removed ${removed.join(', ')}`+ ),description: (<>{actor} changed the scope ceiling on <strong>{appName}</strong>: added{' '}@@ -168,6 +223,7 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLo}if (added.length > 0) {return {+ summary: activityLogSummary(logItem, 'Widened the scope ceiling', appName, `Added ${added.join(', ')}`),description: (<>{actor} widened the scope ceiling on <strong>{appName}</strong>: added{' '}@@ -178,6 +234,12 @@ export const oauthApplicationActivityDescriber: Describer = (logItem: ActivityLo}if (removed.length > 0) {return {+ summary: activityLogSummary(+ logItem,+ 'Narrowed the scope ceiling',+ appName,+ `Removed ${removed.join(', ')}`+ ),description: (<>{actor} narrowed the scope ceiling on <strong>{appName}</strong>: removed{' '}diff --git a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx b/frontend/src/scenes/surveys/surveyActivityDescriber.tsxindex c4e30ffd13eb..5b6fa8c5b5e3 100644--- a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx+++ b/frontend/src/scenes/surveys/surveyActivityDescriber.tsx@@ -1,5 +1,6 @@import { P, match } from 'ts-pattern'+import { summarizeDescriptionChange } from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'import {ActivityChange,ActivityLogItem,@@ -7,9 +8,11 @@ import {ChangeMapping,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'import { truncate } from 'lib/utils/strings'import { urls } from 'scenes/urls'@@ -58,6 +61,8 @@ const surveyActionsMapping: Record<},description: function onDescription(change) {return {+ summary: summarizeDescriptionChange(change),+ preview: typeof change?.after === 'string' ? change.after : undefined,description: [<>updated the description from {formatDescription(change?.before as string | null | undefined)} to{' '}@@ -330,6 +335,45 @@ const surveyActionsMapping: Record<},}+function collectSurveyChanges(logItem: ActivityLogItem): {+ changes: { field: string; description: Description }[]+ summaryChanges: Description[]+ preview?: string+} {+ const changes: { field: string; description: Description }[] = []+ const summaryChanges: Description[] = []+ let preview: string | undefined++ for (const change of logItem.detail.changes || []) {+ if (!change?.field) {+ continue+ }++ const possibleLogItem = surveyActionsMapping[change.field]?.(change, logItem)+ if (possibleLogItem?.description) {+ summaryChanges.push(...(possibleLogItem.summary ?? possibleLogItem.description))+ preview = possibleLogItem.preview ?? preview+ if (Array.isArray(possibleLogItem.description) && possibleLogItem.description.length > 1) {+ // This is for the conditions section, which may have multiple changes.+ // Probably could be refactored into a separate handler like some of the other fields+ changes.push(+ ...possibleLogItem.description.map((desc) => ({+ field: 'conditions',+ description: desc,+ }))+ )+ } else {+ changes.push({+ field: change.field,+ description: possibleLogItem.description[0],+ })+ }+ }+ }++ return { changes, summaryChanges, preview }+}+export function surveyActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope !== 'Survey') {console.error('survey describer received a non-survey activity')@@ -341,6 +385,7 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'created') {return {+ summary: activityLogSummary(logItem, 'Created the survey', surveyLink),description: (<>{user} created {surveyLink}@@ -351,6 +396,7 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the survey', surveyLink),description: (<>{user} deleted {surveyLink}@@ -360,37 +406,13 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotification}if (logItem.activity === 'updated') {- const changes: { field: string; description: Description }[] = []-- for (const change of logItem.detail.changes || []) {- if (!change?.field) {- continue- }-- const possibleLogItem = surveyActionsMapping[change.field]?.(change, logItem)- if (possibleLogItem?.description) {- if (Array.isArray(possibleLogItem.description) && possibleLogItem.description.length > 1) {- // This is for the conditions section, which may have multiple changes.- // Probably could be refactored into a separate handler like some of the other fields- changes.push(- ...possibleLogItem.description.map((desc) => ({- field: 'conditions',- description: desc,- }))- )- } else {- changes.push({- field: change.field,- description: possibleLogItem.description[0],- })- }- }- }+ const { changes, summaryChanges, preview } = collectSurveyChanges(logItem)if (changes.length === 1) {const { field, description } = changes[0]const preposition = field === 'conditions' ? 'for' : getPreposition(field)return {+ summary: activityLogSummary(logItem, <SentenceList listParts={summaryChanges} />, surveyLink, preview),description: (<>{user} {description} {preposition} {surveyLink}@@ -399,6 +421,7 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotification}} else if (changes.length > 1) {return {+ summary: activityLogSummary(logItem, <SentenceList listParts={summaryChanges} />, surveyLink, preview),description: (<>{user} made multiple changes to {surveyLink}:diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsxindex c5abe8257a33..fa904cfa0116 100644--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx@@ -1,10 +1,12 @@+import { describeMappedChanges } from 'lib/components/ActivityLog/activityDescriptions/describeMappedChanges'+import { shortIdActivityLink } from 'lib/components/ActivityLog/activityDescriptions/shortIdActivityLink'import {ActivityChange,ActivityLogItem,ActivityLogUserName,ChangeMapping,- Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'@@ -762,14 +764,24 @@ const TEAM_PROPERTIES_MAPPING: Record<feature_flag_policy_config: () => null,}-function nameAndLink(logItem?: ActivityLogItem): JSX.Element {- return logItem?.detail?.short_id ? (- <Link to={urls.notebook(logItem.detail.short_id)}>{logItem?.detail.name || 'unknown'}</Link>- ) : logItem?.detail.name ? (- <>{logItem?.detail.name}</>- ) : (- <i>Untitled</i>- )+function describeWorkflowEmailSuspension(logItem: ActivityLogItem): HumanizedChange {+ const wasSuspended = logItem.activity === 'email_sending_suspended'+ const reason = logItem.detail?.context?.reason as string | undefined+ return {+ summary: activityLogSummary(+ logItem,+ wasSuspended ? 'Suspended workflow email sending' : 'Re-enabled workflow email sending',+ shortIdActivityLink(logItem, urls.notebook),+ wasSuspended ? reason : undefined+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> {wasSuspended ? 'suspended' : 're-enabled'} workflow email+ sending on {shortIdActivityLink(logItem, urls.notebook)}+ {wasSuspended && reason ? <> (reason: {reason})</> : null}+ </>+ ),+ }}export function teamActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {@@ -779,56 +791,20 @@ export function teamActivityDescriber(logItem: ActivityLogItem, asNotification?:}if (logItem.activity === 'email_sending_suspended' || logItem.activity === 'email_sending_unsuspended') {- const wasSuspended = logItem.activity === 'email_sending_suspended'- const reason = logItem.detail?.context?.reason as string | undefined- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> {wasSuspended ? 'suspended' : 're-enabled'} workflow email- sending on {nameAndLink(logItem)}- {wasSuspended && reason ? <> (reason: {reason})</> : null}- </>- ),- }+ return describeWorkflowEmailSuspension(logItem)}if (logItem.activity == 'changed' || logItem.activity == 'updated') {- let changes: Description[] = []- let changeSuffix: Description = <>on {nameAndLink(logItem)}</>-- for (const change of logItem.detail.changes || []) {- if (!change?.field || !(change.field in TEAM_PROPERTIES_MAPPING)) {- continue // not all fields are describable- }-- const actionHandler = TEAM_PROPERTIES_MAPPING[change.field as keyof TeamType]- const processedChange = actionHandler(change)- if (processedChange === null) {- continue // some logs are indescribable- }-- const { description, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }-- if (suffix) {- changeSuffix = suffix- }- }-- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- }+ const changes = describeMappedChanges(+ logItem,+ TEAM_PROPERTIES_MAPPING,+ shortIdActivityLink(logItem, urls.notebook),+ <>on {shortIdActivityLink(logItem, urls.notebook)}</>+ )+ if (changes) {+ return changes}}- return defaultDescriber(logItem, asNotification, nameAndLink(logItem))+ return defaultDescriber(logItem, asNotification, shortIdActivityLink(logItem, urls.notebook))}diff --git a/products/actions/frontend/actionActivityDescriber.tsx b/products/actions/frontend/actionActivityDescriber.tsxindex 56135009e1a7..7c5a9472acad 100644--- a/products/actions/frontend/actionActivityDescriber.tsx+++ b/products/actions/frontend/actionActivityDescriber.tsx@@ -1,3 +1,5 @@+import { summarizeDescriptionChange } from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'+import { describeMappedChanges } from 'lib/components/ActivityLog/activityDescriptions/describeMappedChanges'import {ActivityChange,ActivityLogItem,@@ -5,10 +7,10 @@ import {ChangeMapping,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'-import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { Link } from 'lib/lemon-ui/Link'import { pluralize } from 'lib/utils/strings'@@ -35,6 +37,8 @@ const actionActionsMapping: Record<const after = change?.after as string | nullif (!before && after) {return {+ summary: summarizeDescriptionChange(change),+ preview: after,description: [<>added description <strong>"{after}"</strong>@@ -43,6 +47,8 @@ const actionActionsMapping: Record<}} else if (before && !after) {return {+ summary: summarizeDescriptionChange(change),+ preview: before,description: [<>removed description (was <strong>"{before}"</strong>)@@ -51,6 +57,8 @@ const actionActionsMapping: Record<}}return {+ summary: summarizeDescriptionChange(change),+ preview: after ?? undefined,description: [<>changed description from <strong>"{before}"</strong> to <strong>"{after}"</strong>@@ -164,6 +172,7 @@ export function actionActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'created') {return {+ summary: activityLogSummary(logItem, 'Created the action', nameAndLink(logItem)),description: (<><ActivityLogUserName logItem={logItem} /> created action {nameAndLink(logItem)}@@ -174,6 +183,7 @@ export function actionActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the action', nameAndLink(logItem)),description: (<><ActivityLogUserName logItem={logItem} /> deleted action {nameAndLink(logItem)}@@ -183,40 +193,14 @@ export function actionActivityDescriber(logItem: ActivityLogItem, asNotification}if (logItem.activity === 'updated') {- let changes: Description[] = []- let changeSuffix: Description = <>on action {nameAndLink(logItem)}</>-- for (const change of logItem.detail.changes || []) {- if (!change?.field || !actionActionsMapping[change.field]) {- continue- }-- const actionHandler = actionActionsMapping[change.field]- const processedChange = actionHandler(change, logItem)- if (processedChange === null) {- continue- }-- const { description, suffix } = processedChange- if (description) {- changes = changes.concat(description)- }-- if (suffix) {- changeSuffix = suffix- }- }-- if (changes.length) {- return {- description: (- <SentenceList- listParts={changes}- prefix={<ActivityLogUserName logItem={logItem} />}- suffix={changeSuffix}- />- ),- }+ const changes = describeMappedChanges(+ logItem,+ actionActionsMapping,+ nameAndLink(logItem),+ <>on action {nameAndLink(logItem)}</>+ )+ if (changes) {+ return changes}}diff --git a/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx b/products/ai_observability/frontend/prompts/promptActivityDescriber.tsxindex f13bb92e3608..90734a19bb3b 100644--- a/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx+++ b/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -15,47 +16,71 @@ function changeBefore(logItem: ActivityLogItem, field: string): string | null {return change?.before != null ? String(change.before) : null}+function describePromptPublished(logItem: ActivityLogItem, promptName: string): HumanizedChange {+ const version = changeAfter(logItem, 'version')+ const versionDescription = changeAfter(logItem, 'version_description')+ // Config contents are never logged; the change entry only records that it changed.+ const configChanged = logItem.detail?.changes?.some((change) => change.field === 'config')+ return {+ summary: activityLogSummary(+ logItem,+ `Published v${version ?? '?'}${configChanged ? ' (configuration changed)' : ''}`,+ promptName,+ versionDescription ?? undefined+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> published <b>v{version ?? '?'}</b> of prompt{' '}+ <b>{promptName}</b>+ {configChanged ? <> (configuration changed)</> : null}+ {versionDescription ? <>: "{versionDescription}"</> : null}+ </>+ ),+ }+}++function describePromptCreated(logItem: ActivityLogItem, promptName: string): HumanizedChange {+ const duplicatedFrom = changeAfter(logItem, 'duplicated_from')+ return {+ summary: activityLogSummary(+ logItem,+ duplicatedFrom ? `Created a copy of ${duplicatedFrom}` : 'Created the prompt',+ promptName+ ),+ description: duplicatedFrom ? (+ <>+ <ActivityLogUserName logItem={logItem} /> created prompt <b>{promptName}</b> as a copy of{' '}+ <b>{duplicatedFrom}</b>+ </>+ ) : (+ <>+ <ActivityLogUserName logItem={logItem} /> created prompt <b>{promptName}</b>+ </>+ ),+ }+}+// Lifecycle events (create/publish/archive/duplicate) for scope LLMPrompt, written by// log_llm_prompt_activity in backend activity_logging.py. detail.name is the prompt name.export function promptActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {const promptName = logItem?.detail?.name ?? ''if (logItem.activity === 'created') {- const duplicatedFrom = changeAfter(logItem, 'duplicated_from')- return {- description: duplicatedFrom ? (- <>- <ActivityLogUserName logItem={logItem} /> created prompt <b>{promptName}</b> as a copy of{' '}- <b>{duplicatedFrom}</b>- </>- ) : (- <>- <ActivityLogUserName logItem={logItem} /> created prompt <b>{promptName}</b>- </>- ),- }+ return describePromptCreated(logItem, promptName)}if (logItem.activity === 'published') {- const version = changeAfter(logItem, 'version')- const versionDescription = changeAfter(logItem, 'version_description')- // Config contents are never logged; the change entry only records that it changed.- const configChanged = logItem.detail?.changes?.some((change) => change.field === 'config')- return {- description: (- <>- <ActivityLogUserName logItem={logItem} /> published <b>v{version ?? '?'}</b> of prompt{' '}- <b>{promptName}</b>- {configChanged ? <> (configuration changed)</> : null}- {versionDescription ? <>: "{versionDescription}"</> : null}- </>- ),- }+ return describePromptPublished(logItem, promptName)}if (logItem.activity === 'archived') {const versionCount = changeBefore(logItem, 'version_count')return {+ summary: activityLogSummary(+ logItem,+ `Archived the prompt${versionCount ? ` (${versionCount} versions)` : ''}`,+ promptName+ ),description: (<><ActivityLogUserName logItem={logItem} /> archived prompt <b>{promptName}</b>@@ -68,6 +93,11 @@ export function promptActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'duplicated') {const duplicatedTo = changeAfter(logItem, 'duplicated_to')return {+ summary: activityLogSummary(+ logItem,+ duplicatedTo ? `Duplicated the prompt to ${duplicatedTo}` : 'Duplicated the prompt',+ promptName+ ),description: (<><ActivityLogUserName logItem={logItem} /> duplicated prompt <b>{promptName}</b>diff --git a/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsx b/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsxindex 4180949d3385..cd8feacdc104 100644--- a/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsx+++ b/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -21,6 +22,8 @@ function parseDetailName(logItem: ActivityLogItem): { promptName: string; labelNexport function promptLabelActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {const { promptName, labelName } = parseDetailName(logItem)const change = logItem.detail?.changes?.[0]+ const beforeVersion = String(change?.before ?? '?')+ const afterVersion = String(change?.after ?? '?')const onPrompt = promptName ? (<>{' '}@@ -30,10 +33,18 @@ export function promptLabelActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ `Created the label pointing at v${afterVersion}`,+ <>+ {labelName}+ {onPrompt}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> created label <b>{labelName}</b> pointing at{' '}- <b>v{String(change?.after ?? '?')}</b>+ <b>v{afterVersion}</b>{onPrompt}</>),@@ -42,10 +53,18 @@ export function promptLabelActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'updated') {return {+ summary: activityLogSummary(+ logItem,+ `Moved the label from v${beforeVersion} to v${afterVersion}`,+ <>+ {labelName}+ {onPrompt}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> moved label <b>{labelName}</b> from{' '}- <b>v{String(change?.before ?? '?')}</b> to <b>v{String(change?.after ?? '?')}</b>+ <b>v{beforeVersion}</b> to <b>v{afterVersion}</b>{onPrompt}</>),@@ -54,10 +73,18 @@ export function promptLabelActivityDescriber(logItem: ActivityLogItem, asNotificif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(+ logItem,+ `Removed the label (was pointing at v${beforeVersion})`,+ <>+ {labelName}+ {onPrompt}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> removed label <b>{labelName}</b> (was pointing at{' '}- <b>v{String(change?.before ?? '?')}</b>){onPrompt}+ <b>v{beforeVersion}</b>){onPrompt}</>),}diff --git a/products/alerts/frontend/components/activityDescriptions.tsx b/products/alerts/frontend/components/activityDescriptions.tsxindex 62458a81a838..0aa43f60e261 100644--- a/products/alerts/frontend/components/activityDescriptions.tsx+++ b/products/alerts/frontend/components/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -47,6 +48,17 @@ export function alertConfigurationActivityDescriber(if (logItem.detail?.type === 'alert_subscription_change') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Added subscriber {logItem.detail.context?.subscriber_name} (+ {logItem.detail.context?.subscriber_email})+ </>,+ <>+ {formattedName(logItem.detail.context?.alert_name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> added{' '}@@ -61,6 +73,14 @@ export function alertConfigurationActivityDescriber(}return {+ summary: activityLogSummary(+ logItem,+ 'Created the alert',+ <>+ {formattedName(logItem.detail.name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the alert {formattedName(logItem?.detail.name)}@@ -75,6 +95,17 @@ export function alertConfigurationActivityDescriber(if (logItem.detail?.type === 'alert_subscription_change') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Removed subscriber {logItem.detail.context?.subscriber_name} (+ {logItem.detail.context?.subscriber_email})+ </>,+ <>+ {formattedName(logItem.detail.context?.alert_name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> removed{' '}@@ -90,6 +121,14 @@ export function alertConfigurationActivityDescriber(const displayName = logItem.detail.name || 'Alert Configuration'return {+ summary: activityLogSummary(+ logItem,+ 'Deleted the alert',+ <>+ {displayName}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> deleted the alert: {displayName}@@ -104,6 +143,14 @@ export function alertConfigurationActivityDescriber(if (logItem.detail?.type === 'threshold_change') {return {+ summary: activityLogSummary(+ logItem,+ 'Updated the threshold',+ <>+ {formattedName(logItem.detail.context?.alert_name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated the <strong>threshold</strong> for alert{' '}@@ -115,6 +162,14 @@ export function alertConfigurationActivityDescriber(}return {+ summary: activityLogSummary(+ logItem,+ 'Updated the alert',+ <>+ {formattedName(logItem.detail.name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated the alert {formattedName(logItem?.detail.name)}diff --git a/products/annotations/frontend/activityDescriptions.tsx b/products/annotations/frontend/activityDescriptions.tsxindex 3cca919551da..9b60df91b1a8 100644--- a/products/annotations/frontend/activityDescriptions.tsx+++ b/products/annotations/frontend/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -78,6 +79,14 @@ export function annotationActivityDescriber(logItem: ActivityLogItem, asNotificaif (logItem.activity == 'created') {const contextDesc = getContextDescription(logItem?.detail?.context)return {+ summary: activityLogSummary(+ logItem,+ 'Created the annotation',+ <>+ {nameOrLinkToAnnotation(logItem?.item_id, logItem?.detail.name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the annotation "@@ -97,6 +106,7 @@ export function annotationActivityDescriber(logItem: ActivityLogItem, asNotificaconst contextDesc = getContextDescription(logItem?.detail?.context)return {+ summary: activityLogSummary(logItem, 'Deleted the annotation', <>Annotation{contextDesc}</>, displayName),description: (<><ActivityLogUserName logItem={logItem} /> deleted the annotation: {displayName}@@ -109,6 +119,14 @@ export function annotationActivityDescriber(logItem: ActivityLogItem, asNotificaif (logItem.activity == 'updated') {const contextDesc = getContextDescription(logItem?.detail?.context)return {+ summary: activityLogSummary(+ logItem,+ 'Updated the annotation',+ <>+ {nameOrLinkToAnnotation(logItem?.item_id, logItem?.detail.name)}+ {contextDesc}+ </>+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated the annotation:{' '}diff --git a/products/canvas/frontend/activityDescriber.tsx b/products/canvas/frontend/activityDescriber.tsxindex c41b1adca955..664856409023 100644--- a/products/canvas/frontend/activityDescriber.tsx+++ b/products/canvas/frontend/activityDescriber.tsx@@ -4,6 +4,7 @@ import {ActivityLogUserName,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -97,6 +98,53 @@ const canvasUpdateFieldCopy = (change: ActivityChange): Description | null => {return null}+function describeCanvasPublished(+ logItem: ActivityLogItem,+ actor: JSX.Element,+ canvasName: JSX.Element+): HumanizedChange {+ const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')+ const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []+ return {+ summary: activityLogSummary(+ logItem,+ <>+ Published the canvas+ {parts.length > 0 && <> and changed its declared capabilities:{inlineOrList(parts)}</>}+ </>,+ canvasName+ ),+ description: (+ <>+ {actor} published canvas {canvasName}+ {parts.length === 1 ? <> and</> : null}+ {parts.length > 1 ? <> and changed its declared capabilities:</> : null}+ {parts.length > 0 ? inlineOrList(parts) : null}+ </>+ ),+ }+}++function describeCanvasDrafted(logItem: ActivityLogItem, actor: JSX.Element, canvasName: JSX.Element): HumanizedChange {+ const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')+ const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []+ return {+ summary: activityLogSummary(+ logItem,+ <>Drafted a new version{parts.length > 0 && <> with capability changes:{inlineOrList(parts)}</>}</>,+ canvasName+ ),+ description: (+ <>+ {actor} drafted a new version of canvas {canvasName}+ {parts.length === 1 ? <> that</> : null}+ {parts.length > 1 ? <> that changes its declared capabilities:</> : null}+ {parts.length > 0 ? inlineOrList(parts) : null}+ </>+ ),+ }+}+export function canvasActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope !== 'Canvas') {console.error('canvas describer received a non-canvas activity')@@ -107,37 +155,16 @@ export function canvasActivityDescriber(logItem: ActivityLogItem, asNotificationconst canvasName = <strong>{logItem.detail.name || 'Untitled canvas'}</strong>if (logItem.activity === 'published') {- const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')- const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []- return {- description: (- <>- {actor} published canvas {canvasName}- {parts.length === 1 ? <> and</> : null}- {parts.length > 1 ? <> and changed its declared capabilities:</> : null}- {parts.length > 0 ? inlineOrList(parts) : null}- </>- ),- }+ return describeCanvasPublished(logItem, actor, canvasName)}if (logItem.activity === 'drafted') {- const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')- const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []- return {- description: (- <>- {actor} drafted a new version of canvas {canvasName}- {parts.length === 1 ? <> that</> : null}- {parts.length > 1 ? <> that changes its declared capabilities:</> : null}- {parts.length > 0 ? inlineOrList(parts) : null}- </>- ),- }+ return describeCanvasDrafted(logItem, actor, canvasName)}if (logItem.activity === 'reverted') {return {+ summary: activityLogSummary(logItem, 'Reverted to an earlier version', canvasName),description: (<>{actor} reverted canvas {canvasName} to an earlier version@@ -150,6 +177,7 @@ export function canvasActivityDescriber(logItem: ActivityLogItem, asNotificationconst parts = (logItem.detail.changes || []).map(canvasUpdateFieldCopy).filter(Boolean) as Description[]if (parts.length > 0) {return {+ summary: activityLogSummary(logItem, <>Updated the canvas:{inlineOrList(parts)}</>, canvasName),description: (<>{actor} updated canvas {canvasName}:{inlineOrList(parts)}@@ -162,6 +190,7 @@ export function canvasActivityDescriber(logItem: ActivityLogItem, asNotificationconst buildCopy = BUILD_ACTIVITY_COPY[logItem.activity]if (buildCopy) {return {+ summary: activityLogSummary(logItem, `${buildCopy} the canvas`, canvasName),description: (<>{actor} {buildCopy} canvas {canvasName}diff --git a/products/conversations/frontend/activityDescriber.test.tsx b/products/conversations/frontend/activityDescriber.test.tsxindex 0ff83df1d584..3db21d6f9620 100644--- a/products/conversations/frontend/activityDescriber.test.tsx+++ b/products/conversations/frontend/activityDescriber.test.tsx@@ -66,6 +66,13 @@ describe('ticketActivityDescriber', () => {const text = getTextContent(result)expect(text).toContain('workflow-actor:flow-123')expect(text).toContain('changed status')+ expect(render(<>{result.summary?.actor}</>).container.textContent).toBe('workflow-actor:flow-123')+ expect(render(<>{result.summary?.action}</>).container.textContent).toContain('changed status')+ expect(+ render(<>{result.summary?.target}</>)+ .container.querySelector('a')+ ?.getAttribute('href')+ ).toContain('/2043')expect(text).not.toContain('PostHog')})diff --git a/products/conversations/frontend/activityDescriber.tsx b/products/conversations/frontend/activityDescriber.tsxindex 503a79e65a01..1d4da9349ea0 100644--- a/products/conversations/frontend/activityDescriber.tsx+++ b/products/conversations/frontend/activityDescriber.tsx@@ -5,8 +5,10 @@ import {ChangeMapping,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { TZLabel } from 'lib/components/TZLabel'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -173,6 +175,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'created') {return {+ summary: activityLogSummary(logItem, 'Created the ticket', ticketLink, undefined, actor),description: (<>{actor} created {ticketLink}@@ -190,6 +193,13 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotificationrole?: { name?: string }} | nullreturn {+ summary: activityLogSummary(+ logItem,+ <>Assigned to {formatAssignee(after)}</>,+ ticketLink,+ undefined,+ actor+ ),description: (<>{actor} assigned {ticketLink} to <strong>{formatAssignee(after)}</strong>@@ -215,6 +225,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotificationif (allChanges.length === 1) {return {+ summary: activityLogSummary(logItem, allChanges[0], ticketLink, undefined, actor),description: (<>{actor} {allChanges[0]} on {ticketLink}@@ -225,6 +236,13 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotificationif (allChanges.length > 1) {return {+ summary: activityLogSummary(+ logItem,+ <SentenceList listParts={allChanges} />,+ ticketLink,+ undefined,+ actor+ ),description: (<>{actor} made changes to {ticketLink}:diff --git a/products/data_warehouse/frontend/shared/components/activityDescriptions.tsx b/products/data_warehouse/frontend/shared/components/activityDescriptions.tsxindex b0dcb72e61e8..f93f52625154 100644--- a/products/data_warehouse/frontend/shared/components/activityDescriptions.tsx+++ b/products/data_warehouse/frontend/shared/components/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -75,6 +76,7 @@ export function externalDataSourceActivityDescriber(if (logItem.activity == 'created') {if (logItem.scope === ActivityScope.EXTERNAL_DATA_SCHEMA) {return {+ summary: activityLogSummary(logItem, 'Created the schema', displayName),description: (<><ActivityLogUserName logItem={logItem} /> created schema <strong>{displayName}</strong>@@ -83,6 +85,7 @@ export function externalDataSourceActivityDescriber(}}return {+ summary: activityLogSummary(logItem, 'Created the source', displayName),description: (<><ActivityLogUserName logItem={logItem} /> created source <strong>{displayName}</strong>@@ -98,6 +101,7 @@ export function externalDataSourceActivityDescriber() {if (logItem.scope === ActivityScope.EXTERNAL_DATA_SCHEMA) {return {+ summary: activityLogSummary(logItem, 'Deleted the schema', displayName),description: (<><ActivityLogUserName logItem={logItem} /> deleted schema <strong>{displayName}</strong>@@ -106,6 +110,7 @@ export function externalDataSourceActivityDescriber(}}return {+ summary: activityLogSummary(logItem, 'Deleted the source', displayName),description: (<><ActivityLogUserName logItem={logItem} /> deleted source <strong>{displayName}</strong>@@ -121,6 +126,7 @@ export function externalDataSourceActivityDescriber(if (enabledChange && changes.length === 1) {const verb = enabledChange.after ? 'enabled' : 'disabled'return {+ summary: activityLogSummary(logItem, `${verb} the schema`, displayName),description: (<><ActivityLogUserName logItem={logItem} /> {verb} schema <strong>{displayName}</strong>@@ -129,6 +135,7 @@ export function externalDataSourceActivityDescriber(}}return {+ summary: activityLogSummary(logItem, 'Updated the schema', displayName),description: (<><ActivityLogUserName logItem={logItem} /> updated schema <strong>{displayName}</strong>@@ -137,6 +144,7 @@ export function externalDataSourceActivityDescriber(}}return {+ summary: activityLogSummary(logItem, 'Updated the source', displayName),description: (<><ActivityLogUserName logItem={logItem} /> updated source <strong>{displayName}</strong>diff --git a/products/endpoints/frontend/activityDescriber.tsx b/products/endpoints/frontend/activityDescriber.tsxindex 3647f2424bb7..7956cb8a8e6b 100644--- a/products/endpoints/frontend/activityDescriber.tsx+++ b/products/endpoints/frontend/activityDescriber.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { Link } from 'lib/lemon-ui/Link'@@ -35,6 +36,13 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity === 'created') {return {+ summary: activityLogSummary(+ logItem,+ <>+ Created the endpoint (<VersionLink name={endpointName} version={1} />)+ </>,+ <EndpointLink name={endpointName} />+ ),description: (<><ActivityLogUserName logItem={logItem} /> created endpoint <EndpointLink name={endpointName} /> (@@ -47,6 +55,7 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the endpoint', endpointName),description: (<><ActivityLogUserName logItem={logItem} /> deleted endpoint <strong>{endpointName}</strong>.@@ -57,6 +66,13 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity === 'version_created' && version !== undefined) {return {+ summary: activityLogSummary(+ logItem,+ <>+ Created version <VersionLink name={endpointName} version={version} />+ </>,+ <EndpointLink name={endpointName} />+ ),description: (<><ActivityLogUserName logItem={logItem} /> created version{' '}@@ -69,6 +85,13 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity === 'version_updated' && version !== undefined) {return {+ summary: activityLogSummary(+ logItem,+ <>+ Updated version <VersionLink name={endpointName} version={version} />+ </>,+ <EndpointLink name={endpointName} />+ ),description: (<><ActivityLogUserName logItem={logItem} /> updated{' '}@@ -81,6 +104,7 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity === 'updated') {return {+ summary: activityLogSummary(logItem, 'Updated the endpoint', <EndpointLink name={endpointName} />),description: (<><ActivityLogUserName logItem={logItem} /> updated endpoint <EndpointLink name={endpointName} />.diff --git a/products/error_tracking/frontend/components/ActivityDescriber.tsx b/products/error_tracking/frontend/components/ActivityDescriber.tsxindex 59bdf39db1a8..e4a0b0c0ab13 100644--- a/products/error_tracking/frontend/components/ActivityDescriber.tsx+++ b/products/error_tracking/frontend/components/ActivityDescriber.tsx@@ -3,13 +3,14 @@ import { useEffect } from 'react'import { Link } from '@posthog/lemon-ui'+import { describeMappedChanges } from 'lib/components/ActivityLog/activityDescriptions/describeMappedChanges'import {ActivityChange,ActivityLogItem,ActivityLogUserName,ChangeMapping,- Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'@@ -69,9 +70,6 @@ const errorTrackingIssueActionsMapping: Record<const { before, after } = change || {}const unassignedBefore = before === nullconst unassignedAfter = after === null- if (unassignedBefore && unassignedAfter) {- return null- }if (objectsEqual(before, after)) {return null}@@ -82,24 +80,48 @@ const errorTrackingIssueActionsMapping: Record<const wasAssigned = unassignedBefore && !unassignedAfterconst wasUnassigned = !unassignedBefore && unassignedAfter- return {- description: [- wasAssigned ? (+ if (wasAssigned) {+ return {+ summary: [+ <>+ Assigned to <AssigneeRenderer assignee={after as ErrorTrackingIssueAssignee} />+ </>,+ ],+ description: [<>assigned {nameAndLink(logItem)} to{' '}<AssigneeRenderer assignee={after as ErrorTrackingIssueAssignee} />- </>- ) : wasUnassigned ? (+ </>,+ ],+ }+ }+ if (wasUnassigned) {+ return {+ summary: [+ <>+ Unassigned from <AssigneeRenderer assignee={before as ErrorTrackingIssueAssignee} />+ </>,+ ],+ description: [<>unassigned {nameAndLink(logItem)} from{' '}<AssigneeRenderer assignee={before as ErrorTrackingIssueAssignee} />- </>- ) : (- <>- changed assignee from <AssigneeRenderer assignee={before as ErrorTrackingIssueAssignee} /> to{' '}- <AssigneeRenderer assignee={after as ErrorTrackingIssueAssignee} /> on {nameAndLink(logItem)}- </>- ),+ </>,+ ],+ }+ }+ return {+ summary: [+ <>+ Changed assignee from <AssigneeRenderer assignee={before as ErrorTrackingIssueAssignee} /> to{' '}+ <AssigneeRenderer assignee={after as ErrorTrackingIssueAssignee} />+ </>,+ ],+ description: [+ <>+ changed assignee from <AssigneeRenderer assignee={before as ErrorTrackingIssueAssignee} /> to{' '}+ <AssigneeRenderer assignee={after as ErrorTrackingIssueAssignee} /> on {nameAndLink(logItem)}+ </>,],}},@@ -109,6 +131,11 @@ const errorTrackingIssueActionsMapping: Record<return null}return {+ summary: [+ <>+ Changed status from {String(before)} to {String(after)}+ </>,+ ],description: [<>changed status of {nameAndLink(logItem)} from <strong>{String(before)}</strong> to{' '}@@ -128,6 +155,62 @@ const errorTrackingIssueActionsMapping: Record<cohort: () => null,}+function describeIssueMergeOrSplit(logItem: ActivityLogItem): HumanizedChange {+ const relatedIssueIds = relatedIssueIdsForLogItem(logItem)+ const count = relatedIssueIds.length+ return {+ summary: activityLogSummary(+ logItem,+ logItem.activity === 'merged' ? (+ <>Merged {count === 1 ? 'an issue' : `${count} issues`} into this issue</>+ ) : (+ <>+ Split into{' '}+ {count > 0 ? (+ <SentenceList+ listParts={relatedIssueIds.map((issueId, index) => (+ <Link key={issueId} to={urls.errorTrackingIssue(issueId)}>+ {count === 1 ? 'a new issue' : `new issue ${index + 1}`}+ </Link>+ ))}+ />+ ) : (+ 'new issues'+ )}+ </>+ ),+ nameAndLink(logItem)+ ),+ description: (+ <SentenceList+ listParts={[+ logItem.activity == 'merged' ? (+ <>+ merged {count === 1 ? 'an issue' : `${count} issues`} into {nameAndLink(logItem)}+ </>+ ) : (+ <>+ split {nameAndLink(logItem)} into{' '}+ {count > 0 ? (+ <SentenceList+ listParts={relatedIssueIds.map((issueId, index) => (+ <Link key={issueId} to={urls.errorTrackingIssue(issueId)}>+ {count === 1 ? 'a new issue' : `new issue ${index + 1}`}+ </Link>+ ))}+ />+ ) : (+ 'new issues'+ )}+ </>+ ),+ ]}+ prefix={<ActivityLogUserName logItem={logItem} />}+ />+ ),+ }+}+export function ActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope !== ActivityScope.ERROR_TRACKING_ISSUE) {console.error('describer received a non-error tracking activity')@@ -135,65 +218,13 @@ export function ActivityDescriber(logItem: ActivityLogItem, asNotification?: boo}if (logItem.activity == 'merged' || logItem.activity == 'split') {- const relatedIssueIds = relatedIssueIdsForLogItem(logItem)- const count = relatedIssueIds.length- return {- description: (- <SentenceList- listParts={[- logItem.activity == 'merged' ? (- <>- merged {count === 1 ? 'an issue' : `${count} issues`} into {nameAndLink(logItem)}- </>- ) : (- <>- split {nameAndLink(logItem)} into{' '}- {count > 0 ? (- <SentenceList- listParts={relatedIssueIds.map((issueId, index) => (- <Link key={issueId} to={urls.errorTrackingIssue(issueId)}>- {count === 1 ? 'a new issue' : `new issue ${index + 1}`}- </Link>- ))}- />- ) : (- 'new issues'- )}- </>- ),- ]}- prefix={<ActivityLogUserName logItem={logItem} />}- />- ),- }+ return describeIssueMergeOrSplit(logItem)}if (logItem.activity == 'updated' || logItem.activity == 'assigned') {- let changes: Description[] = []-- for (const change of logItem.detail.changes || []) {- const field = change.field as keyof ErrorTrackingRelationalIssue-- if (!change?.field || !errorTrackingIssueActionsMapping[field]) {- continue // not all fields are describable- }-- const actionHandler = errorTrackingIssueActionsMapping[field]- const processedChange = actionHandler(change, logItem)- if (processedChange === null) {- continue // unexpected log from backend is indescribable- }-- const { description } = processedChange- if (description) {- changes = changes.concat(description)- }- }-- if (changes.length) {- return {- description: <SentenceList listParts={changes} prefix={<ActivityLogUserName logItem={logItem} />} />,- }+ const changes = describeMappedChanges(logItem, errorTrackingIssueActionsMapping, nameAndLink(logItem), null)+ if (changes) {+ return changes}}diff --git a/products/groups/frontend/activityDescriptions.tsx b/products/groups/frontend/activityDescriptions.tsxindex 60491408514e..9e1b49784907 100644--- a/products/groups/frontend/activityDescriptions.tsx+++ b/products/groups/frontend/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'@@ -13,6 +14,11 @@ export function groupActivityDescriber(logItem: ActivityLogItem, asNotification?if (logItem.activity === 'update_property') {return {+ summary: activityLogSummary(+ logItem,+ `${logItem.detail?.changes?.[0]?.action || 'changed'} the property`,+ <code>{logItem.detail?.name}</code>+ ),description: (<><ActivityLogUserName logItem={logItem} /> {logItem.detail?.changes?.[0]?.action || 'changed'} the{' '}diff --git a/products/persons/frontend/activityDescriptions.tsx b/products/persons/frontend/activityDescriptions.tsxindex 01891194b3c6..1d2d450bd5a5 100644--- a/products/persons/frontend/activityDescriptions.tsx+++ b/products/persons/frontend/activityDescriptions.tsx@@ -2,6 +2,7 @@ import {ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'@@ -11,6 +12,44 @@ import { urls } from 'scenes/urls'import { PersonDisplay } from './components/PersonDisplay'+function describePersonSplit(logItem: ActivityLogItem): HumanizedChange | null {+ const after = logItem.detail.changes?.[0].after+ const distinctIds = isObject(after) ? after.distinct_ids : undefined++ if (Array.isArray(distinctIds)) {+ const normalizedDistinctIds = distinctIds.filter((id): id is string => typeof id === 'string')+ return {+ summary: activityLogSummary(+ logItem,+ <SentenceList+ prefix="Split the person into"+ listParts={normalizedDistinctIds.map((distinctId) => (+ <Link key={distinctId} to={urls.personByDistinctId(distinctId)}>+ {distinctId}+ </Link>+ ))}+ />,+ logItem.detail.name || 'Person'+ ),+ description: (+ <SentenceList+ prefix={+ <>+ <ActivityLogUserName logItem={logItem} /> split this person into+ </>+ }+ listParts={normalizedDistinctIds.map((di) => (+ <span key={di} className="highlighted-activity">+ <Link to={urls.personByDistinctId(di)}>{di}</Link>+ </span>+ ))}+ />+ ),+ }+ }+ return null+}+export function personActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'Person') {console.error('person describer received a non-person activity')@@ -19,6 +58,7 @@ export function personActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the person', logItem.detail.name),description: (<><ActivityLogUserName logItem={logItem} /> deleted the person: {logItem.detail.name}@@ -33,6 +73,7 @@ export function personActivityDescriber(logItem: ActivityLogItem, asNotification// only report here that a certain user has manually edited propertiesreturn {+ summary: activityLogSummary(logItem, "Edited the person's properties", logItem.detail.name || 'Person'),description: (<><ActivityLogUserName logItem={logItem} /> edited this person's properties@@ -43,6 +84,17 @@ export function personActivityDescriber(logItem: ActivityLogItem, asNotificationif (logItem.activity === 'people_merged_into') {if (logItem.detail.merge?.source) {return {+ summary: activityLogSummary(+ logItem,+ <SentenceList+ prefix="Merged"+ listParts={logItem.detail.merge.source.map((person, index) => (+ <PersonDisplay key={person.id || person.uuid || index} person={person} />+ ))}+ suffix="into this person"+ />,+ logItem.detail.name || 'Person'+ ),description: (<SentenceListprefix={@@ -63,27 +115,9 @@ export function personActivityDescriber(logItem: ActivityLogItem, asNotification}if (logItem.activity === 'split_person') {- const after = logItem.detail.changes?.[0].after- const distinctIds = isObject(after) ? after.distinct_ids : undefined-- if (Array.isArray(distinctIds)) {- const normalizedDistinctIds = distinctIds.filter((id): id is string => typeof id === 'string')- return {- description: (- <SentenceList- prefix={- <>- <ActivityLogUserName logItem={logItem} /> split this person into- </>- }- listParts={normalizedDistinctIds.map((di) => (- <span key={di} className="highlighted-activity">- <Link to={urls.personByDistinctId(di)}>{di}</Link>- </span>- ))}- />- ),- }+ const result = describePersonSplit(logItem)+ if (result) {+ return result}}diff --git a/products/signals/frontend/activityDescriber.tsx b/products/signals/frontend/activityDescriber.tsxindex 518fa702264e..50502614a88e 100644--- a/products/signals/frontend/activityDescriber.tsx+++ b/products/signals/frontend/activityDescriber.tsx@@ -1,6 +1,7 @@import {ActivityLogItem,HumanizedChange,+ activityLogSummary,defaultDescriber,userNameForLogItem,} from 'lib/components/ActivityLog/humanizeActivity'@@ -19,11 +20,17 @@ export function signalScoutConfigActivityDescriber(const user = userNameForLogItem(logItem)if (logItem.activity === 'created') {- return { description: `${user} created scout ${name}` }+ return {+ description: `${user} created scout ${name}`,+ summary: activityLogSummary(logItem, 'Created the scout', name),+ }}if (logItem.activity === 'deleted') {- return { description: `${user} deleted scout ${name}` }+ return {+ description: `${user} deleted scout ${name}`,+ summary: activityLogSummary(logItem, 'Deleted the scout', name),+ }}if (logItem.activity === 'updated') {@@ -33,10 +40,16 @@ export function signalScoutConfigActivityDescriber(// Single-field enable/disable toggle gets a dedicated phrasing.if (enabledChange && changes.length === 1) {const verb = enabledChange.after ? 'enabled' : 'disabled'- return { description: `${user} ${verb} scout ${name}` }+ return {+ description: `${user} ${verb} scout ${name}`,+ summary: activityLogSummary(logItem, `${verb} the scout`, name),+ }}- return { description: `${user} updated scout ${name}` }+ return {+ description: `${user} updated scout ${name}`,+ summary: activityLogSummary(logItem, 'Updated the scout', name),+ }}return defaultDescriber(logItem, asNotification, name)diff --git a/products/stamphog/frontend/activityDescriber.tsx b/products/stamphog/frontend/activityDescriber.tsxindex 502153c2b8ce..5b672dce3d67 100644--- a/products/stamphog/frontend/activityDescriber.tsx+++ b/products/stamphog/frontend/activityDescriber.tsx@@ -4,6 +4,7 @@ import {ActivityLogUserName,Description,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'@@ -64,6 +65,7 @@ export function stamphogRepoConfigActivityDescriber(// A row created through the API has no installation until a sync binds it.const verb = logItem.detail.type === 'connected' ? 'connected' : 'added'return {+ summary: activityLogSummary(logItem, `${verb} the repository`, repository),description: (<>{actor} {verb} {repository}@@ -80,6 +82,7 @@ export function stamphogRepoConfigActivityDescriber(const webhookAction = logItem.detail.trigger?.payload?.actionconst reason = typeof webhookAction === 'string' ? WEBHOOK_REASON[webhookAction] : undefinedreturn {+ summary: activityLogSummary(logItem, <SentenceList listParts={parts} />, repository, reason),description: (<SentenceListlistParts={parts}diff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsxindex 3267a98a0090..433758121fb5 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx@@ -1,9 +1,12 @@import {+ ActivityChange,ActivityLogItem,ActivityLogUserName,HumanizedChange,+ activityLogSummary,defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -77,6 +80,91 @@ function processArrayChanges<T extends ArrayChangeItem>(return changes}+function describeWorkflowItems(change: ActivityChange, itemType: 'action' | 'variable'): JSX.Element[] {+ const before = asItemArray(change.before)+ const after = asItemArray(change.after)+ if (!before || !after) {+ return [<>updated {change.field}</>]+ }+ return itemType === 'action'+ ? processArrayChanges(+ before,+ after,+ (item) => item.id || '',+ (item) => item.name || item.id || 'unnamed',+ itemType+ )+ : processArrayChanges(+ before,+ after,+ (item) => item.key || '',+ (item) => item.key || item.label || 'unnamed',+ itemType+ )+}++function describeWorkflowField(change: ActivityChange): JSX.Element[] {+ switch (change.field) {+ case 'name':+ return [+ <>+ renamed from <strong>{String(change.before)}</strong> to <strong>{String(change.after)}</strong>+ </>,+ ]+ case 'description':+ return [<>updated description</>]+ case 'status':+ return [<>{`${change.after === 'active' ? 'enabled' : 'disabled'} the workflow`}</>]+ case 'actions':+ return describeWorkflowItems(change, 'action')+ case 'variables':+ return describeWorkflowItems(change, 'variable')+ default:+ return [<>updated {change.field}</>]+ }+}++function describeWorkflowUpdate(logItem: ActivityLogItem): HumanizedChange {+ const objectNoun = 'workflow'+ const verb = logItem.activity == 'published' ? 'published' : 'updated'+ const changes: JSX.Element[] = []+ let preview: string | undefined+ for (const change of logItem.detail.changes ?? []) {+ if (change.field === 'description') {+ preview = typeof change.after === 'string' ? change.after : undefined+ }+ changes.push(...describeWorkflowField(change))+ }+ const workflowName = nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)++ return {+ summary: activityLogSummary(+ logItem,+ <SentenceList+ listParts={+ logItem.activity === 'published'+ ? [`Published the ${objectNoun}`, ...changes]+ : changes.length+ ? changes+ : [`Updated the ${objectNoun}`]+ }+ />,+ workflowName,+ preview+ ),+ description: (+ <div>+ <ActivityLogUserName logItem={logItem} /> {verb} the {objectNoun}: {workflowName}+ <ul className="ml-5 list-disc">+ {changes.map((c, i) => (+ <li key={i}>{c}</li>+ ))}+ </ul>+ </div>+ ),+ }+}+export function workflowActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'HogFlow') {console.error('Workflow describer received a non-HogFlow activity')@@ -87,6 +175,11 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity == 'created') {return {+ summary: activityLogSummary(+ logItem,+ 'Created the workflow',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> created the {objectNoun}:{' '}@@ -98,6 +191,7 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity == 'deleted') {return {+ summary: activityLogSummary(logItem, 'Deleted the workflow', logItem.detail.name || 'Workflow'),description: (<><ActivityLogUserName logItem={logItem} /> deleted the {objectNoun}: {logItem.detail.name}@@ -108,6 +202,11 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity == 'revision_restored') {return {+ summary: activityLogSummary(+ logItem,+ 'Staged an earlier version for review',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> restored a past version into the staged draft of the{' '}@@ -119,6 +218,11 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity == 'draft_discarded') {return {+ summary: activityLogSummary(+ logItem,+ 'Discarded the staged draft',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> discarded the staged draft of the {objectNoun}:{' '}@@ -130,6 +234,11 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificatiif (logItem.activity == 'email_sending_resumed') {return {+ summary: activityLogSummary(+ logItem,+ 'Resumed email sending',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),description: (<><ActivityLogUserName logItem={logItem} /> resumed email sending for the {objectNoun}:{' '}@@ -140,87 +249,7 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificati}if (logItem.activity == 'updated' || logItem.activity == 'published') {- const verb = logItem.activity == 'published' ? 'published' : 'updated'- const changes: JSX.Element[] = []- for (const change of logItem.detail.changes ?? []) {- switch (change.field) {- case 'name': {- changes.push(- <>- renamed from <strong>{String(change.before)}</strong> to{' '}- <strong>{String(change.after)}</strong>- </>- )- break- }- case 'description': {- changes.push(<>updated description</>)- break- }- case 'status': {- const statusChange = change.after === 'active' ? 'enabled' : 'disabled'- changes.push(<>{`${statusChange} the ${objectNoun}`}</>)- break- }- case 'actions': {- const actionsBefore = asItemArray(change.before)- const actionsAfter = asItemArray(change.after)- if (!actionsBefore || !actionsAfter) {- changes.push(<>updated {change.field}</>)- break- }- changes.push(- ...processArrayChanges(- actionsBefore,- actionsAfter,- (a) => a.id || '',- (a) => a.name || a.id || 'unnamed',- 'action'- )- )- break- }- case 'variables': {- const variablesBefore = asItemArray(change.before)- const variablesAfter = asItemArray(change.after)- if (!variablesBefore || !variablesAfter) {- changes.push(<>updated {change.field}</>)- break- }- changes.push(- ...processArrayChanges(- variablesBefore,- variablesAfter,- (v) => v.key || '',- (v) => v.key || v.label || 'unnamed',- 'variable'- )- )- break- }- case 'trigger':- case 'edges': {- changes.push(<>updated {change.field}</>)- break- }- default:- changes.push(<>updated {change.field}</>)- }- }- const workflowName = nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)-- return {- description: (- <div>- <ActivityLogUserName logItem={logItem} /> {verb} the {objectNoun}: {workflowName}- <ul className="ml-5 list-disc">- {changes.map((c, i) => (- <li key={i}>{c}</li>- ))}- </ul>- </div>- ),- }+ return describeWorkflowUpdate(logItem)}return defaultDescriber(logItem, asNotification, nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name))}