: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): add hogql fallback for livestream behind flag (#109885)
Ben White46430ce06c2d
diff --git a/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md b/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.mdindex 90ef3c129cc1..af347521e699 100644--- a/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md+++ b/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md@@ -113,7 +113,7 @@ Directory: `products/dashboards/frontend/widgets/<product>/` (snake_case product- [ ] Use `WidgetCardContent` for scrollable lists/tables; `WidgetCardBodyMessage` for empty states- [ ] **Adoption CTA on the "no entities yet" empty state** — when the product has nothing to show yet (no surveys, no experiments), render a primary `LemonButton` (`targetBlank`) to the product's create flow and fire `posthog.capture('dashboard widget create <product> clicked', { widget_type, tile_id })` on click. Measures adoption driven _from_ the widget, distinct from the platform `dashboard widget added` event. See [§ Product-adoption tracking](#product-adoption-tracking).- [ ] **List widgets:** follow [list-widget-patterns.md](list-widget-patterns.md) — `hasMore`, footer, tile filter bar, `titleHref`-- [ ] **Live widgets:** compose the `widgets/live/` toolkit (`liveWidgetStream`, `LiveWidgetSlidingWindow`, `useLiveWidgetSeed`, `LiveWidgetEmptyState`) — recipe in [live-widgets.md](live-widgets.md)+- [ ] **Live widgets:** compose the `widgets/live/` toolkit (`LiveWidgetSlidingWindow`, `useLiveWidgetSeed`, `LiveWidgetEmptyState`) — recipe in [live-widgets.md](live-widgets.md)- [ ] Do **not** render card chrome — `DashboardWidgetItem` + catalog handle headers/menusMinimal skeleton:diff --git a/.agents/skills/manage-dashboard-widgets/references/live-widgets.md b/.agents/skills/manage-dashboard-widgets/references/live-widgets.mdindex f4c4b92bc74b..3b9557b2cebf 100644--- a/.agents/skills/manage-dashboard-widgets/references/live-widgets.md+++ b/.agents/skills/manage-dashboard-widgets/references/live-widgets.md@@ -30,24 +30,21 @@ Conventions:## Frontend toolkit — `products/dashboards/frontend/widgets/live/`-Compose these; don't re-wire SSE/flush/tick by hand:+Compose these:| Module | What it does || ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `liveWidgetTypes.ts` — `isLiveDashboardWidgetType()`, `LiveWidgetSeedPayload` | FE read of `WidgetSpec.is_live` from the generated manifest, plus the base seed-payload interface (`generatedAt`) — extend it in your result types || `LiveWidgetSlidingWindow` | Minute-bucketed window: overall count + named breakdown domains, each fed by an extractor `(event) => string \| null` (null = skip). Encodes the seed-merge correctness rules — see below |-| `liveWidgetStream(options)` | Kea logic builder: livestream SSE connection (`/events`, `live_events_token`), flush-batched `onEvents` (300ms), 60s `onMinuteTick`, all via `cache.disposables` (pauses on hidden tabs) || `useLiveWidgetSeed(payload, seed)` | The one prop→action React bridge: seeds your logic from the tile's `result` prop (pass `null` while the payload isn't ready) || `components.tsx` — `LiveWidgetEmptyState` | "No data in the window yet" body with optional CTA || `components.tsx` — `LiveWidgetIndicator` | The pulsing "Live" header marker (platform-rendered — you don't wire this) |**Seed-merge semantics (do not "simplify" these):** the SSE stream reads Kafka (fresh) while seeds read ClickHouse (can lag ingestion). `LiveWidgetSlidingWindow` therefore merges seeds via per-bucket `max` (never replace — an empty lagging re-seed must not wipe stream-accumulated counts) and drops streamed events at or before the domain's seed `generatedAt` (strict `>`), so a re-seed never double counts. `widgets/live/LiveWidgetSlidingWindow.test.ts` guards these.-**kea-typegen constraint:** `liveWidgetStream` only adds `connect`/`events` wiring — typegen cannot see builder-injected symbols, so your logic declares its own actions/reducers/selectors and the builder dispatches into them via `onEvents`/`onMinuteTick` callbacks.+**One connection per dashboard:** make the product's live logic unkeyed and share it across the family's tiles — kea ref-counting keeps one connection or poller no matter how many live tiles are placed, and tears it down when the last unmounts. Reset state in `afterMount` so data can't leak across dashboards.-**One connection per dashboard:** make the product's live logic unkeyed and share it across the family's tiles — kea ref-counting keeps one SSE connection no matter how many live tiles are placed, and tears it down when the last unmounts. Reset state in `afterMount` so data can't leak across dashboards.--**Transports:** the shipped helper is livestream SSE. The contract is transport-agnostic — a polling helper with the same `onEvents`/`onMinuteTick` shape could be added for products without livestream data, with no contract changes.+**Transports:** no transport helper ships with the toolkit. The contract is transport-agnostic: feed the window from a polling helper with an `onEvents`/`onMinuteTick` shape, or re-run the seed query on an interval.## Recipe: shipping a new live widget family@@ -56,7 +53,7 @@ On top of the normal [new-type checklist](checklist-new-widget-type.md):1. Spec: `is_live=True`, `creation_flag="<your-rollout-flag>"`, no `dateRange`/`filterTestAccounts` on the config model (enforced at spec construction).2. Seed query in your product's backend returning `generatedAt`; thin `query_fn` wrapper in `widgets/<type>.py`.3. Catalog entry as normal — `showDateRange` hides automatically for live types. To keep the picker card hidden pre-release, land the FE catalog entry with the release; `creation_flag` is the backend gate either way ([availability-and-gating.md](availability-and-gating.md)).-4. One unkeyed shared logic on `liveWidgetStream` + `LiveWidgetSlidingWindow` (or your own windowing if minute buckets don't fit — keep the idempotent-seed rule).+4. One unkeyed shared logic on `LiveWidgetSlidingWindow` (or your own windowing if minute buckets don't fit — keep the idempotent-seed rule).5. Components: `useLiveWidgetSeed(payload, seedAction)`, render from selectors, `LiveWidgetEmptyState` when the window is empty.6. `hogli build:widget-types` (regenerates the manifest the FE catalog reads `live` from), then the normal verify suite.diff --git a/frontend/src/lib/components/LiveUserCount/liveCountCache.ts b/frontend/src/lib/components/LiveUserCount/liveCountCache.tsnew file mode 100644index 000000000000..8f97727c4ae0--- /dev/null+++ b/frontend/src/lib/components/LiveUserCount/liveCountCache.ts@@ -0,0 +1,73 @@+import api from 'lib/api'++import { QueryLogTags } from '~/queries/schema/schema-general'+import { HogQLQueryString } from '~/queries/utils'++export const LIVE_COUNT_REFRESH_MS = 30000+// pinned: localStorage key prefix, renaming it drops every user's cached counts+const STORAGE_KEY_PREFIX = 'live-count-hogql-'++export interface CachedLiveCount {+ value: number+ fetchedAt: number+}++// Several counters can mount at once, so they share one in-flight query per key.+const inflightByKey = new Map<string, Promise<CachedLiveCount>>()+// Fallback for when localStorage is disabled or full.+const memoryCacheByKey = new Map<string, CachedLiveCount>()++function isCachedLiveCount(value: unknown): value is CachedLiveCount {+ const candidate = value as Partial<CachedLiveCount> | null+ return Number.isFinite(candidate?.value) && Number.isFinite(candidate?.fetchedAt)+}++function readCachedLiveCount(storageKey: string): CachedLiveCount | null {+ try {+ const raw = localStorage.getItem(storageKey)+ const parsed: unknown = raw ? JSON.parse(raw) : null+ if (isCachedLiveCount(parsed)) {+ return parsed+ }+ } catch {+ // Fall through to the in-memory copy.+ }+ return memoryCacheByKey.get(storageKey) ?? null+}++/** Runs a single-value HogQL count, reusing a result younger than LIVE_COUNT_REFRESH_MS across mounts and reloads. */+export async function loadCachedLiveCount(+ name: string,+ teamId: number,+ query: HogQLQueryString,+ tags: QueryLogTags+): Promise<CachedLiveCount> {+ const storageKey = `${STORAGE_KEY_PREFIX}${name}-${teamId}`+ const cached = readCachedLiveCount(storageKey)+ if (cached && Date.now() - cached.fetchedAt < LIVE_COUNT_REFRESH_MS) {+ return cached+ }+ let request = inflightByKey.get(storageKey)+ if (!request) {+ request = queryLiveCount(storageKey, query, tags).finally(() => inflightByKey.delete(storageKey))+ inflightByKey.set(storageKey, request)+ }+ return request+}++async function queryLiveCount(+ storageKey: string,+ query: HogQLQueryString,+ tags: QueryLogTags+): Promise<CachedLiveCount> {+ // The default refresh mode can serve a server-cached count that is older than the whole live window.+ const response = await api.queryHogQL<[number][]>(query, tags, { refresh: 'force_blocking' })+ const result: CachedLiveCount = { value: response.results?.[0]?.[0] ?? 0, fetchedAt: Date.now() }+ memoryCacheByKey.set(storageKey, result)+ try {+ localStorage.setItem(storageKey, JSON.stringify(result))+ } catch {+ // Storage can be full or disabled. The in-memory copy still serves reads.+ }+ return result+}diff --git a/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.test.ts b/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.test.tsnew file mode 100644index 000000000000..e97db750572f--- /dev/null+++ b/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.test.ts@@ -0,0 +1,41 @@+import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { liveUserCountLogic } from './liveUserCountLogic'++describe('liveUserCountLogic', () => {+ const originalFetch = global.fetch++ beforeEach(() => {+ jest.useFakeTimers()+ initKeaTests()+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [[5]] } as any)+ global.fetch = jest.fn().mockResolvedValue({ json: () => Promise.resolve({ users_on_product: 7 }) })+ })++ afterEach(() => {+ jest.useRealTimers()+ global.fetch = originalFetch+ })++ it('keeps polling the live stats endpoint after LIVESTREAM_HOGQL turns off while mounted', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.LIVESTREAM_HOGQL], {+ [FEATURE_FLAGS.LIVESTREAM_HOGQL]: true,+ })+ const logic = liveUserCountLogic({ pollIntervalMs: 30000 })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.liveUserCount).toBe(5)++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.LIVESTREAM_HOGQL]: false })+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.liveUserCount).toBe(7)++ jest.mocked(global.fetch).mockClear()+ await jest.advanceTimersByTimeAsync(60000)+ expect(global.fetch).toHaveBeenCalledTimes(2)+ })+})diff --git a/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.ts b/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.tsindex 75354c5b3210..9a80cda65da6 100644--- a/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.ts+++ b/frontend/src/lib/components/LiveUserCount/liveUserCountLogic.ts@@ -1,9 +1,21 @@import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { liveEventsHostOrigin } from 'lib/utils/apiHost'import { teamLogic } from 'scenes/teamLogic'+import { hogql } from '~/queries/utils'++import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { TeamPublicType, TeamType } from '../../../types'+import { LIVE_COUNT_REFRESH_MS, loadCachedLiveCount } from './liveCountCache'++const LIVE_USERS_COUNT_QUERY = hogql`+ SELECT uniq(distinct_id)+ FROM events+ WHERE timestamp > now() - INTERVAL 1 MINUTE+ AND timestamp < now() + INTERVAL 1 MINUTE`export interface LiveUserCountStats {users_on_product?: number@@ -15,6 +27,7 @@ export interface LiveUserCountLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveUserCountLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogicisHovering: booleanliveUserCount: number | null@@ -26,6 +39,20 @@ export interface liveUserCountLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveUserCountLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+ loadCurrentTeamSuccess: (+ currentTeam: TeamPublicType | null,+ payload?: any+ ) => {+ currentTeam: TeamPublicType | null+ payload?: any+ } // teamLogicpauseStream: () => {value: true}@@ -71,7 +98,8 @@ export const liveUserCountLogic = kea<liveUserCountLogicType>([key((props) => props.pollIntervalMs ?? 30000),props({ pollIntervalMs: 30000 } as LiveUserCountLogicProps),connect(() => ({- values: [teamLogic, ['currentTeam']],+ values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],+ actions: [featureFlagLogic, ['setFeatureFlags'], teamLogic, ['loadCurrentTeamSuccess']],})),actions(() => ({pollStats: true,@@ -131,6 +159,31 @@ export const liveUserCountLogic = kea<liveUserCountLogicType>([return}+ if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ let nextPollMs = LIVE_COUNT_REFRESH_MS+ try {+ const { value, fetchedAt } = await loadCachedLiveCount(+ 'users',+ values.currentTeam.id,+ LIVE_USERS_COUNT_QUERY,+ { productKey: 'product_analytics', name: 'live_users_count' }+ )+ if (cache.disposables.isDisposed) {+ return+ }+ actions.setStats({ users_on_product: value }, new Date(fetchedAt))+ nextPollMs = Math.max(0, fetchedAt + LIVE_COUNT_REFRESH_MS - Date.now())+ } finally {+ if (!cache.statsPaused && cache.usesHogql) {+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => actions.pollStats(), nextPollMs)+ return () => clearTimeout(timeoutId)+ }, 'statsInterval')+ }+ }+ return+ }+const response = await fetch(`${liveEventsHostOrigin()}/stats`, {headers: {Authorization: `Bearer ${values.currentTeam.live_events_token}`,@@ -156,10 +209,29 @@ export const liveUserCountLogic = kea<liveUserCountLogicType>([}},pauseStream: () => {+ cache.statsPaused = truecache.disposables.dispose('statsInterval')},+ loadCurrentTeamSuccess: () => {+ // pollStats returns early without a team, so in HogQL mode no next poll is scheduled until the team loads.+ if (!cache.statsPaused && values.stats === null) {+ actions.pollStats()+ }+ },+ setFeatureFlags: () => {+ // Each mode schedules its polls differently, so a mode change needs a fresh scheduler.+ if (!cache.statsPaused && !!values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL] !== cache.usesHogql) {+ actions.resumeStream()+ }+ },resumeStream: () => {+ cache.statsPaused = false+ cache.usesHogql = !!values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]actions.pollStats()+ if (cache.usesHogql) {+ // pollStats schedules its own next run from the cached fetch time.+ return+ }cache.disposables.add(() => {const intervalId = setInterval(() => {actions.pollStats()diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 713df6231c69..6710c838cdad 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -368,6 +368,7 @@ export const FEATURE_FLAGS = {LINKS: 'links', // owner: @marconlp #team-link (team doesn't exist for now, maybe will come back in the future)LIVE_DEBUGGER: 'live-debugger', // owner: @marcecollLIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analytics+ LIVESTREAM_HOGQL: 'livestream-hogql', // owner: @benjackwhite #team-replay, swaps livestream service calls for HogQL queriesLLM_ANALYTICS_CATEGORICAL_EVALS: 'llm-analytics-categorical-evaluations', // owner: #team-ai-observabilityLLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observabilityLLM_ANALYTICS_COMMUNITY_SKILLS: 'llm-analytics-community-skills', // owner: #team-ai-observabilitydiff --git a/frontend/src/scenes/activity/activitySceneTabsLogic.tsx b/frontend/src/scenes/activity/activitySceneTabsLogic.tsxindex 0526cc2fce77..238d6450b956 100644--- a/frontend/src/scenes/activity/activitySceneTabsLogic.tsx+++ b/frontend/src/scenes/activity/activitySceneTabsLogic.tsx@@ -1,7 +1,9 @@import { MakeLogicType, connect, kea, path, selectors } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'import { GroupsAccessStatus } from 'lib/introductions/groupsAccessLogic'import { LemonTab } from 'lib/lemon-ui/LemonTabs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { capitalizeFirstLetter } from 'lib/utils/strings'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'@@ -12,6 +14,7 @@ import { groupsModel } from '~/models/groupsModel'import { FileSystemIconType } from '~/queries/schema/schema-general'import { ActivityTab } from '~/types'+import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'import type { Noun } from '../../models/groupsModel'import type { GroupType, GroupTypeIndex } from '../../types'@@ -29,6 +32,7 @@ interface ActivitySceneTab {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface activitySceneTabsLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModelgroupTypes: Map<GroupTypeIndex, GroupType> // groupsModelgroupsAccessStatus: GroupsAccessStatus // groupsModel@@ -45,7 +49,7 @@ export interface activitySceneTabsLogicMeta {groupsAccessStatus: GroupsAccessStatus,aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun) => ActivitySceneTab[]- tabs: (groupTabs: ActivitySceneTab[]) => LemonTab<ActivitySceneTabKey>[]+ tabs: (groupTabs: ActivitySceneTab[], featureFlags: FeatureFlagsSet) => LemonTab<ActivitySceneTabKey>[]tabsForKey: (tabs: LemonTab<ActivitySceneTabKey>[]) => (activeKey: ActivitySceneTabKey) => LemonTab<ActivitySceneTabKey>[]@@ -62,7 +66,12 @@ export type activitySceneTabsLogicType = MakeLogicType<export const activitySceneTabsLogic = kea<activitySceneTabsLogicType>([path(['scenes', 'activity', 'activitySceneTabsLogic']),connect(() => ({- values: [groupsModel, ['aggregationLabel', 'groupTypes', 'groupsAccessStatus']],+ values: [+ groupsModel,+ ['aggregationLabel', 'groupTypes', 'groupsAccessStatus'],+ featureFlagLogic,+ ['featureFlags'],+ ],})),selectors({groupTabs: [@@ -100,8 +109,8 @@ export const activitySceneTabsLogic = kea<activitySceneTabsLogicType>([},],tabs: [- (s) => [s.groupTabs],- (groupTabs: ActivitySceneTab[]): LemonTab<ActivitySceneTabKey>[] => {+ (s) => [s.groupTabs, s.featureFlags],+ (groupTabs: ActivitySceneTab[], featureFlags: FeatureFlagsSet): LemonTab<ActivitySceneTabKey>[] => {const tabs: ActivitySceneTab[] = [{key: ActivityTab.ExploreEvents,@@ -140,7 +149,11 @@ export const activitySceneTabsLogic = kea<activitySceneTabsLogicType>([...groupTabs,]- return tabs.map((tab) => ({+ const visibleTabs = featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]+ ? tabs.filter((tab) => tab.key !== ActivityTab.LiveEvents)+ : tabs++ return visibleTabs.map((tab) => ({key: tab.key,label: (<span className="flex items-center gap-1" data-attr={tab.dataAttr}>diff --git a/frontend/src/scenes/activity/explore/EventsScene.tsx b/frontend/src/scenes/activity/explore/EventsScene.tsxindex 4117df88f623..24847a2988f4 100644--- a/frontend/src/scenes/activity/explore/EventsScene.tsx+++ b/frontend/src/scenes/activity/explore/EventsScene.tsx@@ -1,9 +1,13 @@import { useActions, useValues } from 'kea'+import { LiveUserCount } from 'lib/components/LiveUserCount'+import { FEATURE_FLAGS } from 'lib/constants'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'+import { LiveRecordingsCount } from 'scenes/session-recordings/components/LiveRecordingsCount'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'@@ -20,6 +24,7 @@ import { eventsSceneLogic } from './eventsSceneLogic'export function EventsScene(): JSX.Element {const { query, showFlagCallsNote } = useValues(eventsSceneLogic())const { setQuery } = useActions(eventsSceneLogic())+ const { featureFlags } = useValues(featureFlagLogic)useAttachedContext(buildExploreAgentContext(ActivityTab.ExploreEvents, query))@@ -33,6 +38,12 @@ export function EventsScene(): JSX.Element {type: sceneConfigurations[Scene.ExploreEvents].iconType || 'default_icon_type',}}/>+ {featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL] && (+ <div className="flex flex-wrap gap-2 mb-2">+ <LiveUserCount />+ <LiveRecordingsCount />+ </div>+ )}{showFlagCallsNote && (<LemonBanner type="info" dismissKey="activity-flag-calls-stored-separately">Feature flag calls are stored separately from other events. Filter by only the "Feature flag called"diff --git a/frontend/src/scenes/activity/live/liveEventsLogic.tsx b/frontend/src/scenes/activity/live/liveEventsLogic.tsxindex ceba791a291f..c181c26cb694 100644--- a/frontend/src/scenes/activity/live/liveEventsLogic.tsx+++ b/frontend/src/scenes/activity/live/liveEventsLogic.tsx@@ -15,6 +15,7 @@ import { AnyPropertyFilter, LiveEvent, PropertyFilterValue, PropertyOperator } fimport type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { TeamPublicType, TeamType } from '../../../types'import { deduplicateEvents } from './deduplicateEvents'+import { LIVE_EVENTS_QUERY_POLL_MS, loadRecentLiveEvents } from './liveEventsQuery'const ERROR_TOAST_ID = 'live-stream-error'@@ -200,6 +201,35 @@ export const liveEventsLogic = kea<liveEventsLogicType>([return}+ if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ const teamId = values.currentTeam.id+ const { eventType } = values.filters+ cache.disposables.add(() => {+ let cancelled = false+ let timeoutId: ReturnType<typeof setTimeout> | undefined+ // Each poll waits for the previous one to settle, so slow queries never overlap.+ const poll = async (): Promise<void> => {+ try {+ const events = await loadRecentLiveEvents(teamId, eventType)+ if (!cancelled) {+ actions.addEvents(events)+ }+ } catch (error) {+ console.error('Failed to load recent events', error)+ }+ if (!cancelled) {+ timeoutId = setTimeout(() => void poll(), LIVE_EVENTS_QUERY_POLL_MS)+ }+ }+ void poll()+ return () => {+ cancelled = true+ clearTimeout(timeoutId)+ }+ }, 'eventsConnection')+ return+ }+const { eventType, properties } = values.filtersconst url = new URL(`${liveEventsHostOrigin()}/events`)if (eventType) {diff --git a/frontend/src/scenes/activity/live/liveEventsQuery.ts b/frontend/src/scenes/activity/live/liveEventsQuery.tsnew file mode 100644index 000000000000..0cafa1f2e488--- /dev/null+++ b/frontend/src/scenes/activity/live/liveEventsQuery.ts@@ -0,0 +1,31 @@+import api from 'lib/api'++import { hogql } from '~/queries/utils'+import { LiveEvent } from '~/types'++export const LIVE_EVENTS_QUERY_POLL_MS = 10000++type LiveEventRow = [string, string, string, string, string | null, string | null]++export async function loadRecentLiveEvents(teamId: number, eventType: string | null): Promise<LiveEvent[]> {+ const response = await api.queryHogQL<LiveEventRow[]>(+ hogql`SELECT uuid, event, distinct_id, toString(timestamp), properties.$current_url, properties.$screen_name+ FROM events+ WHERE timestamp > now() - INTERVAL 5 MINUTE+ AND timestamp < now() + INTERVAL 1 MINUTE+ AND (${eventType ?? ''} = '' OR event = ${eventType ?? ''})+ ORDER BY timestamp DESC+ LIMIT 100`,+ { productKey: 'product_analytics', name: 'live_events_poll' },+ { refresh: 'force_blocking' }+ )+ return (response.results ?? []).map(([uuid, event, distinctId, timestamp, currentUrl, screenName]) => ({+ uuid,+ event,+ distinct_id: distinctId,+ timestamp,+ created_at: timestamp,+ team_id: teamId,+ properties: { $current_url: currentUrl, $screen_name: screenName },+ }))+}diff --git a/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts b/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.tsindex af89e8e7c4dc..1336f46bdc7f 100644--- a/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts+++ b/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts@@ -1,15 +1,30 @@-import { MakeLogicType, kea, key, path, selectors } from 'kea'+import { MakeLogicType, connect, kea, key, listeners, path, selectors } from 'kea'+import { router, urlToAction } from 'kea-router'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'-import { Breadcrumb } from '~/types'+import { ActivityTab, Breadcrumb } from '~/types'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveEventsTableSceneLogicValues {breadcrumbs: Breadcrumb[]}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface liveEventsTableSceneLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveEventsTableSceneLogicMeta {key: string@@ -17,11 +32,18 @@ export interface liveEventsTableSceneLogicMeta {export type liveEventsTableSceneLogicType = MakeLogicType<liveEventsTableSceneLogicValues,- {},+ liveEventsTableSceneLogicActions,Record<string, any>,liveEventsTableSceneLogicMeta>+function redirectIfLiveEventsRetired(): void {+ const onLiveEvents = router.values.location.pathname.endsWith(urls.activity(ActivityTab.LiveEvents))+ if (onLiveEvents && featureFlagLogic.values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ router.actions.replace(urls.activity(ActivityTab.ExploreEvents))+ }+}+export const liveEventsTableSceneLogic = kea<liveEventsTableSceneLogicType>([key(() => 'scene'),path((key) => ['scenes', 'activity', 'live-events', 'liveEventsTableSceneLogic', key]),@@ -37,4 +59,14 @@ export const liveEventsTableSceneLogic = kea<liveEventsTableSceneLogicType>([],],})),+ connect(() => ({+ actions: [featureFlagLogic, ['setFeatureFlags']],+ })),+ listeners(() => ({+ // Flags can resolve after the URL action ran, so check again when they arrive.+ setFeatureFlags: () => redirectIfLiveEventsRetired(),+ })),+ urlToAction(() => ({+ [urls.activity(ActivityTab.LiveEvents)]: () => redirectIfLiveEventsRetired(),+ })),])diff --git a/frontend/src/scenes/session-recordings/components/liveRecordingsCountLogic.ts b/frontend/src/scenes/session-recordings/components/liveRecordingsCountLogic.tsindex 215123d1c4d3..c15c48621bbf 100644--- a/frontend/src/scenes/session-recordings/components/liveRecordingsCountLogic.ts+++ b/frontend/src/scenes/session-recordings/components/liveRecordingsCountLogic.ts@@ -1,13 +1,11 @@-import { MakeLogicType, events, kea, path } from 'kea'-import { loaders } from 'kea-loaders'+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers } from 'kea'-import api from 'lib/api'+import { LIVE_COUNT_REFRESH_MS, loadCachedLiveCount } from 'lib/components/LiveUserCount/liveCountCache'+import { teamLogic } from 'scenes/teamLogic'import { QueryLogTags } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'-const POLL_INTERVAL_MS = 60000-const QUERY_TAGS: QueryLogTags = { scene: 'Replay', productKey: 'session_replay' }// The min_first_timestamp bound lets ClickHouse prune on the sort key; a session cannot run longer than a day.@@ -24,26 +22,24 @@ const LIVE_RECORDINGS_COUNT_QUERY = hogql`// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveRecordingsCountLogicValues {+ currentTeamId: number | null // teamLogicactiveRecordings: number | null- activeRecordingsLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface liveRecordingsCountLogicActions {- loadActiveRecordings: () => any- loadActiveRecordingsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadActiveRecordingsSuccess: (- activeRecordings: number | null,+ loadCurrentTeamSuccess: (+ currentTeam: null | import('../../../types').TeamPublicType,payload?: any) => {- activeRecordings: number | null+ currentTeam: null | import('../../../types').TeamPublicTypepayload?: any+ } // teamLogic+ pollActiveRecordings: () => {+ value: true+ }+ setActiveRecordings: (activeRecordings: number) => {+ activeRecordings: number}}@@ -54,36 +50,58 @@ export type liveRecordingsCountLogicType = MakeLogicType<export const liveRecordingsCountLogic = kea<liveRecordingsCountLogicType>([path(['scenes', 'session-recordings', 'components', 'liveRecordingsCountLogic']),- loaders(({ values }) => ({+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ actions: [teamLogic, ['loadCurrentTeamSuccess']],+ })),+ actions({+ pollActiveRecordings: true,+ setActiveRecordings: (activeRecordings: number) => ({ activeRecordings }),+ }),+ reducers({activeRecordings: [null as number | null,{- loadActiveRecordings: async () => {- // A failed poll keeps the last count instead of toasting every interval.- try {- // The default refresh mode would serve a cached count for up to 5 minutes.- const response = await api.queryHogQL<[number][]>(LIVE_RECORDINGS_COUNT_QUERY, QUERY_TAGS, {- refresh: 'force_blocking',- })- return response.results[0]?.[0] ?? 0- } catch {- return values.activeRecordings- }- },+ setActiveRecordings: (_, { activeRecordings }) => activeRecordings,},],+ }),+ listeners(({ actions, values, cache }) => ({+ loadCurrentTeamSuccess: () => {+ // Without a team, a poll skips the query and waits a full refresh interval, so poll again when the team loads.+ if (values.activeRecordings === null) {+ actions.pollActiveRecordings()+ }+ },+ pollActiveRecordings: async () => {+ let nextPollMs = LIVE_COUNT_REFRESH_MS+ try {+ if (values.currentTeamId) {+ const { value, fetchedAt } = await loadCachedLiveCount(+ 'recordings',+ values.currentTeamId,+ LIVE_RECORDINGS_COUNT_QUERY,+ QUERY_TAGS+ )+ if (cache.disposables.isDisposed) {+ return+ }+ actions.setActiveRecordings(value)+ nextPollMs = Math.max(0, fetchedAt + LIVE_COUNT_REFRESH_MS - Date.now())+ }+ } catch {+ // A failed poll keeps the last count instead of toasting every interval.+ }+ // Scheduling after the poll settles means two polls never overlap.+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => actions.pollActiveRecordings(), nextPollMs)+ return () => clearTimeout(timeoutId)+ }, 'pollTimeout')+ },})),- events(({ actions, values, cache }) => ({+ events(({ actions }) => ({afterMount: () => {- cache.disposables.add(() => {- actions.loadActiveRecordings()- const intervalId = setInterval(() => {- if (!values.activeRecordingsLoading) {- actions.loadActiveRecordings()- }- }, POLL_INTERVAL_MS)- return () => clearInterval(intervalId)- }, 'pollInterval')+ actions.pollActiveRecordings()},})),])diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsxindex f7b946b3f3c5..2461f16549d3 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx@@ -12,7 +12,7 @@ import clsx from 'clsx'import { useActions, useValues } from 'kea'import { ReactNode, useEffect, useMemo, useState } from 'react'-import { IconDrag, IconFilter, IconGlobe, IconPencil, IconX } from '@posthog/icons'+import { IconDrag, IconFilter, IconGlobe, IconPencil, IconRefresh, IconX } from '@posthog/icons'import { LemonBanner, LemonButton, LemonDivider, Popover, Spinner, Tooltip } from '@posthog/lemon-ui'import { FilterBar } from 'lib/components/FilterBar'@@ -100,6 +100,8 @@ const LiveDashboardFilterRow = ({const { setDeviceTypeFilter, setWebAnalyticsFilters, setIsPathCleaningEnabled } = useActions(webAnalyticsLogic)const { clearFilters } = useActions(webAnalyticsFilterLogic)const { isRefreshing } = useValues(liveWebAnalyticsMetricsLogic)+ const { loadInitialData } = useActions(liveWebAnalyticsMetricsLogic)+ const { featureFlags } = useValues(featureFlagLogic)const hasDomainFilter = !!validatedDomainFilter && validatedDomainFilter !== 'all'const livePropertyFilters = rawWebAnalyticsFilters.filter(isLiveStreamFilter)@@ -171,10 +173,22 @@ const LiveDashboardFilterRow = ({}right={<>- {isRefreshing && (- <Tooltip title="Refreshing live data">- <Spinner className="text-lg text-muted" />- </Tooltip>+ {featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL] ? (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconRefresh />}+ loading={isRefreshing}+ onClick={() => loadInitialData(true)}+ tooltip="Refresh live data"+ data-attr="web-analytics-live-refresh"+ />+ ) : (+ isRefreshing && (+ <Tooltip title="Refreshing live data">+ <Spinner className="text-lg text-muted" />+ </Tooltip>+ ))}{isEditing ? (<>diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsxindex 329b9cbb4afa..f60e7fe4c043 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx@@ -74,6 +74,7 @@ const LIVE_QUERY_CONCURRENCY = 4const LIVE_QUERY_MAX_ATTEMPTS = 3const LIVE_QUERY_RETRY_DELAY_MS = 250const RELOAD_DEBOUNCE_MS = 300+const HOGQL_RELOAD_INTERVAL_MS = 30000const PAUSE_GRACE_MS = 2000const TRANSIENT_QUERY_STATUSES = new Set([502, 503, 504])@@ -237,6 +238,9 @@ export interface liveWebAnalyticsMetricsLogicActions {setIsRefreshing: (refreshing: boolean) => {refreshing: boolean}+ setRecentEvents: (events: LiveEvent[]) => {+ events: LiveEvent[]+ }tickCurrentMinute: () => {value: true}@@ -341,6 +345,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypepauseStream: true,resumeStream: true,clearRecentEvents: true,+ setRecentEvents: (events: LiveEvent[]) => ({ events }),clearFilteredLiveUsers: true,})),reducers({@@ -506,6 +511,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType{addEvents: (state, { events }) => deduplicateEvents(state, events, 50),clearRecentEvents: () => [],+ setRecentEvents: (_, { events }) => events,},],}),@@ -694,6 +700,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypecache.loadAbortController?.abort()cache.eventsConnection?.abort()cache.geoConnection?.abort()+ cache.disposables.dispose('hogqlReload')cache.batch = []cache.geoBatch = []stopFlushInterval(cache as FlushCache)@@ -742,12 +749,14 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypeactions.updateConnection()actions.updateGeoConnection()+ const includeRecentEvents = !!values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]const data = await loadQueryData({dateFrom,dateTo: handoff,filters: values.liveFilters,filterTestAccounts: values.shouldFilterTestAccounts,includeCity: !!values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_CITY_BREAKDOWN],+ includeRecentEvents,filtersEnabled: true,doPathCleaning: values.pathCleaningFilters.length > 0,abortController,@@ -777,6 +786,12 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypedata.recentUsers ? getRecentUsersByLastSeenEntries(data.recentUsers) : [])cache.hasLoadedData = true+ if (includeRecentEvents) {+ // A failed query clears the feed, so the card never shows old events next to fresh metrics.+ actions.setRecentEvents(+ data.recentEvents ? toRecentLiveEvents(data.recentEvents, values.currentTeam?.id ?? 0) : []+ )+ }if (values.shouldLoadBots) {actions.setBotQueryStatus('loading')@@ -836,6 +851,13 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypecache.reloadQueuedDuringInit = falseresetStreamStateAndReload(cache as FlushCache, actions)}+ // Counted from load completion, so a load slower than the interval is never aborted by the next one.+ if (!signal.aborted && values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => actions.loadInitialData(true), HOGQL_RELOAD_INTERVAL_MS)+ return () => clearTimeout(timeoutId)+ }, 'hogqlReload')+ }}},scheduleReload: async (_, breakpoint) => {@@ -848,6 +870,12 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypeupdateConnection: () => {cache.eventsConnection?.abort()+ if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ // A new load is starting, so a reload scheduled by the previous one must not abort it.+ cache.disposables.dispose('hogqlReload')+ return+ }+const token = values.currentTeam?.live_events_tokenif (!token) {return@@ -904,6 +932,10 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypeupdateGeoConnection: () => {cache.geoConnection?.abort()+ if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {+ return+ }+const token = values.currentTeam?.live_events_tokenif (!token) {return@@ -1085,6 +1117,7 @@ interface LiveQueryData {geo: HogQLQueryResponse | nullrecentUsers: HogQLQueryResponse | nullcity: HogQLQueryResponse | null+ recentEvents: HogQLQueryResponse | nullallFailed: booleanfailedQueries: string[]}@@ -1100,6 +1133,7 @@ const LIVE_QUERY_LABELS: Record<LiveQueryKey, string> = {geo: 'locations',recentUsers: 'recent visitors',city: 'cities',+ recentEvents: 'live events',}interface LiveQueryContextParams {@@ -1143,6 +1177,7 @@ const loadQueryData = async ({filters,filterTestAccounts,includeCity,+ includeRecentEvents,filtersEnabled,doPathCleaning,abortController,@@ -1152,6 +1187,7 @@ const loadQueryData = async ({filters: WebAnalyticsPropertyFilter[]filterTestAccounts: booleanincludeCity: boolean+ includeRecentEvents: booleanfiltersEnabled: booleandoPathCleaning: booleanabortController: AbortController@@ -1361,6 +1397,22 @@ const loadQueryData = async ({if (cityQuery) {jobs.push({ key: 'city', query: cityQuery })}+ if (includeRecentEvents) {+ jobs.push({+ key: 'recentEvents',+ query: {+ kind: NodeKind.HogQLQuery,+ query: `SELECT uuid, event, distinct_id, toString(timestamp),+ properties.$current_url, properties.$screen_name, properties.$pathname, properties.$session_id+ FROM events+ WHERE ${whereClause}+ ORDER BY timestamp DESC+ LIMIT 50`,+ tags: liveQueryTags('live_recent_events'),+ ...queryParams,+ },+ })+ }const settled = await Promise.allSettled(jobs.map((job) =>@@ -1381,6 +1433,7 @@ const loadQueryData = async ({geo: null,recentUsers: null,city: null,+ recentEvents: null,allFailed: false,failedQueries: [],}@@ -1680,3 +1733,23 @@ const createEmptyBucket = (): SlidingWindowBucket => {bots: new Map<string, { count: number; category: string }>(),}}++type RecentEventRow = [string, string, string, string, string | null, string | null, string | null, string | null]++const toRecentLiveEvents = (response: HogQLQueryResponse, teamId: number): LiveEvent[] =>+ ((response.results ?? []) as RecentEventRow[]).map(+ ([uuid, event, distinctId, timestamp, currentUrl, screenName, pathname, sessionId]) => ({+ uuid,+ event,+ distinct_id: distinctId,+ timestamp,+ created_at: timestamp,+ team_id: teamId,+ properties: {+ $current_url: currentUrl,+ $screen_name: screenName,+ $pathname: pathname,+ $session_id: sessionId,+ },+ })+ )diff --git a/products/dashboards/frontend/widgets/live/liveWidgetStream.ts b/products/dashboards/frontend/widgets/live/liveWidgetStream.tsdeleted file mode 100644index 38c8d48ad192..000000000000--- a/products/dashboards/frontend/widgets/live/liveWidgetStream.ts+++ /dev/null@@ -1,130 +0,0 @@-import { connect, events, listeners } from 'kea'-import type { Logic, LogicBuilder } from 'kea'--import { createStreamConnection } from 'lib/api-stream'-import { liveEventsHostOrigin } from 'lib/utils/apiHost'-import { teamLogic } from 'scenes/teamLogic'--import type { LiveEvent, TeamPublicType, TeamType } from '~/types'--const FLUSH_INTERVAL_MS = 300-const MINUTE_TICK_INTERVAL_MS = 60_000--export interface LiveWidgetStreamSpec {- /** Livestream `eventType` query param, e.g. '$pageview'. Omit to stream all event types. */- eventType?: string- /** Livestream `columns` query param entries — the event properties the stream should include. */- columns?: string[]-}--export interface LiveWidgetStreamOptions {- /** Build the stream params from the current team; return null to skip connecting. */- getStreamSpec: (team: TeamType | TeamPublicType) => LiveWidgetStreamSpec | null- /**- * Receives streamed events, batched on a flush interval while the tab is visible. Dispatch into- * the consuming logic here via its wrapper (`myLogic.actions.x(...)`) — live widget logics are- * unkeyed shared logics by contract, so one connection serves every tile of the family.- */- onEvents: (liveEvents: LiveEvent[]) => void- /** Fires every 60s so time-windowed state can prune old minutes even without traffic. */- onMinuteTick?: () => void-}--/**- * Kea logic builder wiring a livestream SSE connection into a live widget's logic: one- * `createStreamConnection` to `${liveEventsHostOrigin()}/events` authed with the team's- * `live_events_token`, flush-batched `onEvents` delivery, and a minute tick for window pruning.- *- * All resources go through `cache.disposables`, so the stream tears down when the logic unmounts- * and pauses while the tab is hidden (reconnecting on show). The dropped span is healed by the- * next run_widgets re-seed — live seeds are idempotent by contract (see `LiveWidgetSeedPayload`).- *- * Connecting is re-evaluated on mount and whenever `currentTeam` resolves, because a tile can mount- * before teamLogic has loaded the team (scenes render as soon as the user is known) — without that- * the widget would sit on its seed forever. teamLogic also reloads the team on a poll, so the- * connection is keyed by token + URL and only rebuilt when one of them actually changes.- *- * The builder only adds `connect`/`events` wiring — kea-typegen cannot see builder-injected- * symbols, so the consuming logic declares its own actions/reducers/selectors and this builder- * dispatches into them through the callbacks.- */-export function liveWidgetStream<L extends Logic = Logic>(options: LiveWidgetStreamOptions): LogicBuilder<L> {- return (logic) => {- connect(() => ({- actions: [teamLogic, ['loadCurrentTeamSuccess', 'updateCurrentTeamSuccess']],- }))(logic)-- const syncConnection = (): void => {- const { cache } = logic- const team = teamLogic.values.currentTeam- const token = team?.live_events_token- const host = liveEventsHostOrigin()- if (!team || !token || !host) {- return- }- const spec = options.getStreamSpec(team)- if (!spec) {- return- }-- const url = new URL(`${host}/events`)- if (spec.eventType) {- url.searchParams.append('eventType', spec.eventType)- }- if (spec.columns?.length) {- url.searchParams.append('columns', spec.columns.join(','))- }-- const connectionKey = `${token}::${url.toString()}`- if (cache.liveWidgetStreamKey === connectionKey) {- return- }- cache.liveWidgetStreamKey = connectionKey-- let batch: LiveEvent[] = []-- // pauseOnPageHidden (default) aborts the stream when the tab hides and reconnects on show.- cache.disposables.add(() => {- batch = []- const connection = createStreamConnection({- url,- token,- onMessage: (data) => {- try {- batch.push(JSON.parse(data) as LiveEvent)- } catch (error) {- console.error('Failed to parse live widget event:', error)- }- },- onError: (error) => {- console.error('Live widget stream error:', error)- },- })- return () => connection.abort()- }, 'liveWidgetStream.connection')-- cache.disposables.add(() => {- const intervalId = setInterval(() => {- if (batch.length) {- options.onEvents(batch)- batch = []- }- }, FLUSH_INTERVAL_MS)- return () => clearInterval(intervalId)- }, 'liveWidgetStream.flush')-- if (options.onMinuteTick) {- cache.disposables.add(() => {- const intervalId = setInterval(() => options.onMinuteTick?.(), MINUTE_TICK_INTERVAL_MS)- return () => clearInterval(intervalId)- }, 'liveWidgetStream.tick')- }- }-- events(() => ({ afterMount: syncConnection }))(logic)- listeners(() => ({- loadCurrentTeamSuccess: syncConnection,- updateCurrentTeamSuccess: syncConnection,- }))(logic)- }-}