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(engineering_analytics): carry branch scope into workflow detail page (#67292)

Julian Bez1d914e66aae2
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index b69e2b02c75a..e64eb4b30601 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -6,7 +6,8 @@ parameters and return canonical contract types.
``repo`` is an optional ``owner/name`` filter, applied against the curated repo
identity (mapped from ``base.repo.full_name``). ``branch`` is an optional exact
-``head_branch`` filter for workflow health. ``date_from`` / ``date_to`` accept
+``head_branch`` filter for workflow health, a workflow's runs list, and its runner
+costs. ``date_from`` / ``date_to`` accept
relative strings (``-30d``) or ISO8601 and are resolved against the team timezone.
``source_id`` selects a specific connected GitHub source when the team has more than
one; it defaults to the oldest connected source. ``user_access_control`` enforces the
@@ -123,6 +124,7 @@ def list_workflow_runs(
workflow_name: str,
date_from: str | None = None,
date_to: str | None = None,
+ branch: str | None = None,
source_id: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowRunDetail]:
@@ -132,6 +134,7 @@ def list_workflow_runs(
workflow_name=workflow_name,
date_from=date_from,
date_to=date_to,
+ branch=branch,
)
@@ -142,6 +145,7 @@ def get_workflow_runner_costs(
workflow_name: str,
date_from: str | None = None,
date_to: str | None = None,
+ branch: str | None = None,
source_id: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowRunnerCost]:
@@ -151,6 +155,7 @@ def get_workflow_runner_costs(
workflow_name=workflow_name,
date_from=date_from,
date_to=date_to,
+ branch=branch,
)
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index ed0f2b0c4b77..352721ba969f 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -106,6 +106,7 @@ def build_workflow_run_list(
workflow_name: str,
date_from: str | None = None,
date_to: str | None = None,
+ branch: str | None = None,
) -> list[WorkflowRunDetail]:
owner, name = _split_repo(repo)
if not (owner and name):
@@ -119,6 +120,7 @@ def build_workflow_run_list(
workflow_name=workflow_name,
date_from=parsed_from,
date_to=parsed_to,
+ branch=branch,
)
@@ -129,6 +131,7 @@ def build_workflow_runner_costs(
workflow_name: str,
date_from: str | None = None,
date_to: str | None = None,
+ branch: str | None = None,
) -> list[WorkflowRunnerCost]:
owner, name = _split_repo(repo)
if not (owner and name):
@@ -142,6 +145,7 @@ def build_workflow_runner_costs(
workflow_name=workflow_name,
date_from=parsed_from,
date_to=parsed_to,
+ branch=branch,
)
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index 2e773a9f08a3..10648ea1bab8 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -206,7 +206,8 @@ def query_workflow_window_costs(
# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scoped
-# to the page's run window so the figure always answers "spend over [window]", never an unbounded all-time.
+# to the page's run window (and optional branch) so the figure always answers "spend over [window]",
+# never an unbounded all-time.
_RUNNER_COST_SELECT = """
SELECT
j.labels,
@@ -216,7 +217,7 @@ _RUNNER_COST_SELECT = """
FROM __JOBS_SOURCE__ AS j
INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt
WHERE r.repo_owner = {repo_owner} AND r.repo_name = {repo_name} AND r.workflow_name = {workflow_name}
- AND r.run_started_at >= {date_from} __DATE_TO__
+ AND r.run_started_at >= {date_from} __DATE_TO__ __BRANCH__
GROUP BY j.labels
LIMIT 1000000
"""
@@ -230,10 +231,11 @@ def query_workflow_runner_costs(
workflow_name: str,
date_from: datetime,
date_to: datetime | None,
+ branch: str | None = None,
) -> list[WorkflowRunnerCost]:
- """A workflow's CI cost broken down by runner tier over [date_from, date_to], highest spend first.
- Empty when the jobs source isn't synced. Raw runner-label combos are folded into their display tier
- (via runner_descriptor)."""
+ """A workflow's CI cost broken down by runner tier over [date_from, date_to] (optional branch),
+ highest spend first. Empty when the jobs source isn't synced. Raw runner-label combos are folded
+ into their display tier (via runner_descriptor)."""
jobs_source = curated.jobs_source()
if jobs_source is None:
return []
@@ -247,10 +249,17 @@ def query_workflow_runner_costs(
if date_to is not None:
date_to_clause = "AND r.run_started_at <= {date_to}"
placeholders["date_to"] = ast.Constant(value=date_to)
+ # An empty/whitespace branch is "no filter", not a literal match on '' — mirrors workflow_health.
+ branch = branch.strip() if branch else None
+ branch_clause = ""
+ if branch:
+ branch_clause = "AND r.head_branch = {branch}"
+ placeholders["branch"] = ast.Constant(value=branch)
sql = (
_RUNNER_COST_SELECT.replace("__JOBS_SOURCE__", jobs_source)
.replace("__RUNS_SOURCE__", curated.run_source())
.replace("__DATE_TO__", date_to_clause)
+ .replace("__BRANCH__", branch_clause)
)
response = curated.run(
sql,
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py b/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
index 66278310ec13..d803c6055af6 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_list.py
@@ -22,7 +22,7 @@ _SELECT = f"""
{RUN_DETAIL_COLUMNS}
FROM __RUNS_SOURCE__ AS r
WHERE repo_owner = {{repo_owner}} AND repo_name = {{repo_name}} AND workflow_name = {{workflow_name}}
- AND run_started_at >= {{date_from}} __DATE_TO__
+ AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__
ORDER BY run_started_at DESC, run_attempt DESC
LIMIT {_LIMIT}
"""
@@ -36,6 +36,7 @@ def query_workflow_run_list(
workflow_name: str,
date_from: datetime,
date_to: datetime | None,
+ branch: str | None = None,
) -> list[WorkflowRunDetail]:
placeholders: dict[str, ast.Expr] = {
"repo_owner": ast.Constant(value=repo_owner),
@@ -47,8 +48,16 @@ def query_workflow_run_list(
if date_to is not None:
date_to_clause = "AND run_started_at <= {date_to}"
placeholders["date_to"] = ast.Constant(value=date_to)
+ # An empty/whitespace branch is "no filter", not a literal match on '' — mirrors workflow_health.
+ branch = branch.strip() if branch else None
+ branch_clause = ""
+ if branch:
+ branch_clause = "AND head_branch = {branch}"
+ placeholders["branch"] = ast.Constant(value=branch)
response = curated.run(
- _SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace("__DATE_TO__", date_to_clause),
+ _SELECT.replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__DATE_TO__", date_to_clause)
+ .replace("__BRANCH__", branch_clause),
query_type="engineering_analytics.workflow_run_list",
placeholders=placeholders,
)
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index ef5029c8081b..be62b7f5723d 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -76,7 +76,7 @@ _BRANCH = OpenApiParameter(
type=OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
required=False,
- description="Optional exact git branch (head_branch) to scope workflow health to, e.g. 'main'. "
+ description="Optional exact git branch (head_branch) to scope results to, e.g. 'main'. "
"Omit or leave blank to aggregate across all branches.",
)
@@ -509,6 +509,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
),
_DATE_FROM,
_DATE_TO,
+ _BRANCH,
_SOURCE_ID,
],
responses={
@@ -517,8 +518,9 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
},
description=(
"Runs of a single workflow within a repo over a window (date_from default -30d), newest first. "
- "Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the GitHub "
- "'workflow' page between the workflow list and a single run."
+ "Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and "
+ "per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the "
+ "workflow list and a single run."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -535,6 +537,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
workflow_name=workflow_name,
date_from=request.query_params.get("date_from") or None,
date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
source_id=request.query_params.get("source_id") or None,
user_access_control=self.user_access_control,
)
@@ -561,6 +564,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
),
_DATE_FROM,
_DATE_TO,
+ _BRANCH,
_SOURCE_ID,
],
responses={
@@ -569,7 +573,8 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
},
description=(
"A workflow's estimated CI cost broken down by runner tier over a window (date_from default "
- "-30d), highest spend first. Returns an empty list when the job-level source isn't synced."
+ "-30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an "
+ "empty list when the job-level source isn't synced."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -585,6 +590,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
workflow_name=workflow_name,
date_from=request.query_params.get("date_from") or None,
date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
source_id=request.query_params.get("source_id") or None,
user_access_control=self.user_access_control,
)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index fa2007c0ebe6..ab866de0645c 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -874,6 +874,54 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
# A repo with no such workflow yields an empty list (not an error).
assert api.list_workflow_runs(team=self.team, repo="PostHog/posthog", workflow_name="Nope") == []
+ def test_workflow_detail_branch_filter(self) -> None:
+ # The workflow detail page's runs list and runner-cost breakdown must honor the same branch scope
+ # as the Workflows tab — without it, drilling in from a branch-scoped tab widened back to every
+ # branch and showed more runs (and more cost) than the tab did.
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [_pr_row(90, "alice", "open", 0, _ago(1), head_sha="sha90")],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [
+ _run_row(8501, "CI", "sha-m1", "completed", "success", _ago(2), _ago(2), head_branch="main"),
+ _run_row(8502, "CI", "sha-m2", "completed", "failure", _ago(1), _ago(1), head_branch="main"),
+ _run_row(8503, "CI", "sha-r1", "completed", "success", _ago(1), _ago(1), head_branch="release"),
+ ],
+ )
+ self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(85010, 8501, "build", "success", labels='["depot-ubuntu-22.04-4"]'),
+ _job_row(85020, 8502, "build", "success", labels='["depot-ubuntu-22.04-4"]'),
+ _job_row(85030, 8503, "build", "success", labels='["depot-ubuntu-22.04-4"]'),
+ ],
+ )
+ repo, workflow = "PostHog/posthog", "CI"
+
+ # Runs list: unfiltered spans every branch; scoped keeps only that branch's runs.
+ all_runs = api.list_workflow_runs(team=self.team, repo=repo, workflow_name=workflow)
+ assert {r.id for r in all_runs} == {8501, 8502, 8503}
+ main_runs = api.list_workflow_runs(team=self.team, repo=repo, workflow_name=workflow, branch="main")
+ assert {r.id for r in main_runs} == {8501, 8502}
+ # A blank branch is "no filter", not a literal match on ''; an unknown branch yields nothing.
+ assert len(api.list_workflow_runs(team=self.team, repo=repo, workflow_name=workflow, branch=" ")) == 3
+ assert api.list_workflow_runs(team=self.team, repo=repo, workflow_name=workflow, branch="nope") == []
+
+ # Runner costs: the branch scope narrows the costed jobs the same way (3 jobs → 2 on main).
+ all_jobs = sum(
+ c.job_count for c in api.get_workflow_runner_costs(team=self.team, repo=repo, workflow_name=workflow)
+ )
+ main_jobs = sum(
+ c.job_count
+ for c in api.get_workflow_runner_costs(team=self.team, repo=repo, workflow_name=workflow, branch="main")
+ )
+ assert (all_jobs, main_jobs) == (3, 2)
+
def test_pr_runs_span_all_commits(self) -> None:
# The PR detail lists runs across all of the PR's commits (by association), not just head SHA.
self._create_table(
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 574333bdf161..51a53c0fc27f 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -253,7 +253,9 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
def test_workflow_runs_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.list_workflow_runs", return_value=[_workflow_run()]) as listing:
- response = self.client.get(self._url("workflow_runs"), {"workflow_name": "CI", "repo": "PostHog/posthog"})
+ response = self.client.get(
+ self._url("workflow_runs"), {"workflow_name": "CI", "repo": "PostHog/posthog", "branch": "main"}
+ )
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -261,12 +263,25 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert body[0]["id"] == 7777
assert listing.call_args.kwargs["workflow_name"] == "CI"
assert listing.call_args.kwargs["repo"] == "PostHog/posthog"
+ # The detail page's branch scope must reach the read layer, or the runs list widens to all branches.
+ assert listing.call_args.kwargs["branch"] == "main"
def test_workflow_runs_400_when_params_missing(self) -> None:
response = self.client.get(self._url("workflow_runs"), {"workflow_name": "CI"})
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_workflow_runner_costs_passes_branch_through(self) -> None:
+ # The cost breakdown shares the detail page's branch scope, so the branch must reach the read layer.
+ with mock.patch(f"{_VIEWS}.get_workflow_runner_costs", return_value=[]) as get_costs:
+ response = self.client.get(
+ self._url("workflow_runner_costs"),
+ {"workflow_name": "CI", "repo": "PostHog/posthog", "branch": "main"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert get_costs.call_args.kwargs["branch"] == "main"
+
def test_pr_runs_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.list_pr_runs", return_value=[_workflow_run()]) as listing:
response = self.client.get(self._url("pr_runs"), {"pr_number": "9100", "repo": "PostHog/posthog"})
diff --git a/products/engineering_analytics/frontend/components/BranchFilter.tsx b/products/engineering_analytics/frontend/components/BranchFilter.tsx
new file mode 100644
index 000000000000..7db2c69c054f
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/BranchFilter.tsx
@@ -0,0 +1,52 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+
+import { engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'
+
+// Quick presets for the default branch. We can't tell main from master without another query, so offer
+// both — clicking the active one clears back to all branches.
+const DEFAULT_BRANCHES = ['main', 'master']
+
+/** Branch scope control (server-side head_branch filter), shared by the Workflows tab and a single
+ * workflow's detail page so the scope carries between them. Reads/writes the shared filters logic; typing
+ * stages the value and Enter/blur (or a chip) applies it. */
+export function BranchFilter(): JSX.Element {
+ const { branchInput, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setBranchFilter, applyBranchFilter } = useActions(engineeringAnalyticsFiltersLogic)
+
+ // Stage + apply a branch in one click (the chips). Clicking the active chip clears back to all branches.
+ const selectBranch = (branch: string): void => {
+ setBranchFilter(branch)
+ applyBranchFilter()
+ }
+
+ return (
+ <>
+ <LemonInput
+ type="search"
+ size="small"
+ className="w-56"
+ placeholder="Branch: all (e.g. main)"
+ value={branchInput}
+ onChange={setBranchFilter}
+ onPressEnter={applyBranchFilter}
+ onBlur={applyBranchFilter}
+ data-attr="engineering-analytics-branch-filter"
+ />
+ {DEFAULT_BRANCHES.map((branch) => (
+ <LemonButton
+ key={branch}
+ size="xsmall"
+ type={appliedBranch === branch ? 'primary' : 'secondary'}
+ // Keep focus on the input so its onBlur doesn't fire first and apply whatever was
+ // staged there — a chip should apply exactly its own branch, in one reload.
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => selectBranch(appliedBranch === branch ? '' : branch)}
+ >
+ {branch}
+ </LemonButton>
+ ))}
+ </>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index e2e309f013a5..5ed36054d175 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -142,11 +142,13 @@ export function WorkflowHealthTable({
dataAttr = 'engineering-analytics-workflow-table',
}: WorkflowHealthTableProps): JSX.Element {
const { searchParams } = useValues(router)
- // Carry the active CI-analytics window into the drill-down so opening a workflow from a non-default
- // window keeps it instead of snapping back to the default (the tab links already preserve it this way).
+ // Carry the active CI-analytics window and branch scope into the drill-down so opening a workflow from a
+ // non-default window/branch keeps it instead of snapping back to defaults (the tab links preserve them
+ // the same way). Without the branch (`q`), the detail page would widen to all branches and show more runs.
const windowParams: Record<string, string> = {
...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
+ ...(searchParams.q ? { q: searchParams.q } : {}),
}
const columns: LemonTableColumns<WorkflowHealthRow> = [
{
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 4aec8240f596..2db779016e67 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -733,7 +733,7 @@ export type EngineeringAnalyticsQuarantineParams = {
export type EngineeringAnalyticsWorkflowHealthParams = {
/**
- * Optional exact git branch (head_branch) to scope workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
*/
branch?: string
/**
@@ -777,6 +777,10 @@ export type EngineeringAnalyticsWorkflowRunParams = {
}
export type EngineeringAnalyticsWorkflowRunnerCostsParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
@@ -800,6 +804,10 @@ export type EngineeringAnalyticsWorkflowRunnerCostsParams = {
}
export type EngineeringAnalyticsWorkflowRunsParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index b9ff79e9d683..c020db274f1e 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -416,7 +416,7 @@ export const getEngineeringAnalyticsWorkflowRunnerCostsUrl = (
}
/**
- * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Returns an empty list when the job-level source isn't synced.
+ * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an empty list when the job-level source isn't synced.
*/
export const engineeringAnalyticsWorkflowRunnerCosts = async (
projectId: string,
@@ -449,7 +449,7 @@ export const getEngineeringAnalyticsWorkflowRunsUrl = (
}
/**
- * Runs of a single workflow within a repo over a window (date_from default -30d), newest first. Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the workflow list and a single run.
+ * Runs of a single workflow within a repo over a window (date_from default -30d), newest first. Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the workflow list and a single run.
*/
export const engineeringAnalyticsWorkflowRuns = async (
projectId: string,
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index 1edd7873e23a..78810d9d0da0 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -1,10 +1,9 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
-
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { dateFilterToText, dateMapping } from 'lib/utils/dateFilters'
+import { BranchFilter } from '../components/BranchFilter'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
@@ -32,14 +31,12 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
workflowHealthLoading,
notConnected,
workflowHealthLoadError,
- branchInput,
- appliedBranch,
sourceId,
fleetSummary,
fleetTruncated,
} = useValues(engineeringAnalyticsLogic)
- const { setBranchFilter, applyBranchFilter, refresh } = useActions(engineeringAnalyticsLogic)
- const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { refresh } = useActions(engineeringAnalyticsLogic)
+ const { dateFrom, dateTo, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
if (notConnected) {
@@ -51,12 +48,6 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
const windowLabel = dateFilterToText(dateFrom, dateTo, 'Last 7 days') ?? 'Last 7 days'
- // Stage + apply a branch in one click (the chips). Clicking the active chip clears back to all branches.
- const selectBranch = (branch: string): void => {
- setBranchFilter(branch)
- applyBranchFilter()
- }
-
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
@@ -66,29 +57,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
dateOptions={WORKFLOW_DATE_OPTIONS}
/>
- <LemonInput
- type="search"
- size="small"
- className="w-56"
- placeholder="Branch: all (e.g. main)"
- value={branchInput}
- onChange={setBranchFilter}
- onPressEnter={applyBranchFilter}
- onBlur={applyBranchFilter}
- data-attr="engineering-analytics-branch-filter"
- />
- {/* Quick presets for the default branch. We can't tell main from master without another query,
- so offer both — clicking the active one clears back to all branches. */}
- {['main', 'master'].map((branch) => (
- <LemonButton
- key={branch}
- size="xsmall"
- type={appliedBranch === branch ? 'primary' : 'secondary'}
- onClick={() => selectBranch(appliedBranch === branch ? '' : branch)}
- >
- {branch}
- </LemonButton>
- ))}
+ <BranchFilter />
</div>
{workflowHealth.length > 0 && <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} />}
<WorkflowHealthTable
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index 8e2dfbcae905..2a6cff579fc4 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -14,6 +14,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { BillableBadge } from '../components/BillableBadge'
+import { BranchFilter } from '../components/BranchFilter'
import { DistributionBar } from '../components/DistributionBar'
import { RunActivityChart } from '../components/RunActivityChart'
import { RunnerBadge, RunsTable, formatCost } from '../components/runTables'
@@ -207,7 +208,9 @@ export function WorkflowRunsScene(): JSX.Element {
</LemonButton>
}
/>
- {/* One window scopes both the cost breakdown and the runs list below. */}
+ {/* One window + branch scope the cost breakdown and the runs list below — the same scope as the
+ Workflows tab, so numbers match after drilling in (a missing branch filter here read as more
+ runs than the tab showed). */}
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-semibold tracking-wide text-secondary uppercase">Window</span>
<DateFilter
@@ -217,6 +220,7 @@ export function WorkflowRunsScene(): JSX.Element {
dateOptions={WORKFLOW_DATE_OPTIONS}
size="small"
/>
+ <BranchFilter />
</div>
<WorkflowHealthHeader summary={healthSummary} cost={costSummary} truncated={runsTruncated} />
<RunActivityChart runs={runRows} truncated={runsTruncated} />
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
index b73fa1dfee9d..875734dfb459 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
@@ -1,4 +1,4 @@
-import { actions, kea, path, reducers } from 'kea'
+import { actions, kea, listeners, path, reducers } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import type { engineeringAnalyticsFiltersLogicType } from './engineeringAnalyticsFiltersLogicType'
@@ -11,18 +11,48 @@ import type { engineeringAnalyticsFiltersLogicType } from './engineeringAnalytic
// granularity auto-follows the window, so narrowing to 24h still gives the live hourly view on demand.
export const SHARED_DEFAULT_DATE_FROM = '-7d'
+// The branch scope is shared here too, alongside the window, so filtering to `master` on the Workflows tab
+// carries into a workflow's detail page instead of the detail silently widening back to all branches (which
+// read as "more runs" than the tab showed). It's a server-side filter (head_branch), so typing only stages
+// the value in branchInput; applyBranchFilter promotes it to appliedBranch, which the consuming logics send.
export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsFiltersLogic']),
actions({
setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setBranchFilter: (branch: string) => ({ branch }),
+ applyBranchFilter: true,
+ setAppliedBranch: (branch: string) => ({ branch }),
}),
reducers({
dateFrom: [SHARED_DEFAULT_DATE_FROM as string | null, { setDateRange: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateRange: (_, { dateTo }) => dateTo }],
+ // branchInput is the staged text in the box; appliedBranch is what the consuming loaders send. '' means
+ // all branches. appliedBranch persists across date reloads (e.g. "master on last 30d" → "last 90d").
+ branchInput: ['', { setBranchFilter: (_, { branch }) => branch }],
+ appliedBranch: ['', { setAppliedBranch: (_, { branch }) => branch }],
}),
+ listeners(({ actions, values }) => ({
+ setBranchFilter: ({ branch }) => {
+ // The search input's built-in clear (×) only fires onChange(''), never Enter/blur, so clearing it
+ // would otherwise leave the tables scoped to the old branch. Apply on empty so the × resets to
+ // all-branches immediately.
+ if (branch.trim() === '') {
+ actions.applyBranchFilter()
+ }
+ },
+ applyBranchFilter: () => {
+ const next = values.branchInput.trim()
+ // Skip promoting (and the reload it triggers in consumers) when the box is unchanged.
+ if (next === values.appliedBranch) {
+ return
+ }
+ actions.setAppliedBranch(next)
+ },
+ })),
+
actionToUrl(({ values }) => ({
// Encode the window in the URL so tab links and drill-down links (which preserve query params) carry
// it, and a shared link reopens it. Replace, not push — nudging a date shouldn't stack back-history.
@@ -42,6 +72,18 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
}
return [pathname, next, hashParams, { replace: true }]
},
+ // Mirror the applied branch into `?q=` so a branch-scoped view is shareable, survives reload, and
+ // carries through drill-down links into the workflow detail page. Empty is omitted to keep URLs clean.
+ setAppliedBranch: () => {
+ const { pathname, searchParams, hashParams } = router.values.currentLocation
+ const next = { ...searchParams }
+ if (values.appliedBranch) {
+ next.q = values.appliedBranch
+ } else {
+ delete next.q
+ }
+ return [pathname, next, hashParams, { replace: true }]
+ },
})),
urlToAction(({ actions, values }) => ({
@@ -55,6 +97,14 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
if (dateFrom !== values.dateFrom || dateTo !== values.dateTo) {
actions.setDateRange(dateFrom, dateTo)
}
+ const branch = (searchParams.q ?? '').trim()
+ if (branch !== values.appliedBranch) {
+ actions.setBranchFilter(branch)
+ // An empty value already applies via setBranchFilter's listener; a real branch needs the apply.
+ if (branch !== '') {
+ actions.setAppliedBranch(branch)
+ }
+ }
},
})),
])
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index afa6d35c345a..6e89f5614ef1 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -356,7 +356,9 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '2026-01-01', date_to: '2026-03-01' })
})
- it('filters workflow health by branch server-side, only reloading on a real change', async () => {
+ it('filters workflow health by the shared branch scope, only reloading on a real change', async () => {
+ // Branch lives in the shared filters logic (so it carries into the workflow detail page); the
+ // Workflows tab reads it and reloads workflow health when it's applied.
logic = engineeringAnalyticsLogic()
logic.mount()
const filters = engineeringAnalyticsFiltersLogic()
@@ -365,20 +367,20 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })
// Typing only stages the value — no reload until applied.
- logic.actions.setBranchFilter('main')
- expect(logic.values.branchInput).toBe('main')
- expect(logic.values.appliedBranch).toBe('')
+ filters.actions.setBranchFilter('main')
+ expect(filters.values.branchInput).toBe('main')
+ expect(filters.values.appliedBranch).toBe('')
// Applying promotes it and reloads with the branch param (trimmed).
- logic.actions.setBranchFilter(' main ')
- logic.actions.applyBranchFilter()
+ filters.actions.setBranchFilter(' main ')
+ filters.actions.applyBranchFilter()
await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
- expect(logic.values.appliedBranch).toBe('main')
+ expect(filters.values.appliedBranch).toBe('main')
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', branch: 'main' })
// Re-applying an unchanged value (e.g. a blur with no edit) does not reload.
mockWorkflowHealth.mockClear()
- logic.actions.applyBranchFilter()
+ filters.actions.applyBranchFilter()
await expectLogic(logic).toNotHaveDispatchedActions(['loadWorkflowHealth'])
expect(mockWorkflowHealth).not.toHaveBeenCalled()
@@ -389,9 +391,9 @@ describe('engineeringAnalyticsLogic', () => {
// Clearing the box (e.g. the search × button, which only fires onChange('')) applies
// immediately — no Enter/blur needed — and drops the filter.
- logic.actions.setBranchFilter('')
+ filters.actions.setBranchFilter('')
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
- expect(logic.values.appliedBranch).toBe('')
+ expect(filters.values.appliedBranch).toBe('')
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })
})
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 0e4e8e30b6db..e53a65cc5496 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -485,9 +485,10 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
kea<engineeringAnalyticsLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsLogic']),
- // The Workflows tab reads the shared CI-analytics window; the loader and reload listener use it.
+ // The Workflows tab reads the shared CI-analytics window and branch scope; the loader and reload
+ // listeners use them.
connect(() => ({
- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],
})),
actions({
@@ -497,11 +498,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setCiStatusFilter: (ciStatus: CIStatusFilter) => ({ ciStatus }),
setSearch: (search: string) => ({ search }),
setStuckOnly: (stuckOnly: boolean) => ({ stuckOnly }),
- // Branch is filtered server-side (it's aggregated away in workflow health), so typing only
- // stages the value in branchInput; applyBranchFilter promotes it to appliedBranch and reloads.
- setBranchFilter: (branch: string) => ({ branch }),
- applyBranchFilter: true,
- setAppliedBranch: (branch: string) => ({ branch }),
applyCardFilter: (card: CardFilter) => ({ card }),
setSourceId: (sourceId: string | null) => ({ sourceId }),
setCostLensEnabled: (enabled: boolean) => ({ enabled }),
@@ -663,11 +659,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
DEFAULT_FILTERS.search,
{ setSearch: (_, { search }) => search, resetFilters: () => DEFAULT_FILTERS.search },
],
- // Exact git branch to scope workflow health to; '' means all branches. branchInput is the
- // staged text in the box; appliedBranch is what the loader sends. Server-side filter, so
- // appliedBranch persists across date reloads (e.g. "main on last 30d" → "main on last 90d").
- branchInput: ['', { setBranchFilter: (_, { branch }) => branch }],
- appliedBranch: ['', { setAppliedBranch: (_, { branch }) => branch }],
// Leaving the open backlog (e.g. switching to Merged) exits the stuck lens — stuck implies open.
stuckOnly: [
DEFAULT_FILTERS.stuckOnly,
@@ -903,27 +894,11 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
// Cards, the PR list, workflow health, and the quarantine repo are all per-source — reload them all.
setSourceId: () => actions.refresh(),
- // The shared window scopes workflow health; reload it when the window changes.
+ // The shared window and branch scope workflow health; reload it when either changes.
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowHealth()
},
- setBranchFilter: ({ branch }) => {
- // The search input's built-in clear (×) only fires onChange(''), never Enter/blur, so
- // clearing it would otherwise leave the table scoped to the old branch. Apply on empty
- // so the × resets to all-branches immediately.
- if (branch.trim() === '') {
- actions.applyBranchFilter()
- }
- },
- applyBranchFilter: () => {
- const next = values.branchInput.trim()
- // Skip the reload when the box is unchanged (e.g. a focus/blur with no edit).
- if (next === values.appliedBranch) {
- return
- }
- actions.setAppliedBranch(next)
- },
- setAppliedBranch: () => {
+ [engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {
actions.loadWorkflowHealth()
},
applyCardFilter: ({ card }) => {
@@ -975,44 +950,20 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
}
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
},
- // Mirror the applied branch into `?q=` so a branch-scoped view is shareable and survives reload.
- setAppliedBranch: ({ branch }) => {
- const searchParams = { ...router.values.searchParams }
- if (branch) {
- searchParams.q = branch
- } else {
- delete searchParams.q
- }
- return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
- },
})),
urlToAction(({ actions, values }) => {
// The chosen source rides in `?source=` so it survives tab switches and deep-links into a PR's detail.
+ // (The shared branch scope in `?q=` is hydrated by engineeringAnalyticsFiltersLogic, not here.)
const applySource = (source: string | undefined): void => {
const next = source ?? null
if (next !== values.sourceId) {
actions.setSourceId(next)
}
}
- // `?q=` deep-links a branch-scoped workflow view (e.g. ?q=master). Stage it in the box and apply.
- const applyBranchFromUrl = (q: string | undefined): void => {
- const next = (q ?? '').trim()
- if (next === values.appliedBranch) {
- return
- }
- actions.setBranchFilter(next)
- // An empty value already applies+loads via setBranchFilter's listener; a real branch needs the apply.
- if (next !== '') {
- actions.setAppliedBranch(next)
- }
- }
return {
[urls.engineeringAnalytics()]: (_, searchParams) => applySource(searchParams.source),
- [urls.engineeringAnalyticsWorkflows()]: (_, searchParams) => {
- applySource(searchParams.source)
- applyBranchFromUrl(searchParams.q)
- },
+ [urls.engineeringAnalyticsWorkflows()]: (_, searchParams) => applySource(searchParams.source),
}
}),
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
new file mode 100644
index 000000000000..5c659e06903f
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
@@ -0,0 +1,68 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { ApiConfig } from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ engineeringAnalyticsWorkflowJobs,
+ engineeringAnalyticsWorkflowRunnerCosts,
+ engineeringAnalyticsWorkflowRuns,
+} from '../generated/api'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+import { workflowRunsLogic } from './workflowRunsLogic'
+
+jest.mock('../generated/api', () => ({
+ engineeringAnalyticsWorkflowJobs: jest.fn(),
+ engineeringAnalyticsWorkflowRunnerCosts: jest.fn(),
+ engineeringAnalyticsWorkflowRuns: jest.fn(),
+}))
+
+const mockRuns = engineeringAnalyticsWorkflowRuns as jest.MockedFunction<typeof engineeringAnalyticsWorkflowRuns>
+const mockRunnerCosts = engineeringAnalyticsWorkflowRunnerCosts as jest.MockedFunction<
+ typeof engineeringAnalyticsWorkflowRunnerCosts
+>
+const mockJobs = engineeringAnalyticsWorkflowJobs as jest.MockedFunction<typeof engineeringAnalyticsWorkflowJobs>
+
+describe('workflowRunsLogic', () => {
+ let logic: ReturnType<typeof workflowRunsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ ApiConfig.setCurrentProjectId(1)
+ jest.clearAllMocks()
+ mockRuns.mockResolvedValue([])
+ mockRunnerCosts.mockResolvedValue([])
+ mockJobs.mockResolvedValue([])
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('scopes the runs list and cost breakdown to the shared branch, reloading both on a change', async () => {
+ logic = workflowRunsLogic({ repoOwner: 'PostHog', repoName: 'posthog', workflowName: 'CI', sourceId: null })
+ logic.mount()
+ const filters = engineeringAnalyticsFiltersLogic()
+ filters.mount()
+ await expectLogic(logic).toDispatchActions(['loadRunsSuccess', 'loadRunnerCostsSuccess'])
+
+ // No branch applied → the endpoints see every branch (the pre-fix behavior for the whole page).
+ const runsArgs = { workflow_name: 'CI', repo: 'PostHog/posthog', date_from: '-7d', branch: undefined }
+ expect(mockRuns).toHaveBeenLastCalledWith('1', expect.objectContaining(runsArgs))
+ expect(mockRunnerCosts).toHaveBeenLastCalledWith('1', expect.objectContaining(runsArgs))
+
+ // Applying a branch on the shared filters logic reloads both lists scoped to it — so the detail
+ // page's numbers match the branch-scoped Workflows tab instead of widening back to all branches.
+ filters.actions.setBranchFilter('master')
+ filters.actions.applyBranchFilter()
+ await expectLogic(logic).toDispatchActions([
+ 'loadRuns',
+ 'loadRunnerCosts',
+ 'loadRunsSuccess',
+ 'loadRunnerCostsSuccess',
+ ])
+ expect(mockRuns).toHaveBeenLastCalledWith('1', expect.objectContaining({ branch: 'master' }))
+ expect(mockRunnerCosts).toHaveBeenLastCalledWith('1', expect.objectContaining({ branch: 'master' }))
+ })
+})
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 76b50d9bc938..13a096d5640a 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -51,10 +51,11 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
props({} as WorkflowRunsLogicProps),
key((props) => `${props.repoOwner}/${props.repoName}/${props.workflowName}@${props.sourceId ?? ''}`),
- // The shared CI-analytics window scopes both the runs list and the runner-cost breakdown — one window,
- // never all-time, and the same one the Workflows tab and author page use.
+ // The shared CI-analytics window and branch scope both the runs list and the runner-cost breakdown —
+ // one window and branch, the same the Workflows tab uses, so drilling in from a branch-scoped tab keeps
+ // that scope instead of silently widening back to all branches (which reads as "more runs").
connect(() => ({
- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],
})),
actions({
@@ -77,6 +78,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
repo: `${props.repoOwner}/${props.repoName}`,
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
+ branch: values.appliedBranch || undefined,
source_id: props.sourceId ?? undefined,
}),
},
@@ -91,6 +93,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
repo: `${props.repoOwner}/${props.repoName}`,
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
+ branch: values.appliedBranch || undefined,
source_id: props.sourceId ?? undefined,
}),
},
@@ -220,11 +223,15 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
actions.loadJobs({ runId, runAttempt })
}
},
- // The shared window scopes both lists — reload them together when it changes.
+ // The shared window and branch scope both lists — reload them together when either changes.
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadRuns()
actions.loadRunnerCosts()
},
+ [engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {
+ actions.loadRuns()
+ actions.loadRunnerCosts()
+ },
})),
afterMount(({ actions }) => {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3f5fc98821b8..eea1914c8719 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -61629,7 +61629,7 @@ export namespace Schemas {
export type EngineeringAnalyticsWorkflowHealthParams = {
/**
- * Optional exact git branch (head_branch) to scope workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
*/
branch?: string;
/**
@@ -61673,6 +61673,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsWorkflowRunnerCostsParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string;
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
@@ -61696,6 +61700,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsWorkflowRunsParams = {
+ /**
+ * Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
+ */
+ branch?: string;
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index dc4aa5222417..80a3e983ea0c 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -123,7 +123,7 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod
.string()
.optional()
.describe(
- "Optional exact git branch (head_branch) to scope workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches."
+ "Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches."
),
date_from: zod.string().optional().describe("Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h."),
date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
@@ -163,7 +163,7 @@ export const EngineeringAnalyticsWorkflowJobsQueryParams = /* @__PURE__ */ zod.o
})
/**
- * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Returns an empty list when the job-level source isn't synced.
+ * A workflow's estimated CI cost broken down by runner tier over a window (date_from default -30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an empty list when the job-level source isn't synced.
*/
export const EngineeringAnalyticsWorkflowRunnerCostsParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -174,6 +174,12 @@ export const EngineeringAnalyticsWorkflowRunnerCostsParams = /* @__PURE__ */ zod
})
export const EngineeringAnalyticsWorkflowRunnerCostsQueryParams = /* @__PURE__ */ zod.object({
+ branch: zod
+ .string()
+ .optional()
+ .describe(
+ "Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches."
+ ),
date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),
date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
repo: zod.string().describe("'owner/name' repository the workflow belongs to."),
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 0708e7a2eaac..d2f64548cc5f 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -113,6 +113,7 @@ const engineeringAnalyticsWorkflowRunnerCosts = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/workflow_runner_costs/`,
query: {
+ branch: params.branch,
date_from: params.date_from,
date_to: params.date_to,
repo: params.repo,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json
index 44a3882b908d..52b142ac266d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-workflow-runner-costs.json
@@ -1,6 +1,10 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "branch": {
+ "description": "Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.",
+ "type": "string"
+ },
"date_from": {
"description": "Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
index 3392b9c68d7e..f8132cf55a22 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"branch": {
- "description": "Optional exact git branch (head_branch) to scope workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches.",
+ "description": "Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.",
"type": "string"
},
"date_from": {