:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(visual_review): add free-text search for runs (#64173)
Fernando Gomes530acec91a5e
diff --git a/posthog/helpers/trigram_search.py b/posthog/helpers/trigram_search.pyindex 22e84552dbb0..4cf38183243f 100644--- a/posthog/helpers/trigram_search.py+++ b/posthog/helpers/trigram_search.py@@ -78,6 +78,7 @@ def apply_trigram_search(span_prefix: str,fields: tuple[TrigramSearchField, ...],include_tag_search: bool = False,+ extra_exact_q: Q | None = None,tiebreakers: tuple[str, ...] = (),) -> QuerySet:"""Apply trigram + literal-substring search across `fields`, then order exact-first.@@ -92,6 +93,10 @@ def apply_trigram_search(similarity (plus full-string similarity where `include_full` is set). `tiebreakers` areappended after the score (e.g. `-pinned`, `name`).+ `extra_exact_q` OR's caller-supplied predicates into the exact tier — for structured+ fields that don't fit trigram (a commit-SHA prefix, an exact numeric id). Rows matched+ this way are flagged `_is_exact=1` and sort with the literal-substring matches.+When `include_tag_search=True`, rows whose tag names contain the term also match (as`exact`), and `.distinct()` dedups the tag-join fan-out.@@ -117,6 +122,8 @@ def apply_trigram_search(if f.literal:# nosemgrep: orm-field-injection — f.field is a developer-defined TrigramSearchField path, not user input; only `search` is user-controlled and it is the bound valueexact_q |= Q(**{f"{f.field}__icontains": search})+ if extra_exact_q is not None:+ exact_q |= extra_exact_qif include_tag_search:matching_tag_ids = queryset.filter(tagged_items__tag__name__icontains=search).values("id")exact_q |= Q(id__in=matching_tag_ids)diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 2a3d4e23878e..d275ea63802f 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -19,6 +19,8 @@ from uuid import UUIDfrom django.contrib.auth import get_user_model+from posthog.helpers.trigram_search import search_match_type_from_instance+from .. import logicfrom ..diff_metadata import DiffMetadatafrom . import contracts@@ -188,6 +190,8 @@ def _to_run(run, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = Nsuperseded_by_id=run.superseded_by_id,approved_by=approved_by,metadata=run.metadata or {},+ # Present only when the queryset came from a trigram search (annotation absent otherwise).+ search_match_type=search_match_type_from_instance(run),)@@ -313,6 +317,7 @@ def list_runs(pr_number: int | None = None,commit_sha: str | None = None,branch: str | None = None,+ search: str | None = None,) -> list[contracts.Run]:runs = logic.list_runs_for_team(team_id,@@ -321,6 +326,7 @@ def list_runs(pr_number=pr_number,commit_sha=commit_sha,branch=branch,+ search=search,)return [_to_run(r) for r in runs]diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex b712f35fd3f6..06024cbe41bd 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -272,6 +272,8 @@ class Run:approved_by: UserBasicInfo | None = None# Flexible metadata (pr_title, ci_job_url, base_branch, etc.)metadata: dict = field(default_factory=dict)+ # How this row matched the `search` query param: "exact", "similar", or None when not searching.+ search_match_type: str | None = None@dataclass(frozen=True)diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex b62953cdb353..ee9bf331c235 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -30,6 +30,7 @@ import structlogif TYPE_CHECKING:from posthog.models.integration import GitHubIntegration+from posthog.helpers.trigram_search import TrigramSearchField, apply_trigram_search, normalize_search_termfrom posthog.models.integration import GitHubRateLimitErrorfrom .classifier import SnapshotClassifier@@ -266,6 +267,13 @@ REVIEW_STATE_FILTERS: dict[str, Q] = {}+# Free-text search over the runs list uses the shared trigram helper for the+# prose-like fields (branch, run type), where fuzzy/typo matching helps. Commit+# SHA and PR number are matched exactly (prefix / numeric id) via extra_exact_q —+# fuzzy matching a hex SHA or an integer is meaningless.+RUN_SEARCH_FIELDS = (TrigramSearchField("branch"), TrigramSearchField("run_type"))++def list_runs_for_team(team_id: int,review_state: str | None = None,@@ -273,8 +281,9 @@ def list_runs_for_team(pr_number: int | None = None,commit_sha: str | None = None,branch: str | None = None,+ search: str | None = None,) -> db_models.QuerySet[Run]:- qs = Run.objects.filter(team_id=team_id).select_related("repo").order_by("-created_at")+ qs = Run.objects.filter(team_id=team_id).select_related("repo")if repo_id is not None:qs = qs.filter(repo_id=repo_id)if review_state and review_state in REVIEW_STATE_FILTERS:@@ -285,7 +294,20 @@ def list_runs_for_team(qs = qs.filter(commit_sha=commit_sha)if branch:qs = qs.filter(branch=branch)- return qs+ if search and (term := normalize_search_term(search)):+ # Commit SHA matches by prefix (reviewers paste the short SHA); PR number by exact id.+ extra_exact_q = Q(commit_sha__istartswith=term)+ if term.isdigit():+ extra_exact_q |= Q(pr_number=int(term))+ return apply_trigram_search(+ qs,+ term,+ span_prefix="visual_review.runs.search",+ fields=RUN_SEARCH_FIELDS,+ extra_exact_q=extra_exact_q,+ tiebreakers=("-created_at",),+ )+ return qs.order_by("-created_at")def get_review_state_counts(team_id: int, repo_id: UUID | None = None) -> dict[str, int]:diff --git a/products/visual_review/backend/migrations/0014_run_search_trgm.py b/products/visual_review/backend/migrations/0014_run_search_trgm.pynew file mode 100644index 000000000000..6f0e29f1ed03--- /dev/null+++ b/products/visual_review/backend/migrations/0014_run_search_trgm.py@@ -0,0 +1,16 @@+from django.contrib.postgres.operations import TrigramExtension+from django.db import migrations+++class Migration(migrations.Migration):+ # Free-text runs search uses pg_trgm word_similarity over branch / run_type.+ # visual_review runs on its own Postgres database, so the extension has to be+ # enabled here — the main DB's pg_trgm (posthog migration 0034) doesn't reach it.+ # CREATE EXTENSION IF NOT EXISTS is idempotent, so this is safe on DBs that already have it.+ dependencies = [+ ("visual_review", "0013_run_is_partial"),+ ]++ operations = [+ TrigramExtension(),+ ]diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txtindex 08b26e5da0ca..b4efb6c9edc2 100644--- a/products/visual_review/backend/migrations/max_migration.txt+++ b/products/visual_review/backend/migrations/max_migration.txt@@ -1 +1 @@-0013_run_is_partial+0014_run_search_trgmdiff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex 734fc6808af7..19ae29d9f472 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -91,6 +91,18 @@ class SnapshotSerializer(DataclassSerializer):class RunSerializer(DataclassSerializer):approved_by = UserBasicInfoSerializer(allow_null=True, required=False)+ search_match_type = serializers.ChoiceField(+ choices=["exact", "similar"],+ allow_null=True,+ required=False,+ read_only=True,+ help_text=(+ "How this row matched the `search` query parameter: `exact` (the term is a "+ "case-insensitive substring of branch/run type, a commit SHA prefix, or an exact PR "+ "number) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. "+ "Null when the list is not filtered by `search`."+ ),+ )class Meta:dataclass = Rundiff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex ee176f2d6b1a..23b1999df837 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -26,6 +26,7 @@ from rest_framework.response import Responsefrom posthog.api.mixins import TypedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTHfrom ..facade import api, contractsfrom ..facade.contracts import (@@ -346,14 +347,26 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(parameters=[OpenApiParameter("review_state", str, required=False, description="Filter by review state"),+ OpenApiParameter(+ "search",+ str,+ required=False,+ description="Free-text search over branch, commit SHA, run type, and PR number",+ ),],responses={200: RunSerializer(many=True)},)def list(self, request: Request, **kwargs) -> Response:- """List runs in this repo, optionally filtered by review state."""+ """List runs in this repo, optionally filtered by review state and free-text search."""review_state = request.query_params.get("review_state")+ search = request.query_params.get("search")+ if search and len(search) > MAX_SEARCH_LENGTH:+ return Response(+ {"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},+ status=status.HTTP_400_BAD_REQUEST,+ )repo_id = UUID(self.parents_query_dict["repo_id"])- runs = api.list_runs(self.team_id, review_state=review_state, repo_id=repo_id)+ runs = api.list_runs(self.team_id, review_state=review_state, repo_id=repo_id, search=search)page = self.paginate_queryset(runs)if page is not None:serializer = RunSerializer(instance=page, many=True)@@ -395,22 +408,35 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):OpenApiParameter("pr_number", int, required=False, description="Filter by GitHub PR number"),OpenApiParameter("commit_sha", str, required=False, description="Filter by full commit SHA"),OpenApiParameter("branch", str, required=False, description="Filter by branch name"),+ OpenApiParameter(+ "search",+ str,+ required=False,+ description="Free-text search over branch, commit SHA, run type, and PR number",+ ),],responses={200: RunSerializer(many=True)},)def list(self, request: Request, **kwargs) -> Response:- """List runs for the team, optionally filtered by review state, PR number, commit SHA, or branch."""+ """List runs for the team, optionally filtered by review state, PR number, commit SHA, branch, or free-text search."""pr_number_raw = request.query_params.get("pr_number")try:pr_number = int(pr_number_raw) if pr_number_raw is not None else Noneexcept ValueError:return Response({"detail": "pr_number must be an integer"}, status=status.HTTP_400_BAD_REQUEST)+ search = request.query_params.get("search")+ if search and len(search) > MAX_SEARCH_LENGTH:+ return Response(+ {"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},+ status=status.HTTP_400_BAD_REQUEST,+ )runs = api.list_runs(self.team_id,review_state=request.query_params.get("review_state"),pr_number=pr_number,commit_sha=request.query_params.get("commit_sha"),branch=request.query_params.get("branch"),+ search=search,)page = self.paginate_queryset(runs)if page is not None:diff --git a/products/visual_review/backend/tests/conftest.py b/products/visual_review/backend/tests/conftest.pyindex ec5c7daccba4..6f660e3af1fc 100644--- a/products/visual_review/backend/tests/conftest.py+++ b/products/visual_review/backend/tests/conftest.py@@ -16,6 +16,8 @@ from pathlib import Pathimport pytestfrom unittest.mock import MagicMock+from django.db import connections+import responsesfrom posthog.models.scoping import team_scope@@ -25,6 +27,19 @@ from products.visual_review.backend.models import RepoPRODUCT_DATABASES = {"default", "visual_review_db_writer", "visual_review_db_reader"}[email protected](scope="package", autouse=True)+def _enable_pg_trgm_on_visual_review_db(django_db_setup, django_db_blocker):+ """Runs search uses pg_trgm on the visual_review product database, which is a separate+ Postgres DB from default (so the default DB's pg_trgm doesn't reach it). Enable it once+ per package, after django_db_setup has created the product test databases. Scoped to+ this product's conftest (and to package scope, matching django_db_setup) so other+ products' test sessions — which don't create the visual_review test database — are+ unaffected."""+ with django_db_blocker.unblock():+ with connections["visual_review_db_writer"].cursor() as cursor:+ cursor.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")++@pytest.fixture(autouse=True)def _set_team_scope(request):"""Set team context for raw pytest tests that use the database.diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.pyindex d23dd9a5eeb3..684074b6b37e 100644--- a/products/visual_review/backend/tests/test_presentation.py+++ b/products/visual_review/backend/tests/test_presentation.py@@ -1,6 +1,6 @@"""Integration tests for visual_review DRF views."""-from urllib.parse import quote+from urllib.parse import quote, urlencodefrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -9,6 +9,8 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH+from products.visual_review.backend import logicfrom products.visual_review.backend.facade import apifrom products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem@@ -505,6 +507,122 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):self.assertEqual(response.json()["count"], 0)+class TestRepoRunsSearch(VisualReviewTeamScopedTestMixin, APIBaseTest):+ databases = PRODUCT_DATABASES++ def setUp(self):+ super().setUp()+ self.vr_project = api.create_repo(team_id=self.team.id, repo_external_id=88888, repo_full_name="org/searchtest")+ # Two completed runs with no changes — both land in the "clean" review state.+ self.run_login = Run.objects.create(+ repo_id=self.vr_project.id,+ team_id=self.team.id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc1234deadbeefcafef00d",+ branch="feature/login",+ pr_number=101,+ status=RunStatus.COMPLETED,+ )+ self.run_logout = Run.objects.create(+ repo_id=self.vr_project.id,+ team_id=self.team.id,+ run_type=RunType.PLAYWRIGHT,+ commit_sha="fed9876feedface00112233",+ branch="fix/logout",+ pr_number=202,+ status=RunStatus.COMPLETED,+ )++ def _runs_url(self, **params: str) -> str:+ base = f"/api/projects/{self.team.id}/visual_review/repos/{self.vr_project.id}/runs/"+ if not params:+ return base+ return f"{base}?{urlencode(params)}"++ def _team_runs_url(self, **params: str) -> str:+ base = f"/api/projects/{self.team.id}/visual_review/runs/"+ if not params:+ return base+ return f"{base}?{urlencode(params)}"++ def _branches(self, response_json: dict) -> set[str]:+ return {run["branch"] for run in response_json["results"]}++ @parameterized.expand(+ [+ # Exact substring on branch ("feature" stays below the fuzzy threshold for fix/logout).+ ("branch_substring", "feature", {"feature/login"}),+ # Exact substring on run type.+ ("run_type", "playwright", {"fix/logout"}),+ # Commit SHA matches by prefix.+ ("commit_sha_prefix", "abc1234", {"feature/login"}),+ # A substring that is not a prefix of the SHA must not match (prefix, not substring).+ ("commit_sha_mid_substring_excluded", "deadbeef", set()),+ # PR number matches exactly.+ ("pr_number", "101", {"feature/login"}),+ # Case-insensitive.+ ("case_insensitive", "FEATURE", {"feature/login"}),+ # A typo in the branch still matches via trigram similarity.+ ("fuzzy_branch_typo", "featuer", {"feature/login"}),+ # A typo in the run type still matches via trigram similarity.+ ("fuzzy_run_type_typo", "storybok", {"feature/login"}),+ ("no_match", "zzzznomatch", set()),+ ]+ )+ def test_search_filters_runs(self, _name: str, search: str, expected_branches: set[str]):+ response = self.client.get(self._runs_url(search=search))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self._branches(response.json()), expected_branches)++ def test_exact_matches_rank_before_fuzzy_and_set_match_type(self):+ # "login" is a substring of feature/login (exact) and a fuzzy match for fix/logout (similar).+ results = self.client.get(self._runs_url(search="login")).json()["results"]++ self.assertEqual([run["branch"] for run in results], ["feature/login", "fix/logout"])+ self.assertEqual([run["search_match_type"] for run in results], ["exact", "similar"])++ def test_match_type_is_null_without_search(self):+ results = self.client.get(self._runs_url()).json()["results"]++ self.assertTrue(results)+ self.assertTrue(all(run["search_match_type"] is None for run in results))++ def test_blank_search_returns_all_runs(self):+ response = self.client.get(self._runs_url(search=""))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self._branches(response.json()), {"feature/login", "fix/logout"})++ def test_search_composes_with_review_state(self):+ """Search narrows within whichever review state is active, not the whole repo."""+ both = self.client.get(self._runs_url(review_state="clean"))+ self.assertEqual(self._branches(both.json()), {"feature/login", "fix/logout"})++ scoped = self.client.get(self._runs_url(review_state="clean", search="feature"))+ self.assertEqual(scoped.status_code, status.HTTP_200_OK)+ self.assertEqual(self._branches(scoped.json()), {"feature/login"})++ # A run that exists but is not in the requested state is excluded even on a match.+ other_state = self.client.get(self._runs_url(review_state="processing", search="feature"))+ self.assertEqual(self._branches(other_state.json()), set())++ def test_team_wide_endpoint_supports_search(self):+ # The project-wide endpoint (exposed as the MCP tool) shares the same search path.+ response = self.client.get(self._team_runs_url(search="feature"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self._branches(response.json()), {"feature/login"})++ @parameterized.expand([("repo_scoped", "_runs_url"), ("team_wide", "_team_runs_url")])+ def test_overlong_search_is_rejected(self, _name: str, url_method: str):+ # Cap the term before it reaches the trigram comparison (pathological CPU cost).+ url = getattr(self, url_method)(search="x" * (MAX_SEARCH_LENGTH + 1))+ response = self.client.get(url)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++class TestRunFinalizePersonalAPIKeyScopes(VisualReviewTeamScopedTestMixin, APIBaseTest):databases = PRODUCT_DATABASESCONFIG_AUTO_LOGIN = Falsediff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 9aade79ff911..5726a7bb6e7e 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -153,6 +153,13 @@ export interface QuarantineInputApi {expires_at?: string | null}+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+export interface RunSummaryApi {total: numberchanged: number@@ -167,6 +174,11 @@ export type RunApiMetadata = { [key: string]: unknown }export interface RunApi {approved_by?: UserBasicInfoApi | null+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of branch/run type, a commit SHA prefix, or an exact PR number) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`.+ *+ * * `exact` - exact+ * * `similar` - similar */+ readonly search_match_type: SearchMatchTypeEnumApi | nullid: stringrepo_id: stringstatus: string@@ -464,6 +476,10 @@ export type VisualReviewReposRunsListParams = {* Filter by review state*/review_state?: string+ /**+ * Free-text search over branch, commit SHA, run type, and PR number+ */+ search?: string}export type VisualReviewReposSnapshotsListParams = {@@ -502,6 +518,10 @@ export type VisualReviewRunsListParams = {* Filter by review state*/review_state?: string+ /**+ * Free-text search over branch, commit SHA, run type, and PR number+ */+ search?: string}export type VisualReviewRunsSnapshotHistoryListParams = {diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.tsindex cd8ab6fe4181..aec3bed0c147 100644--- a/products/visual_review/frontend/generated/api.ts+++ b/products/visual_review/frontend/generated/api.ts@@ -272,7 +272,7 @@ export const getVisualReviewReposRunsListUrl = (}/**- * List runs in this repo, optionally filtered by review state.+ * List runs in this repo, optionally filtered by review state and free-text search.*/export const visualReviewReposRunsList = async (projectId: string,@@ -363,7 +363,7 @@ export const getVisualReviewRunsListUrl = (projectId: string, params?: VisualRev}/**- * List runs for the team, optionally filtered by review state, PR number, commit SHA, or branch.+ * List runs for the team, optionally filtered by review state, PR number, commit SHA, branch, or free-text search.*/export const visualReviewRunsList = async (projectId: string,diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsxindex e2cc2db53e32..8b0150d8ffa6 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx@@ -47,6 +47,7 @@ const run: RunApi = {completed_at: '2026-06-10T00:01:00Z',is_stale: false,metadata: {},+ search_match_type: null,}const snapshot = (overrides: Partial<SnapshotApi>): SnapshotApi => ({diff --git a/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsxindex 1bd447878760..8274b85dd725 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx@@ -2,7 +2,15 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { IconGear, IconGithub } from '@posthog/icons'-import { LemonButton, LemonSegmentedButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonInput,+ LemonSegmentedButton,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ Link,+} from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { SceneExport } from 'scenes/sceneTypes'@@ -61,9 +69,9 @@ const TAB_COUNT_TYPES: Record<ReviewState, 'warning' | 'highlight' | 'default' |}export function VisualReviewRunsScene(): JSX.Element {- const { runs, runsLoading, activeTab, counts, repoId, repoFullName, page, totalCount } =+ const { runs, runsLoading, activeTab, counts, repoId, repoFullName, page, totalCount, searchQuery } =useValues(visualReviewRunsSceneLogic)- const { loadRuns, loadCounts, setActiveTab, setPage } = useActions(visualReviewRunsSceneLogic)+ const { loadRuns, loadCounts, setActiveTab, setPage, setSearchQuery } = useActions(visualReviewRunsSceneLogic)const columns: LemonTableColumns<RunApi> = [{@@ -146,7 +154,7 @@ export function VisualReviewRunsScene(): JSX.Element {/><VisualReviewTabs activeKey="runs" repoId={repoId} />- <div className="mb-3 flex items-center gap-2">+ <div className="mb-3 flex items-center gap-2 flex-wrap"><LemonSegmentedButtonvalue={activeTab}onChange={(value) => setActiveTab(value)}@@ -165,6 +173,15 @@ export function VisualReviewRunsScene(): JSX.Element {}))}size="small"/>+ {/* Search stays mounted across every tab so it filters whichever state is active. */}+ <LemonInput+ type="search"+ placeholder="Search by branch, commit, type, or PR…"+ value={searchQuery}+ onChange={setSearchQuery}+ size="small"+ className="flex-1 min-w-60"+ /><LemonButtonsize="small"type="secondary"@@ -173,9 +190,6 @@ export function VisualReviewRunsScene(): JSX.Element {loadCounts()}}loading={runsLoading}- // Push refresh away from the segmented filter; sitting flush- // next to the active-tab handle made it look like another tab.- className="ml-auto">Refresh</LemonButton>@@ -194,7 +208,7 @@ export function VisualReviewRunsScene(): JSX.Element {onForward: () => setPage(page + 1),}}nouns={['run', 'runs']}- emptyState={EMPTY_MESSAGES[activeTab]}+ emptyState={searchQuery.trim() ? `No runs match “${searchQuery.trim()}”.` : EMPTY_MESSAGES[activeTab]}onRow={(run) => ({onClick: () => router.actions.push(`/visual_review/runs/${run.id}`),className: 'cursor-pointer',diff --git a/products/visual_review/frontend/scenes/visualReviewRunsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunsSceneLogic.tsindex 192008c10e16..35a99552cf59 100644--- a/products/visual_review/frontend/scenes/visualReviewRunsSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunsSceneLogic.ts@@ -35,6 +35,7 @@ export const visualReviewRunsSceneLogic = kea<visualReviewRunsSceneLogicType>([actions({setActiveTab: (tab: ReviewState) => ({ tab }),setPage: (page: number) => ({ page }),+ setSearchQuery: (searchQuery: string) => ({ searchQuery }),}),reducers({@@ -49,21 +50,37 @@ export const visualReviewRunsSceneLogic = kea<visualReviewRunsSceneLogicType>([{setPage: (_, { page }) => page,setActiveTab: () => 1,+ // Any new search starts from the first page of results.+ setSearchQuery: () => 1,+ },+ ],+ searchQuery: [+ '',+ {+ setSearchQuery: (_, { searchQuery }) => searchQuery,},],}),- loaders(({ props, values }) => ({+ loaders(({ props, values, cache }) => ({runsResponse: [{ count: 0, results: [] } as PaginatedRunListApi,{loadRuns: async () => {const offset = (values.page - 1) * RUNS_PAGE_SIZE- return await visualReviewReposRunsList(String(values.currentProjectId), props.repoId, {+ const search = values.searchQuery.trim()+ // Tag each request; a slower, superseded one must not overwrite a newer one's results.+ const requestId = (cache.loadRunsSeq = (cache.loadRunsSeq ?? 0) + 1)+ const response = await visualReviewReposRunsList(String(values.currentProjectId), props.repoId, {review_state: values.activeTab,limit: RUNS_PAGE_SIZE,offset,+ ...(search ? { search } : {}),})+ if (requestId !== cache.loadRunsSeq) {+ return values.runsResponse+ }+ return response},},],@@ -108,6 +125,11 @@ export const visualReviewRunsSceneLogic = kea<visualReviewRunsSceneLogicType>([setPage: () => {actions.loadRuns()},+ setSearchQuery: async (_, breakpoint) => {+ // Debounce so we hit the API once the user pauses typing, not on every keystroke.+ await breakpoint(300)+ actions.loadRuns()+ },})),afterMount(({ actions }) => {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c4407a51b2a2..448817f32618 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22270,6 +22270,11 @@ export namespace Schemas {export interface Run {approved_by?: UserBasicInfo | null;+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of branch/run type, a commit SHA prefix, or an exact PR number) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`.+ *+ * * `exact` - exact+ * * `similar` - similar */+ readonly search_match_type: SearchMatchTypeEnum | null;id: string;repo_id: string;status: string;@@ -60788,6 +60793,10 @@ export namespace Schemas {* Filter by review state*/review_state?: string;+ /**+ * Free-text search over branch, commit SHA, run type, and PR number+ */+ search?: string;};export type VisualReviewReposSnapshotsListParams = {@@ -60826,6 +60835,10 @@ export namespace Schemas {* Filter by review state*/review_state?: string;+ /**+ * Free-text search over branch, commit SHA, run type, and PR number+ */+ search?: string;};export type VisualReviewRunsSnapshotHistoryListParams = {diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.tsindex b2823115b541..052075d2d7d8 100644--- a/services/mcp/src/generated/visual_review/api.ts+++ b/services/mcp/src/generated/visual_review/api.ts@@ -37,7 +37,7 @@ export const VisualReviewReposRetrieveParams = /* @__PURE__ */ zod.object({})/**- * List runs for the team, optionally filtered by review state, PR number, commit SHA, or branch.+ * List runs for the team, optionally filtered by review state, PR number, commit SHA, branch, or free-text search.*/export const VisualReviewRunsListParams = /* @__PURE__ */ zod.object({project_id: zod@@ -54,6 +54,7 @@ export const VisualReviewRunsListQueryParams = /* @__PURE__ */ zod.object({offset: zod.number().optional().describe('The initial index from which to return the results.'),pr_number: zod.number().optional().describe('Filter by GitHub PR number'),review_state: zod.string().optional().describe('Filter by review state'),+ search: zod.string().optional().describe('Free-text search over branch, commit SHA, run type, and PR number'),})/**diff --git a/services/mcp/src/tools/generated/visual_review.ts b/services/mcp/src/tools/generated/visual_review.tsindex dabcb1c8bb63..850fb45293bf 100644--- a/services/mcp/src/tools/generated/visual_review.ts+++ b/services/mcp/src/tools/generated/visual_review.ts@@ -153,6 +153,7 @@ const visualReviewRunsList = (): ToolBase<offset: params.offset,pr_number: params.pr_number,review_state: params.review_state,+ search: params.search,},})return await withPostHogUrl(