Skip to content

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

feat(today): test recent and frequent jump back ranking (#123868)

Shy Alter7bbf0d024db2
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f721cac84c30..cc2cd50ecf3e 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -7051,6 +7051,19 @@ export type FileSystemDestroyParams = {
recursive?: boolean
}
+export type FileSystemFrequentListParams = {
+ /**
+ * Maximum number of frequently viewed items to return.
+ * @minimum 1
+ * @maximum 20
+ */
+ limit?: number
+ /**
+ * A search term.
+ */
+ search?: string
+}
+
export type FileSystemSearchRetrieveParams = {
/**
* Maximum number of results to return, best first.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index f10262f8a804..8ce22cc15922 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -36,6 +36,7 @@ import type {
ExportsListParams,
FileSystemApi,
FileSystemDestroyParams,
+ FileSystemFrequentListParams,
FileSystemHomeFolderApi,
FileSystemListParams,
FileSystemRankedSearchResponseApi,
@@ -1946,6 +1947,36 @@ export const fileSystemCountByPathCreate = async (
})
}
+export const getFileSystemFrequentListUrl = (projectId: string, params?: FileSystemFrequentListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/file_system/frequent/?${stringifiedParams}`
+ : `/api/projects/${projectId}/file_system/frequent/`
+}
+
+/**
+ * @summary List frequently viewed files
+ */
+export const fileSystemFrequentList = async (
+ projectId: string,
+ params?: FileSystemFrequentListParams,
+ options?: RequestInit
+): Promise<FileSystemApi[]> => {
+ return apiMutator<FileSystemApi[]>(getFileSystemFrequentListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getFileSystemHomeFolderCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/file_system/home_folder/`
}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d7faf9a6af30..8d93493b50e6 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -545,6 +545,7 @@ export const FEATURE_FLAGS = {
TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. control changes nothing, banner suggests the right tab, promote moves the predicted group to the top of the All tab
TAXONOMIC_FILTER_VALUE_SEARCH_GATING: 'taxonomic-filter-value-search-gating', // owner: @pauldambra
TEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cards
+ TODAY_JUMP_BACK_RANKING: 'today-jump-back-ranking',
TODAY_PULSE_RANKING: 'today-pulse-ranking',
TODAY_RAIL_NAV: 'today-rail-nav', // owner: @k11kirky, replaces the left navigation with a rail (Home, Spaces, Library, Tools) and makes the Today page the homepage
TODAY_REPORT_JEV: 'today-report-jev', // owner: @puemos, asks the decision model to label the problem, cause and fix in a Today report, to mark the numbers a source states, and to pick the code excerpt a finding describes
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index 9ccd93135209..980e0d8771a7 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -912,6 +912,7 @@ const meta: Meta = {
const results = type ? LIBRARY.filter((entry) => entry.type === type) : LIBRARY
return [200, { results, count: results.length }]
},
+ '/api/projects/:team_id/file_system/frequent/': [],
'/api/environments/:team_id/file_system/unfiled/': { results: [], count: 0 },
'/api/projects/:team_id/canvases/canvas-building/': VIEW_CANVASES[1],
'/api/projects/:team_id/tasks/task-canvas-building/': {
@@ -972,6 +973,52 @@ type Story = StoryObj<{}>
export const Home: Story = { decorators: [keepNumbers([])] }
+export const HomeWithFrequentItems: Story = {
+ parameters: {
+ featureFlags: {
+ [FEATURE_FLAGS.TODAY_RAIL_NAV]: true,
+ [FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS]: true,
+ [FEATURE_FLAGS.TODAY_JUMP_BACK_RANKING]: 'test',
+ },
+ },
+ decorators: [
+ keepNumbers([]),
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/file_system/frequent/': [
+ {
+ id: 'fs-frequent-1',
+ path: 'Dashboards/Daily operations',
+ type: 'dashboard',
+ ref: '81',
+ href: '/dashboard/81',
+ last_viewed_at: '2026-09-27T09:00:00Z',
+ },
+ {
+ id: 'fs-frequent-2',
+ path: 'Notebooks/Weekly review',
+ type: 'notebook',
+ ref: 'weekly-review',
+ href: '/notebooks/weekly-review',
+ last_viewed_at: '2026-09-21T09:00:00Z',
+ },
+ ],
+ },
+ }),
+ ],
+}
+
+export const HomeWithRecentRanking: Story = {
+ ...HomeWithFrequentItems,
+ parameters: {
+ featureFlags: {
+ [FEATURE_FLAGS.TODAY_RAIL_NAV]: true,
+ [FEATURE_FLAGS.POSTHOG_CODE_TASK_ANALYSIS]: true,
+ [FEATURE_FLAGS.TODAY_JUMP_BACK_RANKING]: 'control',
+ },
+ },
+}
+
export const HomeWithKeptNumbers: Story = {
decorators: [
keepNumbers([
diff --git a/frontend/src/scenes/project-homepage/today/TodayRecents.tsx b/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
index c69438d05048..88832d47ab82 100644
--- a/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
@@ -4,8 +4,8 @@ import { useId, useMemo } from 'react'
import { IconChevronDown } from '@posthog/icons'
+import { TZLabel } from 'lib/components/TZLabel'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { capitalizeFirstLetter } from 'lib/utils/strings'
import { todayObjectGlanceLogic } from '~/layout/today/todayObjectGlanceLogic'
import { TodayObjectIcon } from '~/layout/today/TodayObjectIcon'
@@ -18,8 +18,17 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'
import { TodayHomeHeading } from './TodayHomeHeading'
import { RECENT_OBJECT_COUNT, todayLogic } from './todayLogic'
-function RecentObjectRow({ entry }: { entry: FileSystemEntry }): JSX.Element {
+function RecentObjectRow({
+ entry,
+ position,
+ frequent,
+}: {
+ entry: FileSystemEntry
+ position: number
+ frequent: boolean
+}): JSX.Element {
const preview = useMemo(() => objectPreview(entry), [entry])
+ const { jumpBackOpened } = useActions(todayLogic)
return (
<li className="TodayJumpRow">
<TodayObjectIcon type={entry.type} className="TodayJumpRow__icon" />
@@ -28,12 +37,20 @@ function RecentObjectRow({ entry }: { entry: FileSystemEntry }): JSX.Element {
to={preview.href ?? undefined}
className="TodayJumpRow__link"
data-attr="today-home-recent-object"
+ onClick={() => jumpBackOpened(entry, position, frequent)}
>
{preview.name}
</LinkPrimitive>
- {preview.typeLabel && (
- <span className="TodayJumpRow__meta">{capitalizeFirstLetter(preview.typeLabel)}</span>
- )}
+ <span className="TodayJumpRow__meta">
+ {entry.last_viewed_at ? (
+ <time dateTime={entry.last_viewed_at} title={`Last opened: ${entry.last_viewed_at}`}>
+ <span className="sr-only">Last opened </span>
+ <TZLabel time={entry.last_viewed_at} showPopover={false} noStyles />
+ </time>
+ ) : (
+ <span title="Last-opened time is not available">Time unknown</span>
+ )}
+ </span>
</TodayPreviewTrigger>
</li>
)
@@ -41,7 +58,8 @@ function RecentObjectRow({ entry }: { entry: FileSystemEntry }): JSX.Element {
export function TodayRecents(): JSX.Element {
useMountedLogic(todayObjectGlanceLogic)
- const { recentObjects, recentsHasLoaded, listExpanded } = useValues(todayLogic)
+ const { recentObjects, frequentObjectsLoading, recentsHasLoaded, listExpanded, useFrequentJumpBack } =
+ useValues(todayLogic)
const { setListExpanded } = useActions(todayLogic)
const { pickPane } = useActions(todayShellLogic)
const titleId = useId()
@@ -63,8 +81,8 @@ export function TodayRecents(): JSX.Element {
</Collapsible.Trigger>
)}
</div>
- {!recentsHasLoaded ? (
- <p className="TodayHome__note">Finding what you looked at last…</p>
+ {!recentsHasLoaded || (useFrequentJumpBack && frequentObjectsLoading) ? (
+ <p className="TodayHome__note">Finding your items…</p>
) : recentObjects.length === 0 ? (
<p className="TodayHome__note">
<span>
@@ -84,15 +102,25 @@ export function TodayRecents(): JSX.Element {
) : (
<TodayPreviewCardProvider>
<ul className="TodayJumpList">
- {shown.map((entry) => (
- <RecentObjectRow key={entry.id} entry={entry} />
+ {shown.map((entry, index) => (
+ <RecentObjectRow
+ key={entry.id}
+ entry={entry}
+ position={index + 1}
+ frequent={entry.jumpBackReason === 'frequent'}
+ />
))}
</ul>
{more.length > 0 && (
<Collapsible.Panel className="TodayJumpList__more">
<ul className="TodayJumpList">
- {more.map((entry) => (
- <RecentObjectRow key={entry.id} entry={entry} />
+ {more.map((entry, index) => (
+ <RecentObjectRow
+ key={entry.id}
+ entry={entry}
+ position={RECENT_OBJECT_COUNT + index + 1}
+ frequent={entry.jumpBackReason === 'frequent'}
+ />
))}
</ul>
</Collapsible.Panel>
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
index 746c0947f658..0708699fb908 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
@@ -2,7 +2,11 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
+import { recentItemsModel } from '~/models/recentItemsModel'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
@@ -18,6 +22,7 @@ import { makeHighlightItem, makeHighlights } from './todayTestFixtures'
import { todayVerdictLogic } from './todayVerdictLogic'
describe('todayLogic', () => {
+ let frequentResponse: [number, unknown]
let listResponse: [number, any]
let listParams: URLSearchParams | null
let reportResponse: [number, any] | null
@@ -25,6 +30,7 @@ describe('todayLogic', () => {
let highlightCalls: number
beforeEach(() => {
+ frequentResponse = [200, []]
highlightResponses = [[200, makeHighlights()]]
listResponse = [200, { results: [], count: 0 }]
highlightCalls = 0
@@ -32,6 +38,7 @@ describe('todayLogic', () => {
reportResponse = null
useMocks({
get: {
+ '/api/projects/:team_id/file_system/frequent/': () => frequentResponse,
'/api/projects/:team_id/signals/reports/': ({ request }) => {
listParams = new URL(request.url).searchParams
return listResponse
@@ -49,10 +56,65 @@ describe('todayLogic', () => {
initKeaTests()
})
+ it.each([
+ { status: 200, variant: 'test' },
+ { status: 500, variant: 'test' },
+ { status: 200, variant: 'control' },
+ { status: 200, variant: false },
+ ])('selects $variant ranking when the request returns $status', async ({ status, variant }) => {
+ const entry = (id: string): { id: string; path: string; type: string; ref: string } => ({
+ id,
+ path: `Dashboards/${id}`,
+ type: 'dashboard',
+ ref: id,
+ })
+ frequentResponse = [status, status === 200 ? [entry('daily'), entry('weekly')] : {}]
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_JUMP_BACK_RANKING]: variant })
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ recentItemsModel.actions.loadRecentsSuccess(['a', 'b', 'c', 'd'].map(entry))
+ const mixed = status === 200 && variant === 'test'
+ expect(logic.values.recentObjects.map((item) => item.id)).toEqual(
+ mixed ? ['a', 'b', 'daily', 'weekly', 'c', 'd'] : ['a', 'b', 'c', 'd']
+ )
+ logic.actions.jumpBackOpened(logic.values.recentObjects[2], 3, mixed)
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'today jump back opened',
+ expect.objectContaining({
+ position: 3,
+ reason: mixed ? 'frequent' : 'recent',
+ ranking_variant: variant === 'test' ? 'test' : 'control',
+ })
+ )
+ })
+
afterEach(() => {
jest.useRealTimers()
})
+ it.each(['toggle', 'url'])('reloads frequent items when sample mode is disabled by %s', async (source) => {
+ const entry = { id: 'daily', path: 'Daily dashboard', type: 'dashboard', ref: 'daily' }
+ frequentResponse = [200, [entry]]
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => logic.actions.setUseSampleData(true))
+ .toFinishAllListeners()
+ .toMatchValues({ frequentObjects: [] })
+
+ await expectLogic(logic, () => {
+ if (source === 'url') {
+ router.actions.push('/home', { sample: '0' })
+ } else {
+ logic.actions.setUseSampleData(false)
+ }
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ useSampleData: false, frequentObjects: [entry] })
+ })
+
it.each([
{
shown: 'the report list',
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.ts
index 3394fdfcb8ea..b2cce3b58e2b 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts
@@ -5,14 +5,19 @@ import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { withTimeout } from 'lib/utils/async'
+import { isObject } from 'lib/utils/guards'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
+import { fileSystemFrequentList } from '~/generated/core/api'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { TeamPublicType, TeamType, UserType } from '~/types'
@@ -40,7 +45,7 @@ import {
type TodayForYouRows,
} from './todayForYouRows'
import { todayHighlightsLogic } from './todayHighlightsLogic'
-import { recentObjectsForHome } from './todayRecentObjects'
+import { JumpBackObject, jumpBackObjectsForHome, recentObjectsForHome } from './todayRecentObjects'
import { type TodayReportPreview, reportPreview } from './todayReportPreviews'
import type { TodayReportState } from './todayReportState'
import { isSampleReportId, parseSampleParam, sampleTopReports } from './todaySampleReports'
@@ -148,6 +153,7 @@ interface TodayRankedReport {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
recents: FileSystemEntry[] // recentItemsModel
recentsHasLoaded: boolean // recentItemsModel
currentProjectId: number | string // teamLogic
@@ -173,6 +179,8 @@ export interface todayLogicValues {
forYouReady: boolean
forYouRows: TodayForYouRows
forYouVisibleRows: TodayForYouRow[]
+ frequentObjects: FileSystemEntry[]
+ frequentObjectsLoading: boolean
greeting: string
homeScrollTop: number | null
hour: number
@@ -184,7 +192,7 @@ export interface todayLogicValues {
moreReportsInInbox: number
moreReportsLoading: boolean
now: number
- recentObjects: FileSystemEntry[]
+ recentObjects: JumpBackObject[]
reportId: string | null
reportOpenContext: TodayReportOpenContext | null
reportPreviews: Record<string, TodayReportPreview>
@@ -195,6 +203,7 @@ export interface todayLogicValues {
shownReportIds: string[]
topReports: TodayReports | null
topReportsLoading: boolean
+ useFrequentJumpBack: boolean
useSampleData: boolean
}
@@ -221,6 +230,13 @@ export interface todayLogicActions {
searchParams: Record<string, any>
url: string
} // router
+ loadCurrentTeamSuccess: (
+ currentTeam: TeamPublicType | null,
+ payload?: any
+ ) => {
+ currentTeam: TeamPublicType | null
+ payload?: any
+ } // teamLogic
loadHighlights: () => any // todayHighlightsLogic
askAi: (
prompt: string,
@@ -241,6 +257,30 @@ export interface todayLogicActions {
position: number
product: string
}
+ jumpBackOpened: (
+ entry: FileSystemEntry,
+ position: number,
+ frequent: boolean
+ ) => {
+ entry: FileSystemEntry
+ frequent: boolean
+ position: number
+ }
+ loadFrequentObjects: () => any
+ loadFrequentObjectsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFrequentObjectsSuccess: (
+ frequentObjects: FileSystemEntry[],
+ payload?: any
+ ) => {
+ frequentObjects: FileSystemEntry[]
+ payload?: any
+ }
loadMoreReports: () => any
loadMoreReportsFailure: (
error: string,
@@ -323,7 +363,12 @@ export interface todayLogicMeta {
moreReportCount: (topReports: TodayReports | null) => number
hour: (now: number) => number
greeting: (hour: number, user: UserType | null) => string
- recentObjects: (recents: FileSystemEntry[]) => FileSystemEntry[]
+ useFrequentJumpBack: (featureFlags: FeatureFlagsSet) => boolean
+ recentObjects: (
+ recents: FileSystemEntry[],
+ frequentObjects: FileSystemEntry[],
+ useFrequentJumpBack: boolean
+ ) => JumpBackObject[]
shownReportIds: (reports: SignalReport[]) => string[]
currentMoreReports: (
moreReports: TodayMoreReports | null,
@@ -376,6 +421,8 @@ export const todayLogic = kea<todayLogicType>([
path(['scenes', 'project-homepage', 'today', 'todayLogic']),
connect(() => ({
values: [
+ featureFlagLogic,
+ ['featureFlags'],
userLogic,
['user'],
teamLogic,
@@ -395,7 +442,14 @@ export const todayLogic = kea<todayLogicType>([
todayVerdictLogic,
['reportStateOverrides'],
],
- actions: [router, ['locationChanged'], todayHighlightsLogic, ['loadHighlights']],
+ actions: [
+ router,
+ ['locationChanged'],
+ todayHighlightsLogic,
+ ['loadHighlights'],
+ teamLogic,
+ ['loadCurrentTeamSuccess'],
+ ],
})),
actions({
// `report` is the report the person reads. Without it, the context is the report list.
@@ -408,12 +462,52 @@ export const todayLogic = kea<todayLogicType>([
setReturnFocusReportId: (reportId: string | null) => ({ reportId }),
setReportOpenContext: (context: TodayReportOpenContext | null) => ({ context }),
setListExpanded: (list: TodayList, expanded: boolean) => ({ list, expanded }),
+ jumpBackOpened: (entry: FileSystemEntry, position: number, frequent: boolean) => ({
+ entry,
+ position,
+ frequent,
+ }),
showMoreForYou: true,
retryFailedLoads: true,
setUseSampleData: (useSampleData: boolean) => ({ useSampleData }),
tick: true,
}),
loaders(({ values }) => ({
+ frequentObjects: [
+ [] as FileSystemEntry[],
+ {
+ loadFrequentObjects: async (): Promise<FileSystemEntry[]> => {
+ if (values.useSampleData || values.currentProjectId === null) {
+ return []
+ }
+ try {
+ const projectId = values.currentProjectId
+ const entries = await withTimeout(
+ (signal) => fileSystemFrequentList(String(projectId), { limit: 8 }, { signal }),
+ 10_000,
+ 'loadFrequentObjects timed out'
+ )
+ if (values.currentProjectId !== projectId) {
+ return []
+ }
+ return entries.map((entry) => ({
+ id: entry.id,
+ path: entry.path,
+ type: entry.type,
+ ref: entry.ref ?? undefined,
+ href: entry.href ?? undefined,
+ meta: isObject(entry.meta) ? entry.meta : undefined,
+ last_viewed_at: entry.last_viewed_at,
+ }))
+ } catch (error) {
+ if (!(error instanceof ApiError && error.status === 403)) {
+ posthog.captureException(error)
+ }
+ return []
+ }
+ },
+ },
+ ],
topReports: [
null as TodayReports | null,
{
@@ -543,9 +637,23 @@ export const todayLogic = kea<todayLogicType>([
(s) => [s.hour, s.user],
(hour: number, user: UserType | null): string => greetingForHour(hour, user?.first_name),
],
+ useFrequentJumpBack: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => featureFlags[FEATURE_FLAGS.TODAY_JUMP_BACK_RANKING] === 'test',
+ ],
recentObjects: [
- (s) => [s.recents],
- (recents: FileSystemEntry[]): FileSystemEntry[] => recentObjectsForHome(recents, RECENT_OBJECT_MORE_COUNT),
+ (s) => [s.recents, s.frequentObjects, s.useFrequentJumpBack],
+ (
+ recents: FileSystemEntry[],
+ frequentObjects: FileSystemEntry[],
+ useFrequentJumpBack: boolean
+ ): JumpBackObject[] =>
+ useFrequentJumpBack
+ ? jumpBackObjectsForHome(recents, frequentObjects, RECENT_OBJECT_MORE_COUNT)
+ : recentObjectsForHome(recents, RECENT_OBJECT_MORE_COUNT).map((entry) => ({
+ ...entry,
+ jumpBackReason: 'recent',
+ })),
],
shownReportIds: [(s) => [s.reports], (reports: SignalReport[]): string[] => reports.map((report) => report.id)],
currentMoreReports: [
@@ -716,6 +824,18 @@ export const todayLogic = kea<todayLogicType>([
})
}
return {
+ loadCurrentTeamSuccess: () => actions.loadFrequentObjects(),
+ jumpBackOpened: ({ entry, position, frequent }) => {
+ if (!values.useSampleData) {
+ posthog.capture('today jump back opened', {
+ object_type: entry.type,
+ object_ref: entry.ref ?? entry.id,
+ position,
+ reason: frequent ? 'frequent' : 'recent',
+ ranking_variant: values.useFrequentJumpBack ? 'test' : 'control',
+ })
+ }
+ },
askAi: async ({ prompt, source, report }, breakpoint) => {
let context: TodayAskContext
// Sample reports have ids that do not exist, so PostHog AI gets no context to look up. A real
@@ -745,6 +865,7 @@ export const todayLogic = kea<todayLogicType>([
},
setUseSampleData: () => {
actions.loadTopReports()
+ actions.loadFrequentObjects()
},
exploreOpened: ({ product, position }) => {
posthog.capture('today explore opened', { product, position })
@@ -809,6 +930,7 @@ export const todayLogic = kea<todayLogicType>([
posthog.capture('today home loaded', {
report_count: topReports.results.length,
more_report_count: values.moreReportCount,
+ jump_back_ranking: values.useFrequentJumpBack ? 'recent-and-frequent-v1' : 'recent-v1',
})
},
loadMoreReports: () => {
@@ -858,6 +980,7 @@ export const todayLogic = kea<todayLogicType>([
} else {
actions.loadTopReports()
}
+ actions.loadFrequentObjects()
cache.disposables.add(() => {
const clock = window.setInterval(() => actions.tick(), CLOCK_MS)
return () => clearInterval(clock)
diff --git a/frontend/src/scenes/project-homepage/today/todayRecentObjects.test.ts b/frontend/src/scenes/project-homepage/today/todayRecentObjects.test.ts
index 2dc178dbb432..1bee2d46897b 100644
--- a/frontend/src/scenes/project-homepage/today/todayRecentObjects.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayRecentObjects.test.ts
@@ -1,15 +1,66 @@
-import { recentObjectsForHome } from './todayRecentObjects'
+import { jumpBackObjectsForHome, recentObjectsForHome } from './todayRecentObjects'
describe('recentObjectsForHome', () => {
it('keeps agent sessions and entries with no page out of the recent objects', () => {
const recents = [
{ id: 'task', path: 'Tasks/Fix the flaky test', type: 'task', href: '/tasks/1' },
{ id: 'dashboard', path: 'Dashboards/Growth', type: 'dashboard', href: '/dashboard/1' },
+ { id: 'dashboard-copy', path: 'Pinned/Growth', type: 'dashboard', ref: '1' },
{ id: 'unlinked', path: 'Insights/Draft', type: 'insight' },
{ id: 'by-ref', path: 'Flags/checkout', type: 'feature_flag', ref: '7' },
{ id: 'insight', path: 'Insights/Funnel', type: 'insight/funnels', href: '/insights/a' },
+ { id: 'insight-copy', path: 'Pinned/Funnel', type: 'insight', ref: 'a' },
+ { id: 'query-one', path: 'Queries/One', href: '/sql?open_saved_query=one' },
+ { id: 'query-two', path: 'Queries/Two', href: '/sql?open_saved_query=two' },
]
- expect(recentObjectsForHome(recents, 3).map((entry) => entry.id)).toEqual(['dashboard', 'by-ref', 'insight'])
+ expect(recentObjectsForHome(recents, 5).map((entry) => entry.id)).toEqual([
+ 'dashboard',
+ 'by-ref',
+ 'insight',
+ 'query-one',
+ 'query-two',
+ ])
+ })
+
+ it.each([
+ [
+ ['a', 'b', 'c', 'd', 'e'],
+ ['d', 'e'],
+ ['a', 'b', 'd', 'e', 'c'],
+ ],
+ [
+ ['a', 'b', 'c', 'd', 'e'],
+ ['a', 'b', 'd', 'e'],
+ ['a', 'b', 'd', 'e', 'c'],
+ ],
+ [['a', 'b', 'c', 'd', 'e'], ['d'], ['a', 'b', 'd', 'c', 'e']],
+ [['a', 'b', 'c', 'd', 'e'], [], ['a', 'b', 'c', 'd', 'e']],
+ [
+ ['a', 'b', 'c', 'd', 'e'],
+ ['d', 'd', 'e'],
+ ['a', 'b', 'd', 'e', 'c'],
+ ],
+ [
+ ['a', 'a', 'b', 'c', 'd', 'e'],
+ ['c', 'd'],
+ ['a', 'b', 'c', 'd', 'e'],
+ ],
+ [
+ ['a', 'b', 'c', 'c', 'd', 'e'],
+ ['d', 'e'],
+ ['a', 'b', 'd', 'e', 'c'],
+ ],
+ [['a', 'a', 'b', 'c', 'd', 'e'], [], ['a', 'b', 'c', 'd', 'e']],
+ ])('mixes recent %j and frequent %j without duplicates', (recentIds, frequentIds, expected) => {
+ const entry = (id: string): { id: string; path: string; type: string; ref: string } => ({
+ id,
+ path: `Dashboards/${id}`,
+ type: 'dashboard',
+ ref: id,
+ })
+ expect(jumpBackObjectsForHome(recentIds.map(entry), frequentIds.map(entry), 8).map((item) => item.id)).toEqual(
+ expected
+ )
})
})
diff --git a/frontend/src/scenes/project-homepage/today/todayRecentObjects.ts b/frontend/src/scenes/project-homepage/today/todayRecentObjects.ts
index 0ebe4312d5f8..894d00363457 100644
--- a/frontend/src/scenes/project-homepage/today/todayRecentObjects.ts
+++ b/frontend/src/scenes/project-homepage/today/todayRecentObjects.ts
@@ -1,10 +1,63 @@
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { baseObjectType, libraryObjectHref } from 'scenes/library/libraryUtils'
import { FileSystemEntry } from '~/queries/schema/schema-general'
+function objectKey(entry: FileSystemEntry): string {
+ const href = libraryObjectHref({ type: baseObjectType(entry.type), ref: entry.ref }) ?? libraryObjectHref(entry)
+ if (!href) {
+ return `${baseObjectType(entry.type)}:${entry.ref ?? entry.id}`
+ }
+ const destination = removeProjectIdIfPresent(href).split('#')[0]
+ const queryStart = destination.indexOf('?')
+ const pathname = queryStart === -1 ? destination : destination.slice(0, queryStart)
+ const search = queryStart === -1 ? '' : destination.slice(queryStart)
+ return `${pathname.replace(/\/+$/, '')}${search}`
+}
+
/** Recently viewed objects for the home, without tasks, which are agent sessions rather than things people look at. */
export function recentObjectsForHome(recents: FileSystemEntry[], limit: number): FileSystemEntry[] {
+ const seen = new Set<string>()
return recents
- .filter((entry) => libraryObjectHref(entry) !== null && baseObjectType(entry.type) !== 'task')
+ .filter((entry) => {
+ if (libraryObjectHref(entry) === null || baseObjectType(entry.type) === 'task') {
+ return false
+ }
+ const key = objectKey(entry)
+ if (seen.has(key)) {
+ return false
+ }
+ seen.add(key)
+ return true
+ })
.slice(0, limit)
}
+
+export type JumpBackObject = FileSystemEntry & { jumpBackReason: 'recent' | 'frequent' }
+
+export function jumpBackObjectsForHome(
+ recents: FileSystemEntry[],
+ frequent: FileSystemEntry[],
+ limit: number
+): JumpBackObject[] {
+ const recentObjects = recentObjectsForHome(recents, limit)
+ const first = recentObjects.slice(0, 2)
+ const seen = new Set(first.map(objectKey))
+ const result: JumpBackObject[] = first.map((entry) => ({ ...entry, jumpBackReason: 'recent' }))
+ for (const entry of recentObjectsForHome(frequent, frequent.length)) {
+ if (!seen.has(objectKey(entry))) {
+ seen.add(objectKey(entry))
+ result.push({ ...entry, jumpBackReason: 'frequent' })
+ if (result.length === first.length + 2) {
+ break
+ }
+ }
+ }
+ for (const entry of recentObjects) {
+ if (!seen.has(objectKey(entry))) {
+ seen.add(objectKey(entry))
+ result.push({ ...entry, jumpBackReason: 'recent' })
+ }
+ }
+ return result.slice(0, limit)
+}
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index a5aa5043fdad..e50372d49598 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -6,6 +6,7 @@ import builtins
from functools import cached_property
from typing import Any, Optional, cast
from uuid import UUID
+from zoneinfo import ZoneInfo
from django.apps import apps
from django.db import connection, transaction
@@ -146,6 +147,12 @@ class FileSystemDeleteQuerySerializer(serializers.Serializer):
)
+class FileSystemFrequentQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ default=8, min_value=1, max_value=20, help_text="Maximum number of frequently viewed items to return."
+ )
+
+
class FileSystemSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):
last_viewed_at = serializers.DateTimeField(read_only=True, allow_null=True)
created_by = UserBasicSerializer(read_only=True, allow_null=True)
@@ -367,6 +374,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"list",
"retrieve",
"search",
+ "frequent",
"unfiled",
"count",
"count_by_path",
@@ -883,6 +891,26 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return response
+ @validated_request(
+ query_serializer=FileSystemFrequentQuerySerializer,
+ responses={200: FileSystemSerializer(many=True)},
+ summary="List frequently viewed files",
+ )
+ @action(methods=["GET"], detail=False, pagination_class=None)
+ def frequent(self, request: Request, **kwargs: object) -> Response:
+ queryset = FileSystem.objects.filter(surface_q(self.file_system_surface), team_id=self.team.id)
+ queryset = self._filter_by_access_control(queryset)
+ items = get_recent_file_system_items(
+ team_id=self.team.id,
+ user_id=cast(User, request.user).id,
+ surface=self.file_system_surface,
+ limit=request.validated_query_data["limit"],
+ exclude_types=[*RETIRED_FILE_SYSTEM_TYPES, "folder", "task"],
+ file_system_queryset=queryset,
+ frequent_on=timezone.now().astimezone(ZoneInfo(self.team.timezone or "UTC")).date(),
+ )
+ return Response(self.get_serializer(items, many=True).data)
+
def _created_by_users(self, results: builtins.list[dict[str, Any]]) -> builtins.list[dict[str, Any]]:
# Collect user IDs from the "created_by" meta field so the client can render avatars
# without a second round-trip. Rows written before `meta` was validated can hold a
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index d2677057d07d..d77ba3f9736f 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -1,5 +1,5 @@
from collections.abc import Callable, Iterable, Mapping
-from datetime import UTC
+from datetime import UTC, timedelta
from typing import Any, TypedDict, cast
import pytest
@@ -12,6 +12,7 @@ from django.core.cache import cache
from django.db import connection
from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
@@ -63,6 +64,37 @@ class TestFileSystemAPI(APIBaseTest):
self.user.is_staff = True
self.user.save()
+ @time_machine.travel("2026-01-31T12:00:00Z", tick=False)
+ def test_frequent_files_rank_separate_visit_days_with_recency_decay(self) -> None:
+ now = timezone.now()
+ cases = [
+ ("one-off", [0], "web"),
+ ("regular", [1, 2, 3, 4], "web"),
+ ("older", [10, 20], "web"),
+ ("expired", [40, 41], "web"),
+ ("future", [-1, -2], "web"),
+ ("reloaded", [0, 0, 0], "web"),
+ ("desktop", [0, 1, 2], "desktop"),
+ ]
+ for ref, days, surface in cases:
+ FileSystem.objects.create(team=self.team, path=f"Docs/{ref}", type="doc", ref=ref, surface=surface)
+ FileSystemViewLog.objects.create(
+ team=self.team,
+ user=self.user,
+ type="doc",
+ ref=ref,
+ surface=surface,
+ viewed_at=now - timedelta(days=min(days)),
+ view_days=[(now - timedelta(days=day)).date() for day in days],
+ )
+ url = f"/api/projects/{self.team.id}/file_system/frequent/"
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual([item["ref"] for item in response.json()], ["regular", "older"])
+ self.assertEqual([item["ref"] for item in self.client.get(url, {"limit": 1}).json()], ["regular"])
+ self.client.force_login(self._create_user("[email protected]"))
+ self.assertEqual(self.client.get(url).json(), [])
+
def test_list_files_initially_empty(self):
"""
When no FileSystem objects exist in the DB for the team, the list should be empty.
@@ -1499,6 +1531,29 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
def _create_sibling_team(self) -> Team:
return Team.objects.create(project=self.project, organization=self.organization, name="Env-2")
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_frequent_files_filter_access_before_selecting_top_items(self, mock_flag: MagicMock) -> None:
+ assert self.file_b.ref is not None
+ Dashboard.objects.filter(id=self.file_b.ref).update(created_by=self.other_user)
+ FileSystem.objects.filter(team=self.team, type="dashboard", ref=self.file_b.ref).update(
+ created_by=self.other_user
+ )
+ self._create_access_control(resource="dashboard", resource_id=self.file_b.ref, access_level="none")
+ now = timezone.now()
+ for entry, days in ((self.file_a, [1, 2]), (self.file_b, [0, 1, 2, 3])):
+ assert entry.ref is not None
+ FileSystemViewLog.objects.create(
+ team=self.team,
+ user=self.user,
+ type=entry.type,
+ ref=entry.ref,
+ viewed_at=now - timedelta(days=min(days)),
+ view_days=[(now - timedelta(days=day)).date() for day in days],
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/frequent/", {"limit": 1})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual([item["ref"] for item in response.json()], [self.file_a.ref])
+
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_list_excludes_items_with_none_access(self, mock_flag):
self._create_access_control(resource="dashboard", resource_id=self.file_b.ref, access_level="none")
diff --git a/posthog/models/file_system/file_system_view_log.py b/posthog/models/file_system/file_system_view_log.py
index bf6871d59126..4aa160dc0fb4 100644
--- a/posthog/models/file_system/file_system_view_log.py
+++ b/posthog/models/file_system/file_system_view_log.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import heapq
from collections.abc import Collection, Sequence
from dataclasses import is_dataclass
from datetime import date, datetime, timedelta
@@ -23,6 +24,15 @@ if TYPE_CHECKING:
from posthog.models.user import User
VIEW_DAYS_KEPT = 35
+FRECENCY_HALF_LIFE_DAYS = 14
+
+
+def view_days_score(view_days: Sequence[date], today: date) -> float:
+ return sum(
+ 0.5 ** ((today - day).days / FRECENCY_HALF_LIFE_DAYS)
+ for day in set(view_days)
+ if 0 <= (today - day).days < VIEW_DAYS_KEPT
+ )
class FileSystemViewLog(UUIDModel):
@@ -158,6 +168,7 @@ def get_recent_file_system_items(
exclude_types: Optional[Sequence[str]] = ("folder",),
file_system_queryset: Optional[QuerySet[FileSystem]] = None,
descending: bool = True,
+ frequent_on: date | None = None,
) -> list[FileSystem]:
"""Recently-viewed FileSystem rows for a user, newest first by default.
@@ -170,9 +181,15 @@ def get_recent_file_system_items(
before the ``(type, ref)`` keys are matched. ``descending`` is threaded down to the view-log
query so the ``limit`` slice picks the globally oldest/newest views, not a re-sorted page.
"""
- entries = FileSystem.objects.filter(
- surface_q(surface), team_id=team_id, type=OuterRef("type"), ref=OuterRef("ref")
- ).exclude(shortcut=True)
+ entries = (
+ (
+ file_system_queryset
+ if frequent_on is not None and file_system_queryset is not None
+ else FileSystem.objects.all()
+ )
+ .filter(surface_q(surface), team_id=team_id, type=OuterRef("type"), ref=OuterRef("ref"))
+ .exclude(shortcut=True)
+ )
log_queryset = recent_view_logs(
team_id=team_id,
user_id=user_id,
@@ -180,9 +197,22 @@ def get_recent_file_system_items(
exclude_types=exclude_types,
descending=descending,
).filter(Exists(entries))
- if limit is not None:
- log_queryset = log_queryset[:limit]
- log_rows = list(log_queryset.values_list("type", "ref", "viewed_at"))
+ if frequent_on is not None:
+ candidates = (
+ (row_type, row_ref, viewed_at, view_days_score(view_days or [], frequent_on))
+ for row_type, row_ref, viewed_at, view_days in log_queryset.filter(
+ viewed_at__gte=timezone.now() - timedelta(days=VIEW_DAYS_KEPT)
+ )
+ .values_list("type", "ref", "viewed_at", "view_days")
+ .iterator()
+ if len({day for day in view_days or [] if 0 <= (frequent_on - day).days < VIEW_DAYS_KEPT}) >= 2
+ )
+ ranked = heapq.nlargest(limit or 20, candidates, key=lambda row: (row[3], row[2], row[0], row[1]))
+ log_rows = [(row_type, row_ref, viewed_at) for row_type, row_ref, viewed_at, _ in ranked]
+ else:
+ if limit is not None:
+ log_queryset = log_queryset[:limit]
+ log_rows = list(log_queryset.values_list("type", "ref", "viewed_at"))
if not log_rows:
return []
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a2b6ef01eec1..40821625b1a8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -134220,6 +134220,19 @@ export namespace Schemas {
recursive?: boolean;
};
+ export type FileSystemFrequentListParams = {
+ /**
+ * Maximum number of frequently viewed items to return.
+ * @minimum 1
+ * @maximum 20
+ */
+ limit?: number;
+ /**
+ * A search term.
+ */
+ search?: string;
+ };
+
export type FileSystemSearchRetrieveParams = {
/**
* Maximum number of results to return, best first.