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(cdp): make invocations the default hog function runtime tab and fix batch invocations (#70986)

Meikel Ratz3ac3a8af6a05
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 94722a4f620f..b1fe15f54a2b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5931,13 +5931,13 @@ snapshots:
scenes-app-heatmaps-saved--list--light:
hash: v1.k794b7964.bcb55f9131fb7e69b676a856bb1986ab861ab9461e810e588893b263c648c007.1w2wOjJ9hrohsPO9aXHcRWx3b6TdoHidKTuuoZQ4fRA
scenes-app-hogfunctions-destination--backfills-empty--dark:
- hash: v1.k794b7964.3c1b03f71ed594a98926d29eb35cd2ab7855804ec9801ffec484ce26445e24e3.0wR-DIxE_KjowLILMEPt51tC8V2KHyiSV_ckGB4RY70
+ hash: v1.k794b7964.eb67efee739a283813a4a3389e86262a7e41ac1eeba32bb186f06fa8bfb1f825.eNxwQSwo8ogShZXZ-XuOi-T0AIJb-dNi0a032U9oBpY
scenes-app-hogfunctions-destination--backfills-empty--light:
- hash: v1.k794b7964.1f065fcf2db5b8949c7a12c4ef4b0e732e001950d569eb5fa87ab0453b5e6446.Lqk92H6DiTOMNzvKXdDQjdBacSOfPVN0xFR--vSIm0I
+ hash: v1.k794b7964.f22e05f12425b5ecb5af7e8428f79980f056a3669777039f42b63733707ee83f.CriiwpshesnRsgPx7IQ6qDrO3syD6S4FZ4QMXNgkN24
scenes-app-hogfunctions-destination--backfills-with-data--dark:
- hash: v1.k794b7964.032a23ce18000d4e5882689b013657d3e672429ed717a9b183e58d0d5917c127.AZZ2lDHxECvKkKgvSn2z-n5DFELjQLKG2mzCmp0-e4o
+ hash: v1.k794b7964.f997c130aa451adb720a44f782604a30d4c7b1d8a379b27d5faba71353d38f18.FfGiOC5m2u9wPKarvYxY7FHN1k2b-LIUH1o3V5fJIkI
scenes-app-hogfunctions-destination--backfills-with-data--light:
- hash: v1.k794b7964.075820a5a01ab9f557c7cd8277e613e54448c107f44d41e17c046cfe16f26347.06E6LIG-khXIFud2mT4zHE7j0p9ppPIHzy_JqINJvCs
+ hash: v1.k794b7964.f971c9b24daa779751f4ca9c4a58a6d640b1f1dc482c989521b5aed68d07f5ee.MRVlqmTBTYcUbMQypG59y05w-tbxT3zVWBzTz0rPUF4
scenes-app-hogfunctions-destination--configuration--dark:
hash: v1.k794b7964.bc345f77c32158f7789fa1f2b17bf2d4bf1e19989a15194c3f85440fdc11e118.4hbGee2ZusKi0DMKyI3lC-iCS1ID3wtUo7fgpUYkI8k
scenes-app-hogfunctions-destination--configuration--light:
@@ -5946,18 +5946,14 @@ snapshots:
hash: v1.k794b7964.27836a122e278f4f73483ff79900f08f75bcf01a50c56ed4db1630ef262bd563.LVx2x4gshmrHhfz6goJRqcAnJ1xvhCLyYo1AtHnWnvU
scenes-app-hogfunctions-destination--configuration-with-templating-warning--light:
hash: v1.k794b7964.819c775988c21f467569bbe3839e91810b737298bfd72f2a67bdff148ccc4a1a.bmqQ8PVCOsdRsnEY-bIyReFJ2bBV5S0X_a_uMirsQUA
- scenes-app-hogfunctions-destination--logs--dark:
- hash: v1.k794b7964.b4ce8699e52de8c47affcbad9181359fe8cb7fdf999aee3cdda2f79c2665ce49.ZS0AJdKJpOUSRuubkDMO7RFrUaGg7Nq-or0yMzYCkyw
- scenes-app-hogfunctions-destination--logs--light:
- hash: v1.k794b7964.cfc79ab8091f54e99c33541045c993ce27a3b5db7e96a9fa76ae6e5caf74dd71.HNuQYI8I0k3O8uwcTeUrtm-cJ462Lt5ud5V3RCuO3Dg
scenes-app-hogfunctions-destination--runs-empty--dark:
- hash: v1.k794b7964.74fbe6fbf08217ddace2d500bba76d006321c275e8238514c1f2ba2157171f8b.b9jTb_Q_XvY7uyOzojXCiGQjav63q0PjwED5WuZhCx0
+ hash: v1.k794b7964.9338d457e2d64f5a491115541fa681db1c44ab049531d9eec24d58fa056a31f0.mhgFOxcURq4YcXhnV16BaRPW4OAZ5mFkUBgjhDazfhg
scenes-app-hogfunctions-destination--runs-empty--light:
- hash: v1.k794b7964.363458367c547cac5b650c2aacdc2a31cfaf9c495ad0ce54ac82c41b3a3ba2f6._PT2XKYAGoVERoFYE2xvLOGhrhpBGKQTEjbBUsklfpQ
+ hash: v1.k794b7964.167756e358629948b843ded0c506a2788745d88fdfbe0e2420425568903be37e.c5EvxvbXDPnlunDHuQ32NvOQ51ILYxWkgfuYDCidRwg
scenes-app-hogfunctions-destination--runs-with-data--dark:
- hash: v1.k794b7964.54858c86de5e7a3e44a4f5d4618ced5e554f373f0a88a7d08769373a3c24287c.RT0cK9JOFugZYbJ2EmpjFQ4aHrEwCV8PfYk9ngXN62I
+ hash: v1.k794b7964.f3c8bc6697db692d759f57d5f1cba413b909e22923e87c65d0c223e613144076.sfVPBgq0NjbXJfcc8nye_vNXKKoaNiKVdX2kKdYWjug
scenes-app-hogfunctions-destination--runs-with-data--light:
- hash: v1.k794b7964.3b3004e30f5953c0b046939e2e4e20043e0d693dba37cce2dee8070933f03430.BqqPtqMQGPbp_1rkG0Lkj3EfrDZiOLYqNstTX8Z-uMY
+ hash: v1.k794b7964.7ebd6b1de8b3532192340ab4748697c7175fbb3e36227394abac3397e7fb36d5.g74q_2eAZTmStVOVUVR9w1MEZmTHfWR6PBmaj1xImiM
scenes-app-identitymatching--identity-matching-empty--dark:
hash: v1.k794b7964.30bea223b948150a5eb1a169b853333dd9815447869ccbbdc30c1cffe2b78cd2.v7d6U5tiu6DTfHv0ZI3PW0Ps99p-BlQI_MZc7DuESbM
scenes-app-identitymatching--identity-matching-empty--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 73aa909b6dc2..ee1db45eecf4 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -332,7 +332,6 @@ export const FEATURE_FLAGS = {
FUNNEL_INSIGHT_ALERTS: 'funnel-insight-alerts', // owner: @vdekrijger, gates alerts on funnel insights (conversion rate)
GROUP_PROFILE_EXPERIMENT: 'group-profile-experiment', // owner: @arthurdedeus #team-customer-analytics
HEALTH_ASK_AI: 'health-ask-ai', // owner: @jordanm-posthog #team-web-analytics, gates the "Ask PostHog AI" buttons on the Health overview
- HOG_INVOCATION_RESULTS_RUNS_TAB: 'hog-invocation-results-runs-tab', // owner: #team-workflows
HOGQL_INSIGHT_ALERTS: 'hogql-insight-alerts', // owner: @vdekrijger, gates alerts on SQL-backed (HogQL) insights
HOGQL_WAREHOUSE_ACCESS_CONTROL: 'hogql-warehouse-access-control', // owner: @a-lider #team-platform-features, gates per-object access control for warehouse tables and views
IDENTITY_MATCHING: 'identity-matching', // owner: @fercgomes #team-growth, gates new identity matching scene on marketing analytics
diff --git a/frontend/src/scenes/hog-functions/HogFunctionScene.stories.tsx b/frontend/src/scenes/hog-functions/HogFunctionScene.stories.tsx
index 9ce21bf0a60d..1698d597c55a 100644
--- a/frontend/src/scenes/hog-functions/HogFunctionScene.stories.tsx
+++ b/frontend/src/scenes/hog-functions/HogFunctionScene.stories.tsx
@@ -249,81 +249,3 @@ export const ConfigurationWithTemplatingWarning: Story = {
pageUrl: urls.hogFunction(MOCK_HOG_FUNCTION_TEMPLATING_WARNING_ID),
},
}
-
-const MOCK_HOG_FUNCTION_LOG_RESULTS = {
- results: [
- [
- 'invocation-aaa-bbb-ccc',
- '2024-01-15 10:00:00.000001',
- 'DEBUG',
- "Executing function on event 'https://example.com/events/abc123'",
- ],
- ['invocation-aaa-bbb-ccc', '2024-01-15 10:00:00.050002', 'INFO', 'fetch(POST, https://example.com/webhook)'],
- [
- 'invocation-aaa-bbb-ccc',
- '2024-01-15 10:00:00.250003',
- 'DEBUG',
- "Function completed in 250ms. Sync: 2ms. Mem: 128kb. Ops: 42. Event: 'https://example.com/events/abc123'",
- ],
- [
- 'invocation-ddd-eee-fff',
- '2024-01-15 10:01:00.000001',
- 'DEBUG',
- "Executing function on event 'https://example.com/events/def456'",
- ],
- ['invocation-ddd-eee-fff', '2024-01-15 10:01:00.050002', 'INFO', 'fetch(POST, https://example.com/webhook)'],
- [
- 'invocation-ddd-eee-fff',
- '2024-01-15 10:01:00.350003',
- 'ERROR',
- 'HTTP fetch failed on attempt 1 with status code 500. Retrying in 1000ms.',
- ],
- [
- 'invocation-ddd-eee-fff',
- '2024-01-15 10:01:01.400004',
- 'ERROR',
- 'HTTP fetch failed on attempt 2 with status code 500. Retrying in 2000ms.',
- ],
- [
- 'invocation-ddd-eee-fff',
- '2024-01-15 10:01:03.500005',
- 'ERROR',
- 'HTTP fetch failed on attempt 3 with status code 500.',
- ],
- [
- 'invocation-ggg-hhh-iii',
- '2024-01-15 10:02:00.000001',
- 'DEBUG',
- "Executing function on event 'https://example.com/events/ghi789'",
- ],
- ['invocation-ggg-hhh-iii', '2024-01-15 10:02:00.050002', 'INFO', 'fetch(POST, https://example.com/webhook)'],
- [
- 'invocation-ggg-hhh-iii',
- '2024-01-15 10:02:00.150003',
- 'DEBUG',
- "Function completed in 150ms. Sync: 1ms. Mem: 96kb. Ops: 38. Event: 'https://example.com/events/ghi789'",
- ],
- ],
-}
-
-export const Logs: Story = {
- parameters: {
- pageUrl: urls.hogFunction(MOCK_HOG_FUNCTION_ID, 'logs'),
- },
- decorators: [
- mswDecorator({
- ...commonMocks,
- get: {
- ...commonMocks.get,
- [`/api/environments/:team_id/batch_exports/${MOCK_BATCH_EXPORT_ID}/backfills/`]: {
- results: [],
- next: null,
- },
- },
- post: {
- ...commonMocks.post,
- '/api/environments/:team_id/query/HogQLQuery/': MOCK_HOG_FUNCTION_LOG_RESULTS,
- },
- }),
- ],
-}
diff --git a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
index 5a55163a0c10..6a47dfc128b7 100644
--- a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
+++ b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
@@ -33,8 +33,6 @@ import {
HogFunctionConfigurationLogicProps,
hogFunctionConfigurationLogic,
} from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
-import { HogFunctionLogs } from 'scenes/hog-functions/logs/HogFunctionLogs'
-import { HogFunctionTesting } from 'scenes/hog-functions/testing/HogFunctionTesting'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -60,16 +58,7 @@ import { HogFunctionMetrics } from './metrics/HogFunctionMetrics'
import { HogFunctionSkeleton } from './misc/HogFunctionSkeleton'
import { HogFunctionRuns } from './runs/HogFunctionRuns'
-const HOG_FUNCTION_SCENE_TABS = [
- 'configuration',
- 'metrics',
- 'logs',
- 'testing',
- 'runs',
- 'invocations',
- 'backfills',
- 'history',
-] as const
+const HOG_FUNCTION_SCENE_TABS = ['configuration', 'metrics', 'runs', 'invocations', 'backfills', 'history'] as const
export type HogFunctionSceneTab = (typeof HOG_FUNCTION_SCENE_TABS)[number]
const HogFunctionSceneMapping: Partial<Record<HogFunctionTypeType, { scene: Scene; url: () => string }>> = {
@@ -98,7 +87,7 @@ export interface hogFunctionSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionSceneLogicActions {
setCurrentTab: (tab: HogFunctionSceneTab) => {
- tab: 'backfills' | 'configuration' | 'history' | 'invocations' | 'logs' | 'metrics' | 'runs' | 'testing'
+ tab: 'backfills' | 'configuration' | 'history' | 'invocations' | 'metrics' | 'runs'
}
}
@@ -507,36 +496,10 @@ export function HogFunctionScene(): JSX.Element {
type === 'site_app' || type === 'site_destination'
? null
: {
- label: 'Logs',
- key: 'logs',
- content: <HogFunctionLogs />,
- },
- // New runs view backed by hog_invocation_results. Behind a flag while
- // the underlying ClickHouse producer ramps; subsumes the legacy
- // logs tab once it's GA.
- type === 'site_app' ||
- type === 'site_destination' ||
- !featureFlags[FEATURE_FLAGS.HOG_INVOCATION_RESULTS_RUNS_TAB]
- ? null
- : {
- label: (
- <div className="flex flex-row">
- <div>Invocations</div>
- <LemonTag className="ml-2 uppercase" type="warning">
- Beta
- </LemonTag>
- </div>
- ),
+ label: 'Invocations',
key: 'invocations',
content: <HogInvocations id={id} functionKind="hog_function" />,
},
- type === 'site_app' || type === 'site_destination' || type === 'internal_destination'
- ? null
- : {
- label: 'Testing',
- key: 'testing',
- content: <HogFunctionTesting />,
- },
supportsBackfills && featureFlags[FEATURE_FLAGS.BACKFILL_WORKFLOWS_DESTINATION]
? {
diff --git a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
index a5804f3ea4a1..c066324cb797 100644
--- a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
@@ -52,7 +52,6 @@ import {
isRerunWrapperKind,
} from './hogInvocationsLogic'
import { InvocationsSparkline } from './InvocationsSparkline'
-import { InvocationsBetaBanner } from './InvocationsTabBanners'
const STATUS_OPTIONS: { value: RunStatus; label: string }[] = [
{ value: 'running', label: 'Running' },
@@ -221,14 +220,27 @@ export interface HogInvocationsProps extends HogInvocationsLogicProps {
* matching the standalone Logs tab. Defaults to the hog-function renderer.
*/
renderLogMessage?: (message: string) => JSX.Element | string
+ /**
+ * Trim the chrome for an embedded view — hides the sparkline, the person/kind/
+ * logged-errors filters, and the bulk re-run modal. Used by the batch view, which
+ * renders one scoped table per broadcast inside a collapsible panel.
+ */
+ compact?: boolean
}
/**
* Rerun is async — posting to `/rerun` enqueues a cyclotron wrapper job; new
* lifecycle rows show up here once the worker drains it.
*/
-export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvocationsProps): JSX.Element | null {
- const logic = hogInvocationsLogic({ id, functionKind })
+export function HogInvocations({
+ id,
+ functionKind,
+ renderLogMessage,
+ compact,
+ parentRunId,
+ defaultDateFrom,
+}: HogInvocationsProps): JSX.Element | null {
+ const logic = hogInvocationsLogic({ id, functionKind, parentRunId, defaultDateFrom })
const {
runs,
runsLoading,
@@ -469,12 +481,13 @@ export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvoca
return (
<div className="flex-1 deprecated-space-y-2 flex flex-col min-w-0">
- <InvocationsBetaBanner />
- <InvocationsSparkline
- data={sparkline}
- loading={sparklineLoading}
- onDateRangeChange={(date_from, date_to) => setFilters({ date_from, date_to })}
- />
+ {compact ? null : (
+ <InvocationsSparkline
+ data={sparkline}
+ loading={sparklineLoading}
+ onDateRangeChange={(date_from, date_to) => setFilters({ date_from, date_to })}
+ />
+ )}
<div className="flex flex-wrap items-center gap-2 justify-between">
<div className="flex items-center gap-2 flex-1 min-w-100">
<LemonInput
@@ -489,7 +502,7 @@ export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvoca
prefix={<IconSearch />}
allowClear
/>
- <PersonFilterPicker id={id} functionKind={functionKind} />
+ {compact ? null : <PersonFilterPicker id={id} functionKind={functionKind} />}
</div>
<div className="flex items-center gap-2 flex-wrap">
<StatusFilterDropdown
@@ -500,30 +513,34 @@ export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvoca
})
}
/>
- <LemonSelect<'all' | 'invocations' | 'rerun_jobs'>
- size="small"
- value={filters.kind ?? 'all'}
- onChange={(v) =>
- setFilters({
- kind: v === 'invocations' || v === 'rerun_jobs' ? v : undefined,
- })
- }
- options={[
- { value: 'all', label: 'All rows' },
- { value: 'invocations', label: 'Invocations only' },
- { value: 'rerun_jobs', label: 'Rerun jobs only' },
- ]}
- />
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconWarning />}
- active={!!filters.problem_only}
- onClick={() => setFilters({ problem_only: filters.problem_only ? undefined : true })}
- tooltip="Show only runs that logged an error or warning — e.g. an email bounce or complaint that arrived after the run finished"
- >
- Logged errors
- </LemonButton>
+ {compact ? null : (
+ <>
+ <LemonSelect<'all' | 'invocations' | 'rerun_jobs'>
+ size="small"
+ value={filters.kind ?? 'all'}
+ onChange={(v) =>
+ setFilters({
+ kind: v === 'invocations' || v === 'rerun_jobs' ? v : undefined,
+ })
+ }
+ options={[
+ { value: 'all', label: 'All rows' },
+ { value: 'invocations', label: 'Invocations only' },
+ { value: 'rerun_jobs', label: 'Rerun jobs only' },
+ ]}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconWarning />}
+ active={!!filters.problem_only}
+ onClick={() => setFilters({ problem_only: filters.problem_only ? undefined : true })}
+ tooltip="Show only runs that logged an error or warning — e.g. an email bounce or complaint that arrived after the run finished"
+ >
+ Logged errors
+ </LemonButton>
+ </>
+ )}
<DateFilter
size="small"
dateTo={filters.date_to ?? undefined}
@@ -549,28 +566,32 @@ export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvoca
>
Refresh
</LemonButton>
- <LemonButton
- size="small"
- type="primary"
- icon={<IconRevert />}
- onClick={() => setRerunModalOpen(true)}
- >
- Re-run…
- </LemonButton>
+ {compact ? null : (
+ <LemonButton
+ size="small"
+ type="primary"
+ icon={<IconRevert />}
+ onClick={() => setRerunModalOpen(true)}
+ >
+ Re-run…
+ </LemonButton>
+ )}
</div>
</div>
- <RerunModal
- isOpen={rerunModalOpen}
- onClose={() => setRerunModalOpen(false)}
- initialDateFrom={filters.date_from}
- initialDateTo={filters.date_to}
- countMatches={(params) => countRerunMatches({ id, functionKind }, params)}
- onSubmit={(params) => {
- bulkRerun(params)
- setRerunModalOpen(false)
- }}
- />
+ {compact ? null : (
+ <RerunModal
+ isOpen={rerunModalOpen}
+ onClose={() => setRerunModalOpen(false)}
+ initialDateFrom={filters.date_from}
+ initialDateTo={filters.date_to}
+ countMatches={(params) => countRerunMatches({ id, functionKind }, params)}
+ onSubmit={(params) => {
+ bulkRerun(params)
+ setRerunModalOpen(false)
+ }}
+ />
+ )}
{selectedCount > 0 ? (
<div className="flex items-center justify-between border rounded p-2 bg-bg-light">
@@ -697,9 +718,11 @@ function RunDetail({
renderLogMessage?: (message: string) => JSX.Element | string
}): JSX.Element {
const isRerunWrapper = isRerunWrapperKind(record.function_kind)
+ // A batch child's log entries are keyed under the batch run (parent_run_id) as the log
+ // source, not the workflow id — so fetch this run's logs from there when it's a child.
const logsLogicProps: LogsViewerLogicProps = {
sourceType: functionKind,
- sourceId: hogFunctionId,
+ sourceId: record.parent_run_id || hogFunctionId,
logicKey: `invocations-${record.invocation_id}`,
defaultFilters: { instanceId: record.invocation_id },
groupByInstanceId: false,
diff --git a/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsx b/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsx
deleted file mode 100644
index 89a06348f482..000000000000
--- a/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useValues } from 'kea'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-export function InvocationsLegacyTabBanner({
- legacyTab,
-}: {
- legacyTab: 'Logs' | 'Testing' | 'Invocations (legacy)'
-}): JSX.Element | null {
- const { featureFlags } = useValues(featureFlagLogic)
- if (!featureFlags[FEATURE_FLAGS.HOG_INVOCATION_RESULTS_RUNS_TAB]) {
- return null
- }
- return (
- <LemonBanner
- type="warning"
- dismissKey={`invocations-legacy-${legacyTab.toLowerCase().replace(/\s+/g, '-')}-banner`}
- className="mb-2"
- >
- This {legacyTab} view will be replaced by the new <strong>Invocations</strong> tab soon.
- </LemonBanner>
- )
-}
-
-export function InvocationsBetaBanner(): JSX.Element {
- return (
- <LemonBanner type="warning" dismissKey="invocations-beta-banner" className="mb-2">
- Invocations is in beta — it will replace the Logs and Testing tabs.
- </LemonBanner>
- )
-}
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts
index aa0aa65ea512..c177e771a419 100644
--- a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts
@@ -1,47 +1,117 @@
-import { buildSearchClause } from './hogInvocationsLogic'
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
-describe('buildSearchClause', () => {
- const props = { id: 'flow-1', functionKind: 'hog_flow' as const }
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
- it('returns an empty clause when no search is set', () => {
- // An empty clause when a search IS set (covered below) would silently show every run — the
- // failure mode worth locking.
- expect(buildSearchClause(props, { date_from: '-24h' }).raw).toBe('')
- })
+import { buildSearchClause, hogInvocationsLogic, parentClauseFor } from './hogInvocationsLogic'
+
+describe('hogInvocationsLogic', () => {
+ describe('buildSearchClause', () => {
+ const props = { id: 'flow-1', functionKind: 'hog_flow' as const }
+
+ it('returns an empty clause when no search is set', () => {
+ // An empty clause when a search IS set (covered below) would silently show every run — the
+ // failure mode worth locking.
+ expect(buildSearchClause(props, { date_from: '-24h' }).raw).toBe('')
+ })
+
+ it('matches the typed term as an exact id OR a log-message substring', () => {
+ // One typed term goes into every arm: it's compared for equality against each id column (paste
+ // an id to find that run) and, via a log_entries subquery, as a substring of the message (type
+ // words to find a run that logged them). So the same term appears in all arms below.
+ const clause = buildSearchClause(props, { date_from: '-24h', search: 'run-42' }).raw
+ expect(clause).toContain("invocation_id = 'run-42'")
+ expect(clause).toContain("event_uuid = 'run-42'")
+ expect(clause).toContain("distinct_id = 'run-42'")
+ expect(clause).toContain("person_id = 'run-42'")
+ expect(clause).toContain('FROM log_entries')
+ expect(clause).toContain("message ILIKE concat('%', 'run-42', '%')")
+ // No level narrowing for a manual search — it matches any level.
+ expect(clause).not.toContain('lower(level)')
+ })
+
+ it('narrows the message match to log_levels when a drill-down sets them', () => {
+ // Drill-downs carry levels so "Bounced" (WARN/ERROR) does not also match the INFO
+ // "Email sent to bounce@…" log.
+ const clause = buildSearchClause(props, {
+ date_from: '-24h',
+ search: 'bounce',
+ log_levels: ['WARN', 'ERROR'],
+ }).raw
+ expect(clause).toContain("message ILIKE concat('%', 'bounce', '%')")
+ expect(clause).toContain("lower(level) IN ('warn','error')")
+ })
- it('matches the typed term as an exact id OR a log-message substring', () => {
- // One typed term goes into every arm: it's compared for equality against each id column (paste
- // an id to find that run) and, via a log_entries subquery, as a substring of the message (type
- // words to find a run that logged them). So the same term appears in all arms below.
- const clause = buildSearchClause(props, { date_from: '-24h', search: 'run-42' }).raw
- expect(clause).toContain("invocation_id = 'run-42'")
- expect(clause).toContain("event_uuid = 'run-42'")
- expect(clause).toContain("distinct_id = 'run-42'")
- expect(clause).toContain("person_id = 'run-42'")
- expect(clause).toContain('FROM log_entries')
- expect(clause).toContain("message ILIKE concat('%', 'run-42', '%')")
- // No level narrowing for a manual search — it matches any level.
- expect(clause).not.toContain('lower(level)')
+ it('escapes ILIKE wildcards in the message arm but not the id arms', () => {
+ // Typing "a%b" must match that literal text in messages, not "a<anything>b". The % is
+ // backslash-escaped only for the ILIKE arm (then doubled by escapeHogQLString for the SQL
+ // literal); the exact-id arms keep the raw term.
+ const clause = buildSearchClause(props, { date_from: '-24h', search: 'a%b' }).raw
+ expect(clause).toContain("invocation_id = 'a%b'")
+ expect(clause).toContain("message ILIKE concat('%', 'a\\\\%b', '%')")
+ })
})
- it('narrows the message match to log_levels when a drill-down sets them', () => {
- // Drill-downs carry levels so "Bounced" (WARN/ERROR) does not also match the INFO
- // "Email sent to bounce@…" log.
- const clause = buildSearchClause(props, {
- date_from: '-24h',
- search: 'bounce',
- log_levels: ['WARN', 'ERROR'],
- }).raw
- expect(clause).toContain("message ILIKE concat('%', 'bounce', '%')")
- expect(clause).toContain("lower(level) IN ('warn','error')")
+ describe('parentClauseFor', () => {
+ const base = { id: 'flow-1', functionKind: 'hog_flow' as const }
+
+ it('returns an empty clause when no parent run is scoped', () => {
+ // Unscoped is the flat list. A non-empty clause here would wrongly filter the whole workflow's runs.
+ expect(parentClauseFor(base).raw).toBe('')
+ })
+
+ it('scopes to the batch job id when parentRunId is set', () => {
+ // The batch view depends on this: without it a job's table shows every run for the workflow,
+ // not just that broadcast's. The id goes in as an escaped HogQL string literal.
+ expect(parentClauseFor({ ...base, parentRunId: 'job-1' }).raw).toBe("AND parent_run_id = 'job-1'")
+ })
})
- it('escapes ILIKE wildcards in the message arm but not the id arms', () => {
- // Typing "a%b" must match that literal text in messages, not "a<anything>b". The % is
- // backslash-escaped only for the ILIKE arm (then doubled by escapeHogQLString for the SQL
- // literal); the exact-id arms keep the raw term.
- const clause = buildSearchClause(props, { date_from: '-24h', search: 'a%b' }).raw
- expect(clause).toContain("invocation_id = 'a%b'")
- expect(clause).toContain("message ILIKE concat('%', 'a\\\\%b', '%')")
+ describe('parent-run scope isolation', () => {
+ beforeEach(() => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ })
+ initKeaTests()
+ })
+
+ it('does not write a scoped table filters to the shared URL', async () => {
+ // Several per-job tables can mount on one scene; if a scoped one wrote inv_* params it would
+ // clobber the flat list and its siblings. The parentRunId guard in actionToUrl prevents that.
+ const scoped = hogInvocationsLogic({ id: 'flow-1', functionKind: 'hog_flow', parentRunId: 'job-1' })
+ scoped.mount()
+ const before = { ...router.values.searchParams }
+ await expectLogic(scoped, () => {
+ scoped.actions.setFilters({ date_from: '-7d' })
+ }).toDispatchActions(['setFilters'])
+ expect(router.values.searchParams).toEqual(before)
+ scoped.unmount()
+ })
+
+ it('the flat list still writes its filters to the URL', async () => {
+ const flat = hogInvocationsLogic({ id: 'flow-1', functionKind: 'hog_flow' })
+ flat.mount()
+ await expectLogic(flat, () => {
+ flat.actions.setFilters({ date_from: '-7d' })
+ }).toDispatchActions(['setFilters'])
+ expect(router.values.searchParams.inv_date_from).toBe('-7d')
+ flat.unmount()
+ })
+
+ it('anchors the initial window to defaultDateFrom for a scoped table', () => {
+ // A broadcast older than 24h would show no runs if the scoped table used the default -24h window.
+ const scoped = hogInvocationsLogic({
+ id: 'flow-1',
+ functionKind: 'hog_flow',
+ parentRunId: 'job-1',
+ defaultDateFrom: '2026-01-01',
+ })
+ scoped.mount()
+ expect(scoped.values.filters.date_from).toBe('2026-01-01')
+ scoped.unmount()
+ })
})
})
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
index 8adf6c84e648..192840f4b73d 100644
--- a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
@@ -94,6 +94,18 @@ export interface HogInvocationsLogicProps {
/** HogFunction.id or HogFlow.id */
id: string
functionKind: HogInvocationsFunctionKind
+ /**
+ * Scope the list to invocations spawned by a single parent run. Batch-triggered
+ * workflows fan out one child invocation per person, each tagged with the batch
+ * job's id as `parent_run_id` — passing it here renders that broadcast's runs on
+ * their own, so the batch scene can group runs by job (see `WorkflowBatchInvocations`).
+ */
+ parentRunId?: string
+ /**
+ * Override the default date window (`-24h`). The per-job batch view anchors this to
+ * the job's creation time so a broadcast's runs are in range no matter how old it is.
+ */
+ defaultDateFrom?: string
}
export interface SparklineSeries {
@@ -326,6 +338,16 @@ export const kindClauseFor = (
return hogql.raw(`function_kind IN ('${props.functionKind}', '${wrapperKind}')`)
}
+/**
+ * Optional predicate scoping the list to one parent run (a batch job). Empty when
+ * `parentRunId` isn't set, so the flat list is unchanged. Placement depends on the query:
+ * put it in WHERE when it reads the physical `parent_run_id` column, but in HAVING when the
+ * SELECT aliases `parent_run_id` to `argMax(parent_run_id, version)` — there the name
+ * resolves to that aggregate alias, which ClickHouse rejects in WHERE.
+ */
+export const parentClauseFor = (props: HogInvocationsLogicProps): ReturnType<typeof hogql.raw> =>
+ props.parentRunId ? hogql.raw(`AND parent_run_id = ${escapeHogQLString(props.parentRunId)}`) : hogql.raw('')
+
/**
* Optional predicate restricting to invocations that logged an error/warning entry. Uses a
* `log_entries` subquery (resolved server-side, so no client-side id list) keyed by the same
@@ -480,6 +502,7 @@ async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvoc
FROM posthog.hog_invocation_results
WHERE ${kindClause}
AND function_id = ${props.id}
+ ${parentClauseFor(props)}
${dateClause}
GROUP BY invocation_id, function_kind
HAVING argMax(is_deleted, version) = 0
@@ -581,6 +604,7 @@ async function fetchRunsPage(
${dateClause}
GROUP BY invocation_id, function_kind
HAVING argMax(is_deleted, version) = 0
+ ${parentClauseFor(props)}
${optionalStatusClause}
${optionalErrorKindClause}
${buildSearchClause(props, filters)}
@@ -914,7 +938,7 @@ export type hogInvocationsLogicType = MakeLogicType<
export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
path((id) => ['scenes', 'hog-functions', 'invocations', 'hogInvocationsLogic', id]),
props({} as HogInvocationsLogicProps),
- key((props) => `${props.functionKind}:${props.id}`),
+ key((props) => `${props.functionKind}:${props.id}${props.parentRunId ? `:${props.parentRunId}` : ''}`),
actions({
setFilters: (filters: Partial<HogInvocationsFilters>) => ({ filters }),
@@ -935,70 +959,75 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
setPickedPerson: (person: PersonType | null) => ({ person }),
}),
- reducers({
- filters: [
- DEFAULT_FILTERS,
- {
- setFilters: (state, { filters }) => ({ ...state, ...filters }),
- resetFilters: () => DEFAULT_FILTERS,
- },
- ],
- selectedIds: [
- {} as Record<string, boolean>,
- {
- toggleSelected: (state, { invocationId }) => {
- const next = { ...state }
- if (next[invocationId]) {
- delete next[invocationId]
- } else {
- next[invocationId] = true
- }
- return next
+ reducers(({ props }) => {
+ const defaultFilters: HogInvocationsFilters = props.defaultDateFrom
+ ? { ...DEFAULT_FILTERS, date_from: props.defaultDateFrom }
+ : DEFAULT_FILTERS
+ return {
+ filters: [
+ defaultFilters,
+ {
+ setFilters: (state, { filters }) => ({ ...state, ...filters }),
+ resetFilters: () => defaultFilters,
},
- clearSelected: () => ({}),
- setSelectedIds: (_, { ids }) => Object.fromEntries(ids.map((id) => [id, true])),
- },
- ],
- expandedIds: [
- {} as Record<string, boolean>,
- {
- setExpanded: (state, { invocationId, expanded }) => {
- const next = { ...state }
- if (expanded) {
- next[invocationId] = true
- } else {
- delete next[invocationId]
- }
- return next
+ ],
+ selectedIds: [
+ {} as Record<string, boolean>,
+ {
+ toggleSelected: (state, { invocationId }) => {
+ const next = { ...state }
+ if (next[invocationId]) {
+ delete next[invocationId]
+ } else {
+ next[invocationId] = true
+ }
+ return next
+ },
+ clearSelected: () => ({}),
+ setSelectedIds: (_, { ids }) => Object.fromEntries(ids.map((id) => [id, true])),
},
- },
- ],
- hasMore: [
- false,
- {
- setHasMore: (_, { hasMore }) => hasMore,
- setFilters: () => false,
- resetFilters: () => false,
- },
- ],
- hasLoadedOnce: [
- false,
- {
- setHasMore: () => true,
- },
- ],
- pickedPerson: [
- null as PersonType | null,
- {
- setPickedPerson: (_, { person }) => person,
- // A URL-driven filter change without a matching pickedPerson means we came in
- // from a shared link — clear the stale display until the hydrator populates it.
- // `person.uuid` is the actual UUID; `person.id` is Django's numeric PK.
- setFilters: (state, { filters }) =>
- 'person_uuid' in filters && filters.person_uuid !== state?.uuid ? null : state,
- resetFilters: () => null,
- },
- ],
+ ],
+ expandedIds: [
+ {} as Record<string, boolean>,
+ {
+ setExpanded: (state, { invocationId, expanded }) => {
+ const next = { ...state }
+ if (expanded) {
+ next[invocationId] = true
+ } else {
+ delete next[invocationId]
+ }
+ return next
+ },
+ },
+ ],
+ hasMore: [
+ false,
+ {
+ setHasMore: (_, { hasMore }) => hasMore,
+ setFilters: () => false,
+ resetFilters: () => false,
+ },
+ ],
+ hasLoadedOnce: [
+ false,
+ {
+ setHasMore: () => true,
+ },
+ ],
+ pickedPerson: [
+ null as PersonType | null,
+ {
+ setPickedPerson: (_, { person }) => person,
+ // A URL-driven filter change without a matching pickedPerson means we came in
+ // from a shared link — clear the stale display until the hydrator populates it.
+ // `person.uuid` is the actual UUID; `person.id` is Django's numeric PK.
+ setFilters: (state, { filters }) =>
+ 'person_uuid' in filters && filters.person_uuid !== state?.uuid ? null : state,
+ resetFilters: () => null,
+ },
+ ],
+ }
}),
loaders(({ props, values, actions, cache }) => ({
@@ -1332,7 +1361,12 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
},
})),
- actionToUrl(({ values }) => {
+ actionToUrl(({ values, props }) => {
+ // Per-job scoped tables (batch view) don't own the URL — several can mount on one
+ // scene and they'd clobber the shared `inv_*` params. Only the flat list syncs.
+ if (props.parentRunId) {
+ return {}
+ }
const buildUrl = (): [
string,
Record<string, string | undefined>,
@@ -1350,8 +1384,13 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
}
}),
- urlToAction(({ actions, values }) => {
+ urlToAction(({ actions, values, props }) => {
const handleSearch = (_: any, searchParams: Record<string, string | undefined>): void => {
+ // Per-job scoped tables (batch view) don't own the URL — several can mount on one
+ // scene and they'd clobber the shared `inv_*` params. Only the flat list syncs.
+ if (props.parentRunId) {
+ return
+ }
const next = searchParamsToFilters(searchParams)
// Diff against current state to avoid looping with actionToUrl.
const changed = Object.entries(next).some(
diff --git a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx b/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx
deleted file mode 100644
index da987cb35708..000000000000
--- a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-import { useMemo } from 'react'
-
-import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonDialog, LemonMenu, LemonTag } from '@posthog/lemon-ui'
-
-import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { capitalizeFirstLetter } from 'lib/utils/strings'
-import { urls } from 'scenes/urls'
-
-import { hogFunctionConfigurationLogic } from '../configuration/hogFunctionConfigurationLogic'
-import { hogFunctionTestLogic } from '../configuration/hogFunctionTestLogic'
-import { InvocationsLegacyTabBanner } from '../invocations/InvocationsTabBanners'
-import { hogFunctionLogsLogic } from './hogFunctionLogsLogic'
-import { LogsViewer } from './LogsViewer'
-import { GroupedLogEntry, LogsViewerLogicProps } from './logsViewerLogic'
-import { renderHogFunctionMessage } from './renderHogFunctionMessage'
-
-export function HogFunctionLogs(): JSX.Element | null {
- const { logicProps } = useValues(hogFunctionConfigurationLogic)
- const id = logicProps.id
- const logsLogicProps: LogsViewerLogicProps = {
- sourceType: 'hog_function',
- sourceId: logicProps.id ?? 'unknown',
- }
- const logic = hogFunctionLogsLogic(logsLogicProps)
-
- const { selectingMany, selectedForRetry, retryRunning } = useValues(logic)
- const { setSelectingMany, retrySelectedInvocations, selectAllForRetry } = useActions(logic)
-
- if (!id) {
- return null
- }
-
- return (
- <>
- <InvocationsLegacyTabBanner legacyTab="Logs" />
- {selectingMany ? (
- <div className="flex gap-2 items-center mb-2 justify-end">
- <>
- <LemonButton size="small" type="secondary" onClick={() => setSelectingMany(false)}>
- Cancel
- </LemonButton>
- <LemonButton size="small" type="secondary" onClick={() => selectAllForRetry()}>
- Select all
- </LemonButton>
- <LemonButton
- size="small"
- type="primary"
- onClick={() => {
- LemonDialog.open({
- title: 'Retry invocations',
- content: `Are you sure you want to retry the selected events? Please don't close the window until the invocations have completed.`,
- secondaryButton: {
- children: 'Cancel',
- },
- primaryButton: {
- children: 'Retry selected events',
- onClick: () => retrySelectedInvocations(),
- },
- })
- }}
- loading={retryRunning}
- disabledReason={
- retryRunning
- ? 'Please wait for the current retries to complete.'
- : Object.values(selectedForRetry).length === 0
- ? 'No invocations selected'
- : undefined
- }
- >
- Retry selected
- </LemonButton>
- </>
- </div>
- ) : null}
- <LogsViewer
- {...logsLogicProps}
- sourceId={id}
- renderColumns={(columns) => {
- // Add in custom columns for handling retries
- const newColumns: LemonTableColumns<GroupedLogEntry> = [
- {
- title: 'Status',
- key: 'status',
- width: 0,
- render: (_, record) => <HogFunctionLogsStatus record={record} hogFunctionId={id} />,
- },
- ...columns.filter((column) => column.key !== 'logLevel'),
- ]
-
- return newColumns
- }}
- renderMessage={(message) => renderHogFunctionMessage(message)}
- />
- </>
- )
-}
-
-type HogFunctionLogsStatus = 'success' | 'failure' | 'running'
-
-function HogFunctionLogsStatus({
- record,
- hogFunctionId,
-}: {
- record: GroupedLogEntry
- hogFunctionId: string
-}): JSX.Element {
- const logicProps: LogsViewerLogicProps = {
- sourceType: 'hog_function',
- sourceId: hogFunctionId,
- }
- const { loadSampleGlobals, toggleExpanded } = useActions(hogFunctionTestLogic({ id: hogFunctionId }))
- const { contextId } = useValues(hogFunctionConfigurationLogic({ id: hogFunctionId }))
-
- const { retries, selectingMany, selectedForRetry, eventIdByInvocationId } = useValues(
- hogFunctionLogsLogic(logicProps)
- )
- const { retryInvocations, setSelectingMany, setSelectedForRetry } = useActions(hogFunctionLogsLogic(logicProps))
-
- const thisRetry = retries[record.instanceId]
-
- const status = useMemo<HogFunctionLogsStatus>((): HogFunctionLogsStatus => {
- if (thisRetry === 'pending') {
- return 'running'
- }
-
- const lastEntry = record.entries[record.entries.length - 1]
-
- if (lastEntry.message.includes('Function completed') || lastEntry.message.includes('Execution successful')) {
- return 'success'
- }
-
- if (lastEntry.level === 'ERROR') {
- return 'failure'
- }
-
- return 'running'
- }, [record, thisRetry])
-
- const eventId = eventIdByInvocationId?.[record.instanceId]
-
- const internalEvent = ['error-tracking', 'insight-alerts', 'activity-log'].includes(contextId)
-
- return (
- <div className="flex items-center gap-2">
- {selectingMany ? (
- <LemonCheckbox
- checked={selectedForRetry[record.instanceId] ?? false}
- onChange={(checked) => setSelectedForRetry({ [record.instanceId]: checked })}
- />
- ) : null}
- <LemonTag type={status === 'success' ? 'success' : status === 'failure' ? 'danger' : 'warning'}>
- {capitalizeFirstLetter(status)}
- </LemonTag>
-
- {!internalEvent && (
- <LemonMenu
- items={[
- eventId
- ? {
- label: 'View event',
- to: urls.event(eventId, ''),
- }
- : null,
- {
- label: 'Retry event',
- disabledReason: !eventId ? 'Could not find the source event' : undefined,
- onClick: () => retryInvocations([record]),
- },
- {
- label: 'Select for retry',
- onClick: () => {
- setSelectingMany(true)
- setSelectedForRetry({
- [record.instanceId]: true,
- })
- },
- },
- {
- label: 'Test with this event in configuration',
- onClick: () => {
- loadSampleGlobals({ eventId })
- toggleExpanded(true)
- router.actions.push(urls.hogFunction(hogFunctionId) + '?tab=configuration')
- },
- },
- ]}
- >
- <LemonButton
- size="xsmall"
- icon={<IconEllipsis className="rotate-90" />}
- loading={thisRetry === 'pending'}
- />
- </LemonMenu>
- )}
- </div>
- )
-}
diff --git a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
deleted file mode 100644
index f11ed111719a..000000000000
--- a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
+++ /dev/null
@@ -1,490 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-import { Form } from 'kea-forms'
-import { router } from 'kea-router'
-import { useState } from 'react'
-
-import { IconEllipsis, IconRefresh } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonCheckbox,
- LemonDialog,
- LemonDropdown,
- LemonMenu,
- LemonTable,
- LemonTag,
- LemonTagType,
- Tooltip,
-} from '@posthog/lemon-ui'
-
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { TZLabel } from 'lib/components/TZLabel'
-import { capitalizeFirstLetter } from 'lib/utils/strings'
-import { InsightEmptyState } from 'scenes/insights/EmptyStates'
-import { PersonDisplay } from 'scenes/persons/PersonDisplay'
-import { urls } from 'scenes/urls'
-
-import { CyclotronJobInvocationGlobals, GroupType, GroupTypeIndex, LogEntry } from '~/types'
-
-import {
- convertToHogFunctionInvocationGlobals,
- hogFunctionConfigurationLogic,
-} from '../configuration/hogFunctionConfigurationLogic'
-import { hogFunctionTestLogic } from '../configuration/hogFunctionTestLogic'
-import { HogFunctionFilters } from '../filters/HogFunctionFilters'
-import { InvocationsLegacyTabBanner } from '../invocations/InvocationsTabBanners'
-import { tagTypeForLevel } from '../logs/LogsViewer'
-import { CyclotronJobTestInvocationResultWithEventId, hogFunctionTestingLogic } from './hogFunctionTestingLogic'
-
-const buildGlobals = (
- row: any,
- groupTypes: Map<GroupTypeIndex, GroupType>,
- hogFunctionName: string
-): CyclotronJobInvocationGlobals => {
- const globals = convertToHogFunctionInvocationGlobals(row[0], row[1])
- globals.groups = {}
- groupTypes.forEach((groupType, index) => {
- const tuple = row?.[4 + index]
- if (tuple && Array.isArray(tuple) && tuple[2]) {
- let properties = {}
- try {
- properties = JSON.parse(tuple[3])
- } catch {
- // Ignore
- }
- globals.groups![groupType.group_type] = {
- type: groupType.group_type,
- index: tuple[1],
- id: tuple[2], // TODO: rename to "key"?
- url: `${window.location.origin}/groups/${tuple[1]}/${encodeURIComponent(tuple[2])}`,
- properties,
- }
- }
- })
- globals.source = {
- name: hogFunctionName ?? 'Unnamed',
- url: window.location.href.split('#')[0],
- }
-
- return globals
-}
-
-export function HogFunctionTesting(): JSX.Element | null {
- const { logicProps } = useValues(hogFunctionConfigurationLogic)
- const id = logicProps.id
-
- if (!id) {
- return null
- }
-
- return (
- <BindLogic logic={hogFunctionTestingLogic} props={{ id }}>
- <div className="deprecated-space-y-3">
- <InvocationsLegacyTabBanner legacyTab="Testing" />
- <LemonBanner type="info">
- <span>
- This is a list of all events matching your filters. You can run the function using these
- historical events.
- </span>
- </LemonBanner>
- <div className="flex items-center gap-2 justify-bewtween">
- <div className="flex items-center gap-2 flex-1">
- <RunsFilters />
- </div>
-
- <div className="flex items-center gap-2">
- <TestRunnerOptions />
- </div>
- </div>
-
- <TestingEventsList />
- </div>
- </BindLogic>
- )
-}
-
-function EmptyColumn(): JSX.Element {
- return (
- <Tooltip title="NULL" placement="right" delayMs={0}>
- <span className="cursor-default" aria-hidden>
- —
- </span>
- </Tooltip>
- )
-}
-
-function TestRunnerOptions(): JSX.Element {
- const { selectingMany, eventsWithRetries, loadingRetries, selectedForRetry } = useValues(hogFunctionTestingLogic)
- const { setSelectingMany, retryInvocation, selectForRetry, deselectForRetry, resetSelectedForRetry } =
- useActions(hogFunctionTestingLogic)
- const { groupTypes, configuration } = useValues(hogFunctionConfigurationLogic)
-
- return (
- <>
- {!selectingMany ? (
- <LemonButton size="small" type="secondary" onClick={() => setSelectingMany(true)}>
- Select invocations
- </LemonButton>
- ) : (
- <>
- <LemonButton
- size="small"
- type="secondary"
- onClick={() => {
- setSelectingMany(false)
- resetSelectedForRetry()
- }}
- >
- Cancel
- </LemonButton>
- <LemonButton
- size="small"
- type="secondary"
- onClick={() =>
- selectedForRetry.length === eventsWithRetries.length
- ? deselectForRetry(eventsWithRetries.map((row) => row[0].uuid))
- : selectForRetry(eventsWithRetries.map((row) => row[0].uuid))
- }
- >
- <span>
- {selectedForRetry.length === eventsWithRetries.length ? 'Deselect all' : 'Select all'}
- </span>
- </LemonButton>
- <LemonButton
- size="small"
- type="primary"
- onClick={() => {
- LemonDialog.open({
- title: 'Test selected events',
- content: `Are you sure you want to test the selected events? Please don't close the window until the invocations have completed.`,
- secondaryButton: {
- children: 'Cancel',
- },
- primaryButton: {
- children: 'Test selected events',
- onClick: () => {
- eventsWithRetries
- .filter((row) => selectedForRetry.includes(row[0].uuid))
- .forEach((row) =>
- retryInvocation({
- eventId: row[0].uuid,
- globals: buildGlobals(
- row,
- groupTypes,
- configuration?.name ?? 'Unnamed'
- ),
- })
- )
- },
- },
- })
- }}
- loading={loadingRetries.length > 0}
- disabledReason={
- loadingRetries.length > 0
- ? 'Please wait for the current tests to complete.'
- : selectedForRetry.length === 0
- ? 'No invocations selected'
- : undefined
- }
- >
- Test selected
- </LemonButton>
- </>
- )}
- </>
- )
-}
-
-function RunsFilters(): JSX.Element {
- const { eventsLoading, baseEventsQuery } = useValues(hogFunctionTestingLogic)
- const { loadEvents, changeDateRange, loadTotalEvents } = useActions(hogFunctionTestingLogic)
- const { logicProps } = useValues(hogFunctionConfigurationLogic)
- const [dropdownOpen, setDropdownOpen] = useState(false)
-
- const handleRefresh = (): void => {
- loadEvents()
- loadTotalEvents()
- }
-
- return (
- <>
- <LemonButton
- onClick={handleRefresh}
- loading={eventsLoading}
- type="secondary"
- icon={<IconRefresh />}
- size="small"
- >
- Refresh
- </LemonButton>
- <DateFilter
- dateFrom={baseEventsQuery?.after ?? undefined}
- dateTo={baseEventsQuery?.before ?? undefined}
- onChange={changeDateRange}
- />
- <LemonDropdown
- visible={dropdownOpen}
- closeOnClickInside={false}
- matchWidth={false}
- placement="right-end"
- overlay={
- <Form
- logic={hogFunctionConfigurationLogic}
- props={logicProps}
- formKey="configuration"
- className="deprecated-space-y-3"
- >
- <HogFunctionFilters embedded={true} showTriggerOptions={false} />
- <div className="flex justify-end mt-2">
- <LemonButton size="small" type="primary" onClick={() => setDropdownOpen(false)}>
- Done
- </LemonButton>
- </div>
- </Form>
- }
- >
- <LemonButton size="small" type="secondary" onClick={() => setDropdownOpen((v) => !v)}>
- Filters
- </LemonButton>
- </LemonDropdown>
- </>
- )
-}
-
-function TestingEventsList(): JSX.Element | null {
- const {
- eventsLoading,
- eventsWithRetries,
- totalEvents,
- pageTimestamps,
- expandedRows,
- loadingRetries,
- selectingMany,
- selectedForRetry,
- } = useValues(hogFunctionTestingLogic)
- const {
- retryInvocation,
- loadNextEventsPage,
- loadPreviousEventsPage,
- expandRow,
- collapseRow,
- selectForRetry,
- deselectForRetry,
- } = useActions(hogFunctionTestingLogic)
- const { groupTypes, configuration, logicProps } = useValues(hogFunctionConfigurationLogic)
- const id = logicProps.id ?? 'new'
- const { setSampleGlobals, toggleExpanded } = useActions(hogFunctionTestLogic(logicProps))
-
- return (
- <LemonTable
- dataSource={eventsWithRetries}
- loading={eventsLoading}
- loadingSkeletonRows={5}
- pagination={{
- controlled: true,
- currentPage: pageTimestamps.length + 1,
- onForward: loadNextEventsPage,
- onBackward: loadPreviousEventsPage,
- pageSize: eventsWithRetries.length,
- hideOnSinglePage: false,
- entryCount: totalEvents,
- }}
- expandable={{
- isRowExpanded: ([event]) => expandedRows.includes(event.uuid),
- onRowExpand: ([event]) => expandRow(event.uuid),
- onRowCollapse: ([event]) => collapseRow(event.uuid),
- noIndent: true,
- expandedRowRender: ([, , , retries]) => {
- return (
- <LemonTable
- dataSource={retries.reduce(
- (acc: LogEntry[], group: CyclotronJobTestInvocationResultWithEventId) =>
- acc.concat(group.logs),
- []
- )}
- embedded={true}
- columns={[
- {
- key: 'spacer',
- width: 0,
- render: () => <div className="w-6" />,
- },
- {
- title: 'Timestamp',
- key: 'timestamp',
- dataIndex: 'timestamp',
- render: (_, { timestamp }) => <TZLabel time={timestamp} />,
- },
- {
- title: 'Level',
- key: 'level',
- dataIndex: 'level',
- render: (_, { level }) => (
- <LemonTag type={tagTypeForLevel(level)}>{level.toUpperCase()}</LemonTag>
- ),
- },
- {
- title: 'Message',
- key: 'message',
- dataIndex: 'message',
- render: (_, { message }) => <code className="whitespace-pre-wrap">{message}</code>,
- },
- ]}
- />
- )
- },
- }}
- columns={[
- {
- title: 'Status',
- key: 'status',
- width: 0,
- render: (_, row) => {
- const eventId = row[0].uuid
-
- const getStatus = (): { text: string; type: LemonTagType } => {
- if (loadingRetries.includes(eventId)) {
- return {
- text: 'Running',
- type: 'warning',
- }
- } else if (row[3].length === 0) {
- return {
- text: 'Not tested',
- type: 'muted',
- }
- } else if (row[3][row[3].length - 1].status === 'error') {
- return {
- text: 'Failure',
- type: 'danger',
- }
- } else if (row[3][row[3].length - 1].status === 'success') {
- return {
- text: 'Success',
- type: 'success',
- }
- }
- return {
- text: 'Unknown',
- type: 'muted',
- }
- }
-
- return (
- <div className="flex gap-2 items-center">
- {selectingMany ? (
- <LemonCheckbox
- checked={selectedForRetry.includes(eventId)}
- onChange={(checked) => {
- if (checked) {
- selectForRetry([eventId])
- } else {
- deselectForRetry([eventId])
- }
- }}
- />
- ) : null}
-
- <LemonTag type={getStatus().type}>{capitalizeFirstLetter(getStatus().text)}</LemonTag>
-
- <LemonMenu
- items={[
- eventId
- ? {
- label: 'View event',
- to: urls.event(eventId, row[0].timestamp),
- }
- : null,
- {
- label: 'Test event',
- onClick: () => {
- retryInvocation({
- eventId,
- globals: buildGlobals(
- row,
- groupTypes,
- configuration?.name ?? 'Unnamed'
- ),
- })
- expandRow(eventId)
- },
- },
- {
- label: 'Test with this event in configuration',
- onClick: () => {
- const globals = buildGlobals(
- row,
- groupTypes,
- configuration?.name ?? 'Unnamed'
- )
- setSampleGlobals(globals)
- toggleExpanded(true)
- router.actions.push(urls.hogFunction(id) + '?tab=configuration')
- },
- },
- ]}
- >
- <LemonButton
- size="xsmall"
- icon={<IconEllipsis className="rotate-90" />}
- loading={loadingRetries.includes(eventId) ? true : undefined}
- />
- </LemonMenu>
- </div>
- )
- },
- },
- {
- title: 'Event',
- key: 'event',
- className: 'max-w-80',
- render: (_, [event]) => {
- return event.event ? (
- <PropertyKeyInfo value={event.event} type={TaxonomicFilterGroupType.Events} />
- ) : (
- <EmptyColumn />
- )
- },
- },
- {
- title: 'Person',
- key: 'person',
- render: (_, [, person]) => {
- return person ? <PersonDisplay person={person} withIcon /> : <EmptyColumn />
- },
- },
- {
- title: 'URL / Screen',
- key: 'url',
- className: 'max-w-80',
- render: (_, [event]) =>
- event.properties['$current_url'] || event.properties['$screen_name'] ? (
- <span>{event.properties['$current_url'] || event.properties['$screen_name']}</span>
- ) : (
- <EmptyColumn />
- ),
- },
- {
- title: 'Library',
- key: 'library',
- className: 'max-w-80',
- render: (_, [event]) => {
- return event.properties['$lib'] ? <span>{event.properties['$lib']}</span> : <EmptyColumn />
- },
- },
- {
- title: 'Time',
- key: 'time',
- className: 'max-w-80',
- render: (_, [event]) => {
- return event.timestamp ? <TZLabel time={event.timestamp} /> : <EmptyColumn />
- },
- },
- ]}
- emptyState={<InsightEmptyState sampleDataVariant="table" />}
- />
- )
-}
diff --git a/frontend/src/scenes/hog-functions/testing/hogFunctionTestingLogic.tsx b/frontend/src/scenes/hog-functions/testing/hogFunctionTestingLogic.tsx
deleted file mode 100644
index 4f6c3c1ac30c..000000000000
--- a/frontend/src/scenes/hog-functions/testing/hogFunctionTestingLogic.tsx
+++ /dev/null
@@ -1,694 +0,0 @@
-import { deepEqual as equal } from 'fast-equals'
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import { beforeUnload } from 'kea-router'
-import { subscriptions } from 'kea-subscriptions'
-
-import { lemonToast } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-
-import { groupsModel } from '~/models/groupsModel'
-import { removeExpressionComment } from '~/queries/nodes/DataTable/utils'
-import { EventsNode, EventsQuery, EventsQueryResponse, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
-import { escapePropertyAsHogQLIdentifier, setLatestVersionsOnQuery } from '~/queries/utils'
-import {
- BaseMathType,
- ChartDisplayType,
- CyclotronJobInvocationGlobals,
- CyclotronJobTestInvocationResult,
-} from '~/types'
-
-import type {
- AccessControlFilterWarning,
- DataWarehouseSyncWarning,
- HogQLQueryModifiers,
- QueryStatus,
- QueryTiming,
- ResolvedDateRangeResponse,
-} from '../../../queries/schema/schema-general'
-import type { GroupType, GroupTypeIndex, HogFunctionConfigurationType, PropertyGroupFilter } from '../../../types'
-import { hogFunctionConfigurationLogic, sanitizeConfiguration } from '../configuration/hogFunctionConfigurationLogic'
-
-export interface HogFunctionTestingLogicProps {
- id: string
-}
-
-export interface EventsResultType {
- before: string | undefined
- results: EventsQueryResponse['results']
-}
-
-export interface CyclotronJobTestInvocationResultWithEventId extends CyclotronJobTestInvocationResult {
- eventId: string
-}
-
-const PAGE_ROWS = 20
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface hogFunctionTestingLogicValues {
- groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
- configuration: HogFunctionConfigurationType // hogFunctionConfigurationLogic
- matchingFilters: PropertyGroupFilter // hogFunctionConfigurationLogic
- templateId: string | undefined // hogFunctionConfigurationLogic
- baseEventsQuery: EventsQuery | null
- dateRange: {
- after: string | null
- before: string | null
- }
- events: EventsResultType
- eventsLoading: boolean
- eventsWithRetries: any[][]
- expandedRows: string[]
- loadingRetries: string[]
- nextQuery: EventsQuery | null
- pageTimestamps: (string | undefined)[]
- previousQuery: EventsQuery | null
- retries: CyclotronJobTestInvocationResultWithEventId[]
- retriesLoading: boolean
- selectedForRetry: string[]
- selectingMany: boolean
- totalEvents: number
- totalEventsLoading: boolean
- totalEventsQuery: TrendsQuery | null
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface hogFunctionTestingLogicActions {
- addLoadingRetry: (eventId: string) => {
- eventId: string
- }
- changeDateRange: (
- after: string | null,
- before: string | null
- ) => {
- after: string | null
- before: string | null
- }
- collapseRow: (eventId: string) => {
- eventId: string
- }
- decreaseCurrentPage: () => {
- value: true
- }
- deselectForRetry: (eventIds: string[]) => {
- eventIds: string[]
- }
- expandRow: (eventId: string) => {
- eventId: string
- }
- increaseCurrentPage: (timestamp: string | undefined) => {
- timestamp: string | undefined
- }
- loadEvents: () => any
- loadEventsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadEventsSuccess: (
- events:
- | {
- before: undefined
- results: never[]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- },
- payload?: any
- ) => {
- events:
- | {
- before: undefined
- results: never[]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- }
- payload?: any
- }
- loadNextEventsPage: () => any
- loadNextEventsPageFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadNextEventsPageSuccess: (
- events:
- | {
- before: undefined
- results: any[][]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- },
- payload?: any
- ) => {
- events:
- | {
- before: undefined
- results: any[][]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- }
- payload?: any
- }
- loadPreviousEventsPage: () => any
- loadPreviousEventsPageFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadPreviousEventsPageSuccess: (
- events:
- | {
- before: undefined
- results: any[][]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- },
- payload?: any
- ) => {
- events:
- | {
- before: undefined
- results: any[][]
- }
- | {
- before: string | undefined
- columns: any[]
- error?: string | undefined
- hasMore?: boolean | undefined
- hogql: string
- limit?: number | undefined
- modifiers?: HogQLQueryModifiers | undefined
- nextCursor?: string | undefined
- offset?: number | undefined
- query_status?: QueryStatus | undefined
- resolved_compare_date_range?: ResolvedDateRangeResponse | undefined
- resolved_date_range?: ResolvedDateRangeResponse | undefined
- results: any[][]
- timings?: QueryTiming[] | undefined
- types: string[]
- warnings?: (AccessControlFilterWarning | DataWarehouseSyncWarning)[] | undefined
- }
- payload?: any
- }
- loadTotalEvents: () => any
- loadTotalEventsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTotalEventsSuccess: (
- totalEvents: number,
- payload?: any
- ) => {
- totalEvents: number
- payload?: any
- }
- removeLoadingRetry: (eventId: string) => {
- eventId: string
- }
- resetCollapsedRows: () => {
- value: true
- }
- resetCurrentPage: () => {
- value: true
- }
- resetSelectedForRetry: () => {
- value: true
- }
- retryInvocation: ({ eventId, globals }: { eventId: string; globals: CyclotronJobInvocationGlobals }) => {
- eventId: string
- globals: CyclotronJobInvocationGlobals
- }
- retryInvocationFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- retryInvocationSuccess: (
- retries: CyclotronJobTestInvocationResultWithEventId[],
- payload?: {
- eventId: string
- globals: CyclotronJobInvocationGlobals
- }
- ) => {
- retries: CyclotronJobTestInvocationResultWithEventId[]
- payload?: {
- eventId: string
- globals: CyclotronJobInvocationGlobals
- }
- }
- selectForRetry: (eventIds: string[]) => {
- eventIds: string[]
- }
- setSelectingMany: (selectingMany: boolean) => {
- selectingMany: boolean
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface hogFunctionTestingLogicMeta {
- key: string
- __keaTypeGenInternalSelectorTypes: {
- baseEventsQuery: (
- configuration: HogFunctionConfigurationType,
- matchingFilters: PropertyGroupFilter,
- groupTypes: Map<GroupTypeIndex, GroupType>,
- dateRange: {
- after: string | null
- before: string | null
- }
- ) => EventsQuery | null
- totalEventsQuery: (
- configuration: HogFunctionConfigurationType,
- matchingFilters: PropertyGroupFilter,
- dateRange: {
- after: string | null
- before: string | null
- }
- ) => TrendsQuery | null
- eventsWithRetries: (events: EventsResultType, retries: CyclotronJobTestInvocationResultWithEventId[]) => any[][]
- nextQuery: (baseEventsQuery: EventsQuery | null, events: EventsResultType) => EventsQuery | null
- previousQuery: (baseEventsQuery: EventsQuery | null, events: EventsResultType) => EventsQuery | null
- }
-}
-
-export type hogFunctionTestingLogicType = MakeLogicType<
- hogFunctionTestingLogicValues,
- hogFunctionTestingLogicActions,
- HogFunctionTestingLogicProps,
- hogFunctionTestingLogicMeta
->
-
-export const hogFunctionTestingLogic = kea<hogFunctionTestingLogicType>([
- path((key) => ['scenes', 'pipeline', 'hogFunctionTestingLogic', key]),
- props({} as HogFunctionTestingLogicProps),
- key(({ id }: HogFunctionTestingLogicProps) => id),
- connect(() => ({
- values: [
- hogFunctionConfigurationLogic,
- ['configuration', 'matchingFilters', 'templateId'],
- groupsModel,
- ['groupTypes'],
- ],
- })),
- actions({
- changeDateRange: (after: string | null, before: string | null) => ({ after, before }),
- addLoadingRetry: (eventId: string) => ({ eventId }),
- removeLoadingRetry: (eventId: string) => ({ eventId }),
- increaseCurrentPage: (timestamp: string | undefined) => ({ timestamp }),
- decreaseCurrentPage: true,
- resetCurrentPage: true,
- expandRow: (eventId: string) => ({ eventId }),
- collapseRow: (eventId: string) => ({ eventId }),
- resetCollapsedRows: true,
- selectForRetry: (eventIds: string[]) => ({ eventIds }),
- deselectForRetry: (eventIds: string[]) => ({ eventIds }),
- resetSelectedForRetry: true,
- setSelectingMany: (selectingMany: boolean) => ({ selectingMany }),
- }),
- reducers({
- dateRange: [
- { after: '-7d', before: null } as { after: string | null; before: string | null },
- {
- changeDateRange: (_, { after, before }: { after: string | null; before: string | null }) => ({
- after,
- before,
- }),
- },
- ],
- loadingRetries: [
- [] as string[],
- {
- addLoadingRetry: (state, { eventId }: { eventId: string }) => [...state, eventId],
- removeLoadingRetry: (state, { eventId }: { eventId: string }) =>
- state.filter((id: string) => id !== eventId),
- },
- ],
- pageTimestamps: [
- [] as (string | undefined)[],
- {
- increaseCurrentPage: (state, { timestamp }: { timestamp: string | undefined }) => [...state, timestamp],
- decreaseCurrentPage: (state) => state.filter((_, i) => i !== state.length - 1),
- resetCurrentPage: () => [],
- },
- ],
- expandedRows: [
- [] as string[],
- {
- expandRow: (state, { eventId }: { eventId: string }) => [...state, eventId],
- collapseRow: (state, { eventId }: { eventId: string }) => state.filter((id: string) => id !== eventId),
- resetCollapsedRows: () => [],
- },
- ],
- selectingMany: [
- false as boolean,
- {
- setSelectingMany: (_, { selectingMany }: { selectingMany: boolean }) => selectingMany,
- },
- ],
- selectedForRetry: [
- [] as string[],
- {
- selectForRetry: (state, { eventIds }: { eventIds: string[] }) => [...new Set([...state, ...eventIds])],
- deselectForRetry: (state, { eventIds }: { eventIds: string[] }) =>
- state.filter((id: string) => !eventIds.includes(id)),
- resetSelectedForRetry: () => [],
- },
- ],
- }),
- loaders(({ values, props, actions }) => ({
- events: [
- { results: [], before: undefined } as EventsResultType,
- {
- loadEvents: async () => {
- if (!values.baseEventsQuery) {
- return { results: [], before: undefined }
- }
- const response = await api.query(values.baseEventsQuery)
- return {
- ...response,
- before: values.dateRange.before ?? undefined,
- }
- },
- loadNextEventsPage: async () => {
- if (!values.nextQuery) {
- return { ...values.events, before: undefined }
- }
- actions.increaseCurrentPage(values.events.before)
- const response = await api.query(values.nextQuery)
- return {
- ...response,
- before: values.nextQuery.before,
- }
- },
- loadPreviousEventsPage: async () => {
- if (!values.previousQuery) {
- return { ...values.events, before: undefined }
- }
- const response = await api.query(values.previousQuery)
- actions.decreaseCurrentPage()
- return {
- ...response,
- before: values.previousQuery.before,
- }
- },
- },
- ],
- totalEvents: [
- 0 as number,
- {
- loadTotalEvents: async () => {
- if (!values.totalEventsQuery) {
- return 0
- }
- const response = await api.query(values.totalEventsQuery)
- return response.results[0]?.aggregated_value ?? 0
- },
- },
- ],
- retries: [
- [] as CyclotronJobTestInvocationResultWithEventId[],
- {
- retryInvocation: async ({
- eventId,
- globals,
- }: {
- eventId: string
- globals: CyclotronJobInvocationGlobals
- }) => {
- actions.addLoadingRetry(eventId)
- const configuration = sanitizeConfiguration(values.configuration) as Record<string, any>
- configuration.template_id = values.templateId
-
- let res: CyclotronJobTestInvocationResult
- try {
- res = await api.hogFunctions.createTestInvocation(props.id ?? 'new', {
- globals,
- mock_async_functions: false,
- configuration,
- })
-
- actions.removeLoadingRetry(eventId)
- const retry: CyclotronJobTestInvocationResultWithEventId = {
- eventId: eventId,
- ...res,
- }
-
- return [...values.retries, retry]
- } catch (e: any) {
- if (e?.data?.configuration?.filters?.non_field_errors) {
- lemonToast.error(`Testing failed: ${e.data.configuration.filters.non_field_errors}`)
- } else {
- lemonToast.error(`An unexpected server error occurred while testing the function: ${e}`)
- }
- }
- actions.removeLoadingRetry(eventId)
- return [...values.retries]
- },
- },
- ],
- })),
- selectors(({ values }) => ({
- baseEventsQuery: [
- (s) => [s.configuration, s.matchingFilters, s.groupTypes, s.dateRange],
- (
- configuration: import('~/types').HogFunctionConfigurationType,
- matchingFilters: import('~/types').PropertyGroupFilter,
- groupTypes: Map<import('~/types').GroupTypeIndex, import('~/types').GroupType>,
- dateRange: {
- after: string | null
- before: string | null
- }
- ): EventsQuery | null => {
- const query: EventsQuery = {
- kind: NodeKind.EventsQuery,
- filterTestAccounts: configuration.filters?.filter_test_accounts,
- fixedProperties: [matchingFilters],
- limit: PAGE_ROWS,
- select: ['*', 'person', 'timestamp'],
- after: dateRange?.after ?? undefined,
- before: dateRange?.before ?? undefined,
- orderBy: ['timestamp DESC'],
- modifiers: {
- personsOnEventsMode: 'person_id_no_override_properties_on_events',
- },
- }
- groupTypes.forEach((groupType) => {
- const name = escapePropertyAsHogQLIdentifier(groupType.group_type)
- query.select.push(
- `tuple(${name}.created_at, ${name}.index, ${name}.key, ${name}.properties, ${name}.updated_at)`
- )
- })
- return setLatestVersionsOnQuery(query)
- },
- { resultEqualityCheck: equal },
- ],
- totalEventsQuery: [
- (s) => [s.configuration, s.matchingFilters, s.dateRange],
- (
- configuration: import('~/types').HogFunctionConfigurationType,
- matchingFilters: import('~/types').PropertyGroupFilter,
- dateRange: {
- after: string | null
- before: string | null
- }
- ): TrendsQuery | null => {
- return setLatestVersionsOnQuery({
- kind: NodeKind.TrendsQuery,
- filterTestAccounts: configuration.filters?.filter_test_accounts,
- series: [
- {
- kind: NodeKind.EventsNode,
- event: null,
- name: 'All Events',
- math: BaseMathType.TotalCount,
- } satisfies EventsNode,
- ],
- properties: matchingFilters,
- dateRange: {
- date_from: dateRange.after,
- date_to: dateRange.before,
- },
- trendsFilter: {
- display: ChartDisplayType.BoldNumber,
- },
- modifiers: {
- personsOnEventsMode: 'person_id_no_override_properties_on_events',
- },
- })
- },
- { resultEqualityCheck: equal },
- ],
- eventsWithRetries: [
- (s) => [s.events, s.retries],
- (events: { results: any[] }, retries: CyclotronJobTestInvocationResultWithEventId[]) =>
- events.results.map((row) => [
- ...row.slice(0, 3),
- retries.filter((r) => r.eventId === row[0].uuid),
- ...row.slice(3),
- ]),
- ],
- nextQuery: [
- (s) => [s.baseEventsQuery, s.events],
- (baseEventsQuery: EventsQuery | null, events: EventsResultType): EventsQuery | null => {
- if (!baseEventsQuery || !events) {
- return null
- }
- const typedResults = events?.results
- const sortColumnIndex = baseEventsQuery?.select
- .map((hql: any) => removeExpressionComment(hql))
- .indexOf('timestamp')
- if (sortColumnIndex !== -1) {
- const lastTimestamp = typedResults?.[typedResults.length - 1]?.[sortColumnIndex]
- if (lastTimestamp) {
- const newQuery: EventsQuery = {
- ...baseEventsQuery,
- before: lastTimestamp,
- limit: PAGE_ROWS,
- }
- return newQuery
- }
- }
- return null
- },
- ],
- previousQuery: [
- (s) => [s.baseEventsQuery, s.events],
- (baseEventsQuery: EventsQuery | null, events: EventsResultType): EventsQuery | null => {
- if (!baseEventsQuery || !events) {
- return null
- }
- const lastTimestamp = values.pageTimestamps[values.pageTimestamps.length - 1]
- const newQuery: EventsQuery = {
- ...baseEventsQuery,
- before: lastTimestamp,
- limit: PAGE_ROWS,
- }
- return newQuery
- },
- ],
- })),
- listeners(({ actions }) => ({
- changeDateRange: () => {
- actions.loadEvents()
- },
- loadEvents: () => {
- actions.loadTotalEvents()
- actions.resetCurrentPage()
- actions.resetCollapsedRows()
- actions.resetSelectedForRetry()
- },
- increaseCurrentPage: () => {
- actions.resetSelectedForRetry()
- },
- decreaseCurrentPage: () => {
- actions.resetSelectedForRetry()
- },
- })),
- subscriptions(({ actions, values }) => ({
- configuration: () => {
- if (values.configuration?.name) {
- actions.loadEvents()
- actions.loadTotalEvents()
- }
- },
- })),
- beforeUnload(({ values, cache }) => ({
- enabled: () => !cache.disabledBeforeUnload && values.loadingRetries.length > 0,
- message: 'You have running tests that will be discarded if you leave. Are you sure?',
- onConfirm: () => {
- cache.disabledBeforeUnload = true
- },
- })),
-])
diff --git a/products/workflows/frontend/Workflows/WorkflowLogs.tsx b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
similarity index 71%
rename from products/workflows/frontend/Workflows/WorkflowLogs.tsx
rename to products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
index c05b262f6597..81236d1457f9 100644
--- a/products/workflows/frontend/Workflows/WorkflowLogs.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
@@ -3,13 +3,13 @@ import { type ReactNode, useMemo } from 'react'
import * as greekPng from '@posthog/brand/hoggies/png/greek'
import { IconClock } from '@posthog/icons'
-import { LemonCollapse, LemonDivider, ProfilePicture, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { LemonCollapse, LemonDivider, LemonTag, ProfilePicture, Spinner, Tooltip } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
-import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
+import { HogInvocations } from 'scenes/hog-functions/invocations/HogInvocations'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { OccurrencesList } from './hogflows/steps/components/OccurrencesList'
@@ -22,35 +22,33 @@ import {
} from './hogflows/steps/components/rrule-helpers'
import { HogFlowBatchJob } from './hogflows/types'
import { renderWorkflowLogMessage } from './logs/log-utils'
-import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
+import { workflowLogic } from './workflowLogic'
const HedgehogGreek = pngHoggie(greekPng)
-export type WorkflowLogsProps = {
- id: string
+const STATUS_TAG_TYPE: Record<HogFlowBatchJob['status'], 'success' | 'danger' | 'warning' | 'default'> = {
+ completed: 'success',
+ failed: 'danger',
+ cancelled: 'default',
+ waiting: 'warning',
+ queued: 'warning',
+ active: 'warning',
}
-function WorkflowRunLogs(props: WorkflowLogsProps): JSX.Element {
- const { workflow } = useValues(workflowLogic)
-
- return (
- <LogsViewer
- sourceType="hog_flow"
- sourceId={props.id!}
- instanceLabel="workflow run"
- renderMessage={(m) => renderWorkflowLogMessage(workflow, m)}
- />
- )
+function SectionHeading({ children }: { children: ReactNode }): JSX.Element {
+ return <h3 className="text-xs font-semibold uppercase tracking-wide text-muted mb-1">{children}</h3>
}
function BatchRunHeader({ job }: { job: HogFlowBatchJob }): JSX.Element {
return (
<div className="flex gap-2 w-full justify-between">
- <strong>{job.id}</strong>
+ <div className="flex items-center gap-2 min-w-0">
+ <strong className="truncate">{job.id}</strong>
+ <LemonTag type={STATUS_TAG_TYPE[job.status] ?? 'default'}>{job.status}</LemonTag>
+ </div>
<div className="flex items-center gap-2">
<TZLabel title="Created at" time={job.created_at} />
<LemonDivider vertical className="h-full" />
-
{job.created_by ? (
<Tooltip title={`Triggered by ${job.created_by.email}`}>
<div>
@@ -65,25 +63,31 @@ function BatchRunHeader({ job }: { job: HogFlowBatchJob }): JSX.Element {
)
}
-function BatchRunInfo({ job }: { job: HogFlowBatchJob }): JSX.Element {
+function BatchRunInvocations({ job, hogFlowId }: { job: HogFlowBatchJob; hogFlowId: string }): JSX.Element {
const { workflow } = useValues(workflowLogic)
+ // Broadcasts can be older than the flat list's 24h default, so anchor the window
+ // just before the job was created to keep this run's invocations in range.
+ const defaultDateFrom = dayjs(job.created_at).subtract(1, 'day').format('YYYY-MM-DD')
+
return (
- <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-3">
<div className="flex flex-col gap-2 items-start w-full">
<span className="text-muted">Job filters</span>
<PropertyFiltersDisplay
filters={Array.isArray(job.filters?.properties) ? job.filters.properties : []}
/>
</div>
- <span className="text-muted">Logs</span>
- <LogsViewer
- sourceType="hog_flow"
- sourceId={job.id}
- groupByInstanceId
- instanceLabel="workflow job"
- renderMessage={(m) => renderWorkflowLogMessage(workflow, m)}
- />
+ <div className="flex flex-col gap-2">
+ <HogInvocations
+ id={hogFlowId}
+ functionKind="hog_flow"
+ parentRunId={job.id}
+ defaultDateFrom={defaultDateFrom}
+ compact
+ renderLogMessage={workflow ? (m) => renderWorkflowLogMessage(workflow, m) : undefined}
+ />
+ </div>
</div>
)
}
@@ -140,12 +144,14 @@ function UpcomingOccurrences(): JSX.Element | null {
)
}
-function SectionHeading({ children }: { children: ReactNode }): JSX.Element {
- return <h3 className="text-xs font-semibold uppercase tracking-wide text-muted mb-1">{children}</h3>
-}
-
-function WorkflowBatchRunLogs(props: WorkflowLogicProps): JSX.Element {
- const { jobs, batchWorkflowJobsLoading } = useValues(batchWorkflowJobsLogic(props))
+/**
+ * Batch-triggered workflows fan out one child invocation per person. The flat invocations
+ * table can't tell which broadcast a run belongs to, so here we group runs by batch job —
+ * each job expands to its own scoped invocations table — and preview the schedule's upcoming
+ * occurrences. Mirrors the batch grouping the standalone Logs tab used to show.
+ */
+export function WorkflowBatchInvocations({ id }: { id: string }): JSX.Element {
+ const { jobs, batchWorkflowJobsLoading } = useValues(batchWorkflowJobsLogic({ id }))
const { currentSchedule } = useValues(workflowLogic)
const hasSchedule = !!currentSchedule?.rrule && !isOneTimeSchedule(currentSchedule.rrule)
@@ -165,7 +171,7 @@ function WorkflowBatchRunLogs(props: WorkflowLogicProps): JSX.Element {
<HedgehogGreek width="100" height="100" className="mb-4" />
<h2 className="text-xl leading-tight">No batch workflow jobs have been run yet</h2>
<p className="text-sm text-balance text-tertiary">
- Once a batch workflow job is triggered, execution logs will appear here.
+ Once a batch workflow job is triggered, its invocations will appear here.
</p>
</div>
</div>
@@ -173,7 +179,7 @@ function WorkflowBatchRunLogs(props: WorkflowLogicProps): JSX.Element {
}
return (
- <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-4" data-attr="workflow-batch-invocations">
<UpcomingOccurrences />
<div>
{hasSchedule && <SectionHeading>Past invocations</SectionHeading>}
@@ -181,20 +187,10 @@ function WorkflowBatchRunLogs(props: WorkflowLogicProps): JSX.Element {
panels={jobs.map((job) => ({
key: job.id,
header: <BatchRunHeader job={job} />,
- content: <BatchRunInfo job={job} />,
+ content: <BatchRunInvocations job={job} hogFlowId={id} />,
}))}
/>
</div>
</div>
)
}
-
-export function WorkflowLogs({ id }: WorkflowLogsProps): JSX.Element {
- const { workflow } = useValues(workflowLogic)
-
- return (
- <div data-attr="workflow-logs">
- {workflow?.trigger?.type === 'batch' ? <WorkflowBatchRunLogs id={id} /> : <WorkflowRunLogs id={id} />}
- </div>
- )
-}
diff --git a/products/workflows/frontend/Workflows/WorkflowInvocations.tsx b/products/workflows/frontend/Workflows/WorkflowInvocations.tsx
index a26e9db33cd0..579cf25d7334 100644
--- a/products/workflows/frontend/Workflows/WorkflowInvocations.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowInvocations.tsx
@@ -3,6 +3,7 @@ import { useValues } from 'kea'
import { HogInvocations } from 'scenes/hog-functions/invocations/HogInvocations'
import { renderWorkflowLogMessage } from './logs/log-utils'
+import { WorkflowBatchInvocations } from './WorkflowBatchInvocations'
import { workflowLogic } from './workflowLogic'
/**
@@ -11,11 +12,20 @@ import { workflowLogic } from './workflowLogic'
* this file exists so the workflow scene can wire its own tab without
* leaking the cross-product import into every call site.
*
- * Passes the workflow-aware log renderer so event/person/action tokens in the
- * per-run logs become links, matching the standalone Logs tab.
+ * Batch-triggered workflows get the grouped-by-job view instead: their runs fan out
+ * one child invocation per person, so we group them by batch job (and preview the
+ * schedule's upcoming occurrences), matching the batch grouping the old Logs tab had.
+ *
+ * The flat view passes the workflow-aware log renderer so event/person/action tokens in
+ * the per-run logs become links, matching the standalone Logs tab.
*/
export function WorkflowInvocations({ id }: { id: string }): JSX.Element | null {
const { workflow } = useValues(workflowLogic)
+
+ if (workflow?.trigger?.type === 'batch') {
+ return <WorkflowBatchInvocations id={id} />
+ }
+
return (
<HogInvocations
id={id}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index 6d7844b65371..fb7ee3b2e085 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -9,9 +9,7 @@ import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'
import { NotFound } from 'lib/components/NotFound'
import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
-import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { SceneExport } from 'scenes/sceneTypes'
@@ -26,7 +24,6 @@ import { Workflow } from './Workflow'
import { WorkflowAssets } from './WorkflowAssets'
import { WorkflowInvocations } from './WorkflowInvocations'
import { workflowLogic } from './workflowLogic'
-import { WorkflowLogs } from './WorkflowLogs'
import { WorkflowMetrics } from './WorkflowMetrics'
import { WorkflowSceneHeader } from './WorkflowSceneHeader'
import { WorkflowSceneLogicProps, WorkflowTab, workflowSceneLogic } from './workflowSceneLogic'
@@ -60,8 +57,6 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)
const isDraft = originalWorkflow?.status === 'draft'
- const runsV2Enabled = useFeatureFlag('HOG_INVOCATION_RESULTS_RUNS_TAB')
-
// Attach child logics to the scene logic so they persist across tab switches
useAttachedLogic(batchJobsLogic, sceneLogic)
useAttachedLogic(logic, sceneLogic)
@@ -82,26 +77,12 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
},
{
- // Once the new Invocations (beta) tab is on, the old log viewer becomes "Logs"
- // to match the hog function scene and avoid two "Invocations" tabs.
- label: runsV2Enabled ? 'Logs' : 'Invocations',
- key: 'logs',
- content: <WorkflowLogs id={workflowSceneProps.id!} />,
+ // Runtime view backed by hog_invocation_results, matching the hog function scene.
+ // Old /logs deep links (and batchWorkflowJobsLogic) redirect here via workflowSceneLogic.
+ label: 'Invocations',
+ key: 'invocations',
+ content: <WorkflowInvocations id={workflowSceneProps.id!} />,
},
- runsV2Enabled
- ? {
- label: (
- <div className="flex flex-row">
- <div>Invocations</div>
- <LemonTag className="ml-2 uppercase" type="warning">
- Beta
- </LemonTag>
- </div>
- ),
- key: 'invocations',
- content: <WorkflowInvocations id={workflowSceneProps.id!} />,
- }
- : null,
{
label: 'Metrics',
key: 'metrics',
diff --git a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
index b2f5ef46709b..85749d07a5ca 100644
--- a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
+++ b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
@@ -29,17 +29,17 @@ describe('batchWorkflowJobsLogic', () => {
logic.mount()
})
- it('fetches once when entering the logs tab', async () => {
- router.actions.push(urls.workflow(WORKFLOW_ID, 'logs'))
+ it('fetches once when entering the invocations tab', async () => {
+ router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
expect(getCalls).toBe(1)
})
- it('fetches on initial mount when the URL is already on the logs tab (deep link)', async () => {
- // Tear down the logic mounted by the outer beforeEach, then re-mount on the logs URL
+ it('fetches on initial mount when the URL is already on the invocations tab (deep link)', async () => {
+ // Tear down the logic mounted by the outer beforeEach, then re-mount on the invocations URL
// so urlToAction fires its afterMount initial-fire while the path already matches.
logic.unmount()
- router.actions.push(urls.workflow(WORKFLOW_ID, 'logs'))
+ router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
getCalls = 0
logic = batchWorkflowJobsLogic({ id: WORKFLOW_ID })
@@ -48,25 +48,25 @@ describe('batchWorkflowJobsLogic', () => {
expect(getCalls).toBe(1)
})
- // Regression: typing in the LogsViewer search box writes to URL search params on every keystroke.
+ // Regression: typing in the invocations search box writes to URL search params on every keystroke.
// Before the fix, that re-triggered loadBatchWorkflowJobs and unmounted the expanded LemonCollapse.
- it('does not refetch when only the URL search params change on the logs tab', async () => {
- router.actions.push(urls.workflow(WORKFLOW_ID, 'logs'))
+ it('does not refetch when only the URL search params change on the invocations tab', async () => {
+ router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
await expectLogic(logic, () => {
- router.actions.push(`${urls.workflow(WORKFLOW_ID, 'logs')}?search=hi`)
- router.actions.push(`${urls.workflow(WORKFLOW_ID, 'logs')}?search=hi+there`)
+ router.actions.push(`${urls.workflow(WORKFLOW_ID, 'invocations')}?search=hi`)
+ router.actions.push(`${urls.workflow(WORKFLOW_ID, 'invocations')}?search=hi+there`)
}).toNotHaveDispatchedActions(['loadBatchWorkflowJobs'])
})
- it('refetches when navigating away and back to the logs tab', async () => {
- router.actions.push(urls.workflow(WORKFLOW_ID, 'logs'))
+ it('refetches when navigating away and back to the invocations tab', async () => {
+ router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
expect(getCalls).toBe(1)
router.actions.push(urls.workflow(WORKFLOW_ID, 'workflow'))
- router.actions.push(urls.workflow(WORKFLOW_ID, 'logs'))
+ router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
expect(getCalls).toBe(2)
})
diff --git a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
index 6d52f9eac442..3961aff3a2df 100644
--- a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
+++ b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
@@ -74,7 +74,7 @@ export const batchWorkflowJobsLogic = kea<batchWorkflowJobsLogicType>([
jobs: [(s) => [s.batchWorkflowJobs], (batchWorkflowJobs: HogFlowBatchJob[] | null) => batchWorkflowJobs || []],
}),
urlToAction(({ props, actions }) => ({
- [urls.workflow(props.id || 'new', 'logs')]: (_, __, ___, currentLocation, previousLocation) => {
+ [urls.workflow(props.id || 'new', 'invocations')]: (_, __, ___, currentLocation, previousLocation) => {
// Skip refetch on same-path URL changes — LogsViewer writes its search filter to the URL on every keystroke.
if (!currentLocation.initial && currentLocation.pathname === previousLocation?.pathname) {
return
diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.ts
index 2f33502f6f16..49849eb13a98 100644
--- a/products/workflows/frontend/Workflows/workflowSceneLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowSceneLogic.ts
@@ -1,5 +1,5 @@
import { MakeLogicType, actions, kea, key, path, props, reducers, selectors } from 'kea'
-import { urlToAction } from 'kea-router'
+import { router, urlToAction } from 'kea-router'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { ActivityScope, Breadcrumb } from '~/types'
-export const WorkflowTabs = ['workflow', 'logs', 'invocations', 'metrics', 'assets', 'history'] as const
+export const WorkflowTabs = ['workflow', 'invocations', 'metrics', 'assets', 'history'] as const
export type WorkflowTab = (typeof WorkflowTabs)[number]
export interface WorkflowSceneLogicProps {
@@ -25,7 +25,7 @@ export interface workflowSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowSceneLogicActions {
setCurrentTab: (tab: WorkflowTab) => {
- tab: 'assets' | 'history' | 'invocations' | 'logs' | 'metrics' | 'workflow'
+ tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'workflow'
}
}
@@ -96,7 +96,14 @@ export const workflowSceneLogic = kea<workflowSceneLogicType>([
],
}),
urlToAction(({ actions, values }) => ({
- '/workflows/:id/:tab': ({ tab }) => {
+ '/workflows/:id/:tab': ({ id, tab }, searchParams) => {
+ // The invocations view used to live on the 'logs' tab. Redirect old /logs deep links
+ // (and the batch-jobs URL trigger) to /invocations so they keep resolving, preserving
+ // any query params (e.g. the metrics-page drill-down's search/level filters).
+ if (tab === 'logs') {
+ router.actions.replace(urls.workflow(id ?? 'new', 'invocations'), searchParams)
+ return
+ }
if (tab !== values.currentTab) {
actions.setCurrentTab(tab as WorkflowTab)
}