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(visual-review): add quarantine extend mode and source run tracking (#58992)

Julian Bez882033deb030
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 0e9644fe2e6b..182962e13b3b 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -216,6 +216,11 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:
"""
raw = logic.get_baselines_overview(repo_id)
+ # Hydrate UserBasicInfo for everyone who created an active quarantine so the
+ # overview can show "Quarantined by X" without a per-card fetch.
+ quarantine_user_ids = {q.created_by_id for q in raw.active_quarantines_by_key.values() if q.created_by_id}
+ quarantine_user_infos = _fetch_user_basic_infos(quarantine_user_ids)
+
entries: list[contracts.BaselineEntry] = []
for snapshot in raw.entries:
identifier = snapshot.identifier
@@ -226,6 +231,7 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:
# different run types is a different baseline.
key = (run.run_type, identifier)
metadata = snapshot.metadata or {}
+ active_quarantine = raw.active_quarantines_by_key.get(key)
entries.append(
contracts.BaselineEntry(
identifier=identifier,
@@ -236,10 +242,15 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:
height=artifact.height if artifact is not None else None,
tolerate_count_30d=raw.tolerate_30d_by_id.get(identifier, 0),
tolerate_count_90d=raw.tolerate_90d_by_id.get(identifier, 0),
- is_quarantined=key in raw.quarantined_ids,
+ is_quarantined=active_quarantine is not None,
last_run_at=run.completed_at or run.created_at,
baseline_change_count=raw.change_count_by_key.get(key, 0),
recent_drift_avg=raw.recent_drift_by_key.get(key),
+ quarantine=(
+ _to_baseline_quarantine_summary(active_quarantine, quarantine_user_infos)
+ if active_quarantine is not None
+ else None
+ ),
)
)
@@ -491,10 +502,32 @@ def _fetch_user_basic_infos(user_ids: set[int]) -> dict[int, contracts.UserBasic
return {u.id: _to_user_basic(u) for u in users}
+def _to_quarantine_source_run(run) -> contracts.QuarantineSourceRun | None:
+ if run is None:
+ return None
+ return contracts.QuarantineSourceRun(
+ id=run.id,
+ branch=run.branch,
+ commit_sha=run.commit_sha,
+ created_at=run.created_at,
+ pr_number=run.pr_number,
+ )
+
+
+def _quarantine_common_fields(
+ q, user_basic_infos: dict[int, contracts.UserBasicInfo] | None
+) -> tuple[contracts.UserBasicInfo | None, contracts.QuarantineSourceRun | None]:
+ """Fields shared by both quarantine DTOs. Callers must ensure `q.source_run`
+ is preloaded — list/overview use `select_related`, and the create path
+ attaches the resolved Run directly — so accessing it never lazy-loads."""
+ created_by = (user_basic_infos or {}).get(q.created_by_id) if q.created_by_id else None
+ return created_by, _to_quarantine_source_run(q.source_run)
+
+
def _to_quarantined_entry(
q, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None
) -> contracts.QuarantinedIdentifierEntry:
- created_by = (user_basic_infos or {}).get(q.created_by_id) if q.created_by_id else None
+ created_by, source_run = _quarantine_common_fields(q, user_basic_infos)
return contracts.QuarantinedIdentifierEntry(
id=q.id,
identifier=q.identifier,
@@ -504,6 +537,21 @@ def _to_quarantined_entry(
created_at=q.created_at,
updated_at=q.updated_at,
created_by=created_by,
+ source_run=source_run,
+ )
+
+
+def _to_baseline_quarantine_summary(
+ q, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None
+) -> contracts.BaselineQuarantineSummary:
+ created_by, source_run = _quarantine_common_fields(q, user_basic_infos)
+ return contracts.BaselineQuarantineSummary(
+ id=q.id,
+ reason=q.reason,
+ expires_at=q.expires_at,
+ created_at=q.created_at,
+ created_by=created_by,
+ source_run=source_run,
)
@@ -525,6 +573,7 @@ def quarantine_identifier(
run_type=run_type,
reason=input.reason,
expires_at=input.expires_at,
+ source_run_id=input.source_run_id,
user_id=user_id,
team_id=team_id,
)
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 4fcc9fd3b525..cdd6d180515f 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -271,6 +271,22 @@ class ToleratedHashEntry:
source_run_id: UUID | None
+@dataclass(frozen=True)
+class QuarantineSourceRun:
+ """Pointer back to the run whose failing snapshot prompted a quarantine.
+
+ Enough fields to render a "View the failing run" link without a second
+ fetch: the run id for routing, plus branch / commit / PR / time for the
+ one-liner the UI shows above the link.
+ """
+
+ id: UUID
+ branch: str
+ commit_sha: str
+ created_at: datetime
+ pr_number: int | None = None
+
+
@dataclass(frozen=True)
class QuarantinedIdentifierEntry:
"""A quarantined snapshot identifier."""
@@ -283,6 +299,10 @@ class QuarantinedIdentifierEntry:
created_at: datetime
updated_at: datetime
created_by: UserBasicInfo | None = None
+ # Set when the quarantine was created from the run scene (we knew which
+ # failing snapshot prompted it). None for quarantines opened from the
+ # snapshot history page or pre-dating this column.
+ source_run: QuarantineSourceRun | None = None
@dataclass(frozen=True)
@@ -292,6 +312,11 @@ class QuarantineInput:
identifier: str
reason: str
expires_at: datetime | None = None
+ # Optional pointer to the run whose failing snapshot prompted this
+ # quarantine. Passed by the run scene so reviewers can jump back to
+ # "what was wrong" later. Omitted when quarantining from the snapshot
+ # history page where no run is in context.
+ source_run_id: UUID | None = None
@dataclass(frozen=True)
@@ -361,6 +386,22 @@ BASELINE_OVERVIEW_MAX_ENTRIES = 5000
BASELINE_DRIFT_RECENT_RUN_COUNT = 10
+@dataclass(frozen=True)
+class BaselineQuarantineSummary:
+ """Compact view of the active quarantine attached to a baseline entry.
+
+ Embedded on `BaselineEntry` so the overview grid can render rich details
+ (reason, expiry, who, source run) without a per-card fetch.
+ """
+
+ id: UUID
+ reason: str
+ expires_at: datetime | None
+ created_at: datetime
+ created_by: UserBasicInfo | None = None
+ source_run: QuarantineSourceRun | None = None
+
+
@dataclass(frozen=True)
class BaselineEntry:
"""The current baseline state of a single snapshot identifier in a repo.
@@ -390,6 +431,9 @@ class BaselineEntry:
# non-zero diff. Drives the drift-severity sort. None when no signal in
# the window.
recent_drift_avg: float | None
+ # Populated when `is_quarantined` is true. Lets the overview grid show
+ # reason / expiry / who / source-run inline instead of just a yellow icon.
+ quarantine: BaselineQuarantineSummary | None = None
@dataclass(frozen=True)
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 3e92007e9f5b..2939202b6773 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -1961,7 +1961,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
entries=[],
tolerate_30d_by_id={},
tolerate_90d_by_id={},
- quarantined_ids=set(),
+ active_quarantines_by_key={},
change_count_by_key={},
recent_drift_by_key={},
totals_all=0,
@@ -2042,17 +2042,30 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
# 3b. Active quarantines for this repo, scoped to the universe identifiers
# AND the run_types they live on (quarantine is per (repo, run_type, id)).
- quarantined_pairs: set[tuple[str, str]] = set()
+ # We hydrate the full row (not just identity) so the overview can render
+ # reason / expiry / who / source-run inline without a per-card fetch.
+ # `select_related("source_run")` is a single JOIN, capped by
+ # `BASELINE_OVERVIEW_MAX_ENTRIES`. `Run.metadata` (JSONField) and
+ # `Run.error_message` (TextField) can be large and aren't needed by the
+ # summary — defer them to keep the response light.
+ active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier] = {}
if universe_identifiers:
- quarantined_pairs = {
- (run_type, identifier)
- for run_type, identifier in QuarantinedIdentifier.objects.filter(
+ for q in (
+ QuarantinedIdentifier.objects.filter(
repo_id=repo_id,
identifier__in=universe_identifiers,
)
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
- .values_list("run_type", "identifier")
- }
+ .select_related("source_run")
+ .defer("source_run__metadata", "source_run__error_message")
+ .order_by("-created_at")
+ ):
+ key = (q.run_type, q.identifier)
+ # Multiple active rows for the same key shouldn't happen — create
+ # auto-supersedes prior — but if it does, keep the latest (sorted
+ # above) and ignore the rest.
+ if key not in active_quarantines_by_key:
+ active_quarantines_by_key[key] = q
# 3c. Per-baseline stability signals: a lifetime baseline-flip count and a
# smoothed recent-drift average. Replaces a daily-bucket sparkline that
@@ -2166,7 +2179,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
)
frequent_ids = set(frequent_grouped)
- # `quarantined_pairs` was built from the truncated set above (per-entry
+ # `active_quarantines_by_key` was built from the truncated set above (per-entry
# attached). Re-query for the totals so they cover the full universe.
if truncated and full_universe_identifiers:
quarantined_id_count = (
@@ -2180,7 +2193,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
.count()
)
else:
- quarantined_id_count = len({identifier for _, identifier in quarantined_pairs})
+ quarantined_id_count = len({identifier for _, identifier in active_quarantines_by_key})
# by_run_type counts every entry in the universe. Aggregate query under
# truncation so it doesn't undercount; in-memory Counter when not truncated
@@ -2199,7 +2212,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
entries=universe,
tolerate_30d_by_id=tolerate_30d_by_id,
tolerate_90d_by_id=tolerate_90d_by_id,
- quarantined_ids=quarantined_pairs,
+ active_quarantines_by_key=active_quarantines_by_key,
change_count_by_key=change_count_by_key,
recent_drift_by_key=recent_drift_by_key,
totals_all=totals_all,
@@ -2222,7 +2235,11 @@ class _BaselineOverviewRaw:
entries: list[RunSnapshot]
tolerate_30d_by_id: dict[str, int]
tolerate_90d_by_id: dict[str, int]
- quarantined_ids: set[tuple[str, str]]
+ # Latest active QuarantinedIdentifier (with `source_run` preloaded) for each
+ # `(run_type, identifier)` in the universe — lets the facade build the rich
+ # quarantine summary embedded on each BaselineEntry. Membership doubles as
+ # the "is_quarantined" signal — no separate set needed.
+ active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier]
# Stability signals keyed by `(run_type, identifier)` because the same
# identifier in different run types is a different baseline; merging would
# bleed storybook stability into playwright stability.
@@ -2303,7 +2320,16 @@ def get_tolerated_hashes_for_identifier(repo_id: UUID, identifier: str) -> list[
def list_quarantined_identifiers(
repo_id: UUID, team_id: int, identifier: str | None = None, run_type: str | None = None
) -> list[QuarantinedIdentifier]:
- qs = QuarantinedIdentifier.objects.using(WRITER_DB).filter(repo_id=repo_id, team_id=team_id)
+ qs = (
+ QuarantinedIdentifier.objects.using(WRITER_DB)
+ .filter(repo_id=repo_id, team_id=team_id)
+ # Preload `source_run` so the facade can render the "what was wrong"
+ # link without an extra fetch per row. `Run.metadata` (JSONField) and
+ # `Run.error_message` (TextField) can be large and aren't needed for
+ # the summary — defer to keep response payloads tight.
+ .select_related("source_run")
+ .defer("source_run__metadata", "source_run__error_message")
+ )
if run_type:
qs = qs.filter(run_type=run_type)
if identifier:
@@ -2323,9 +2349,18 @@ def quarantine_identifier(
user_id: int,
team_id: int,
expires_at: datetime | None = None,
+ source_run_id: UUID | None = None,
) -> QuarantinedIdentifier:
get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
now = timezone.now()
+ # Resolve the source run inside the team scope so a malicious caller can't
+ # attach a quarantine to an unrelated run. Silently drop on mismatch — the
+ # quarantine itself still wins; we just lose the "what was wrong" pointer.
+ # We fetch (not just .exists()) so the facade can serialize source_run
+ # without a lazy-load on the freshly-created row.
+ source_run: Run | None = None
+ if source_run_id is not None:
+ source_run = Run.objects.using(WRITER_DB).filter(id=source_run_id, repo_id=repo_id, team_id=team_id).first()
QuarantinedIdentifier.objects.using(WRITER_DB).select_for_update().filter(
repo_id=repo_id,
identifier=identifier,
@@ -2340,6 +2375,7 @@ def quarantine_identifier(
reason=reason,
expires_at=expires_at,
created_by_id=user_id,
+ source_run=source_run,
)
diff --git a/products/visual_review/backend/migrations/0012_quarantined_identifier_source_run.py b/products/visual_review/backend/migrations/0012_quarantined_identifier_source_run.py
new file mode 100644
index 000000000000..9e4acfdd9208
--- /dev/null
+++ b/products/visual_review/backend/migrations/0012_quarantined_identifier_source_run.py
@@ -0,0 +1,28 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ """Track which run prompted a quarantine so reviewers can jump back to
+ the failing snapshot. Mirrors `ToleratedHash.source_run`. Nullable so
+ historical entries and quarantines created without run context (e.g.
+ from the snapshot history page) still validate.
+ """
+
+ dependencies = [
+ ("visual_review", "0011_alter_artifact_managers_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="quarantinedidentifier",
+ name="source_run",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="originated_quarantines",
+ to="visual_review.run",
+ ),
+ ),
+ ]
diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txt
index 57987126c9d7..f86df01092ba 100644
--- a/products/visual_review/backend/migrations/max_migration.txt
+++ b/products/visual_review/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_alter_artifact_managers_and_more
+0012_quarantined_identifier_source_run
diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.py
index 56a7a89c93ae..7091e55e983c 100644
--- a/products/visual_review/backend/models.py
+++ b/products/visual_review/backend/models.py
@@ -375,6 +375,18 @@ class QuarantinedIdentifier(ProductTeamModel):
expires_at = models.DateTimeField(null=True, blank=True)
created_by_id = models.BigIntegerField(null=True, blank=True)
+ # The run whose failing snapshot prompted the quarantine. Nullable because
+ # quarantines can also be created from the snapshot history page where no
+ # specific failing run is in context, and entries pre-dating this column
+ # have no source. SET_NULL so a deleted/archived Run doesn't cascade-drop
+ # the quarantine — the audit trail (reason, who, when) still matters.
+ source_run = models.ForeignKey(
+ Run,
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="originated_quarantines",
+ )
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index cebd559e1d83..3d3dc5d36643 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -16,6 +16,7 @@ from ..facade.contracts import (
AutoApproveResult,
BaselineEntry,
BaselineOverview,
+ BaselineQuarantineSummary,
BaselineTotals,
ClusterSummary,
CreateRepoInput,
@@ -24,6 +25,7 @@ from ..facade.contracts import (
DiffCluster,
QuarantinedIdentifierEntry,
QuarantineInput,
+ QuarantineSourceRun,
RecomputeResult,
Repo,
Run,
@@ -172,16 +174,42 @@ class MarkToleratedInputSerializer(serializers.Serializer):
snapshot_id = serializers.UUIDField()
+class QuarantineSourceRunSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = QuarantineSourceRun
+
+
class QuarantinedIdentifierEntrySerializer(DataclassSerializer):
created_by = UserBasicInfoSerializer(allow_null=True, required=False)
+ source_run = QuarantineSourceRunSerializer(
+ allow_null=True,
+ required=False,
+ help_text="Run whose failing snapshot prompted this quarantine. Null when quarantine was created without run context.",
+ )
class Meta:
dataclass = QuarantinedIdentifierEntry
+class BaselineQuarantineSummarySerializer(DataclassSerializer):
+ created_by = UserBasicInfoSerializer(allow_null=True, required=False)
+ source_run = QuarantineSourceRunSerializer(allow_null=True, required=False)
+
+ class Meta:
+ dataclass = BaselineQuarantineSummary
+
+
class QuarantineInputSerializer(DataclassSerializer):
- identifier = serializers.CharField(max_length=512)
- reason = serializers.CharField(max_length=255)
+ identifier = serializers.CharField(max_length=512, help_text="Snapshot identifier to quarantine.")
+ reason = serializers.CharField(max_length=255, help_text="Why this snapshot is being quarantined.")
+ source_run_id = serializers.UUIDField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Optional pointer to the run whose failing snapshot prompted this quarantine — "
+ "used to surface a 'view the failing run' link later."
+ ),
+ )
class Meta:
dataclass = QuarantineInput
@@ -197,6 +225,12 @@ class CreateRepoInputSerializer(DataclassSerializer):
class BaselineEntrySerializer(DataclassSerializer):
+ quarantine = BaselineQuarantineSummarySerializer(
+ allow_null=True,
+ required=False,
+ help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",
+ )
+
class Meta:
dataclass = BaselineEntry
diff --git a/products/visual_review/backend/tests/test_baselines.py b/products/visual_review/backend/tests/test_baselines.py
index 9854c307bc22..1e7da2debfbf 100644
--- a/products/visual_review/backend/tests/test_baselines.py
+++ b/products/visual_review/backend/tests/test_baselines.py
@@ -335,6 +335,63 @@ class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
assert by_id == {"active": True, "expired": False, "future": True}
assert result.totals.currently_quarantined == 2
+ def test_baseline_entry_embeds_quarantine_summary(self):
+ """Active quarantines surface their reason/expiry/who/source-run inline
+ on `BaselineEntry.quarantine` so the overview grid doesn't need a
+ per-card fetch. Non-quarantined entries get None."""
+ run = _mk_run(self.repo)
+ _mk_snapshot(run, identifier="flake")
+ _mk_snapshot(run, identifier="clean")
+
+ expires = timezone.now() + timedelta(days=14)
+ QuarantinedIdentifier.objects.create(
+ repo=self.repo,
+ team_id=self.team.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="Known flaky",
+ expires_at=expires,
+ created_by_id=self.user.id,
+ source_run=run,
+ )
+
+ result = vr_api.get_baselines_overview(self.repo.id)
+ by_id = {e.identifier: e for e in result.entries}
+
+ # Clean entry: no embedded summary.
+ assert by_id["clean"].is_quarantined is False
+ assert by_id["clean"].quarantine is None
+
+ # Quarantined entry: full summary surfaces.
+ q = by_id["flake"].quarantine
+ assert q is not None
+ assert q.reason == "Known flaky"
+ assert q.expires_at == expires
+ assert q.created_by is not None
+ assert q.created_by.id == self.user.id
+ assert q.source_run is not None
+ assert q.source_run.id == run.id
+ assert q.source_run.commit_sha == run.commit_sha
+ assert q.source_run.branch == run.branch
+
+ def test_baseline_entry_quarantine_without_source_run(self):
+ """Quarantines opened from the snapshot history page (no run context)
+ have `source_run=None`; the summary should still surface, just without
+ the source-run pointer."""
+ run = _mk_run(self.repo)
+ _mk_snapshot(run, identifier="orphan")
+ QuarantinedIdentifier.objects.create(
+ repo=self.repo,
+ team_id=self.team.id,
+ identifier="orphan",
+ run_type=RunType.STORYBOOK,
+ reason="manual",
+ )
+ result = vr_api.get_baselines_overview(self.repo.id)
+ entry = next(e for e in result.entries if e.identifier == "orphan")
+ assert entry.quarantine is not None
+ assert entry.quarantine.source_run is None
+
def test_baseline_change_count_lifetime(self):
# Three master runs over time. The middle one classifies the snapshot
# as CHANGED (the moment the YAML baseline moved), the others are
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index 2900a0049a0c..192167710fa1 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -1352,6 +1352,87 @@ class TestQuarantineStamping:
assert processed.new_count == 1 # only Card-new
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestQuarantineIdentifier:
+ """Coverage for `logic.quarantine_identifier` — especially the new
+ `source_run_id` behavior (valid run is stored, foreign run is dropped)."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return logic.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/test-source-run")
+
+ def _mk_run(self, repo: Repo, branch: str = "main") -> Run:
+ return Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ run_type=RunType.STORYBOOK,
+ branch=branch,
+ commit_sha="abc123",
+ status=RunStatus.COMPLETED,
+ completed_at=timezone.now(),
+ )
+
+ def test_stores_valid_source_run(self, repo, team, user):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ run = self._mk_run(repo)
+ entry = logic.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ source_run_id=run.id,
+ )
+ # Returned row points at the source run …
+ assert entry.source_run_id == run.id
+ # … and the persisted row agrees.
+ persisted = QuarantinedIdentifier.objects.get(id=entry.id)
+ assert persisted.source_run_id == run.id
+
+ def test_drops_source_run_from_another_team(self, repo, team, user):
+ """A `source_run_id` from a run that doesn't belong to this team/repo
+ is silently dropped — the quarantine still gets created, just without
+ the cross-team pointer."""
+ from posthog.models.team.team import Team
+
+ # Sibling team in the same org with its own repo + run.
+ other_team = Team.objects.create(organization=team.organization, name="other")
+ other_repo = logic.create_repo(team_id=other_team.id, repo_external_id=12121, repo_full_name="org/other-repo")
+ foreign_run = Run.objects.create(
+ team_id=other_team.id,
+ repo=other_repo,
+ run_type=RunType.STORYBOOK,
+ branch="main",
+ commit_sha="xyz789",
+ status=RunStatus.COMPLETED,
+ completed_at=timezone.now(),
+ )
+
+ entry = logic.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ source_run_id=foreign_run.id,
+ )
+ assert entry.source_run_id is None
+
+ def test_omitting_source_run_leaves_it_null(self, repo, team, user):
+ entry = logic.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ )
+ assert entry.source_run_id is None
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
class TestRecomputeRun:
@pytest.fixture
diff --git a/products/visual_review/frontend/components/QuarantineAction.tsx b/products/visual_review/frontend/components/QuarantineAction.tsx
index 22317d8eff3c..15eaac920d97 100644
--- a/products/visual_review/frontend/components/QuarantineAction.tsx
+++ b/products/visual_review/frontend/components/QuarantineAction.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { LemonButton, LemonCheckbox, LemonInput, LemonModal } from '@posthog/lemon-ui'
@@ -14,6 +14,40 @@ const SUGGESTED_REASONS = [
const DEFAULT_EXPIRY_DAYS = 30
+const COPY = {
+ create: {
+ triggerLabel: 'Quarantine this identifier',
+ modalTitle: 'Quarantine snapshot',
+ confirmLabel: 'Quarantine',
+ dataAttrOpen: 'visual-review-quarantine-open',
+ dataAttrConfirm: 'visual-review-quarantine-confirm',
+ expiresLabel: 'Expires',
+ description:
+ 'Quarantined identifiers appear as quarantined immediately and are excluded from gating when future runs finalize — including pending runs on other branches. Snapshots are still captured and diffed, just not gated on.',
+ },
+ extend: {
+ triggerLabel: 'Extend',
+ modalTitle: 'Extend quarantine',
+ confirmLabel: 'Extend',
+ dataAttrOpen: 'visual-review-quarantine-extend-open',
+ dataAttrConfirm: 'visual-review-quarantine-extend-confirm',
+ expiresLabel: 'New expiry',
+ description:
+ 'Extending creates a new quarantine entry that supersedes the current one — the audit trail keeps both. The reason can be edited; the expiry will be bumped to the date you pick below.',
+ },
+} as const
+
+// Bump from the current expiry, not "now", when extending. Falls back to a
+// fresh +30d window if the prior entry already expired.
+function computeDefaultExpiry(initialExpiresAt: string | null | undefined): dayjs.Dayjs {
+ if (initialExpiresAt) {
+ const prior = dayjs(initialExpiresAt)
+ const base = prior.isAfter(dayjs()) ? prior : dayjs()
+ return base.add(DEFAULT_EXPIRY_DAYS, 'day')
+ }
+ return dayjs().add(DEFAULT_EXPIRY_DAYS, 'day')
+}
+
/**
* Identifiers carry an optional `--light` / `--dark` theme suffix.
* When the user quarantines one variant, they almost always want
@@ -33,9 +67,27 @@ export function getThemeSibling(identifier: string): string | null {
interface QuarantineActionProps {
identifier: string
- onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null) => void
+ onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void
/** Override the trigger button label. Defaults to "Quarantine this identifier". */
triggerLabel?: string
+ /**
+ * "extend" mode reuses this modal to bump an active quarantine's expiry — the
+ * backend create endpoint auto-supersedes the prior active row, so extending
+ * is just a re-create with a pre-populated reason and a future date. The
+ * sibling-quarantine checkbox is hidden because the sibling has its own
+ * quarantine row already.
+ */
+ mode?: 'create' | 'extend'
+ /** Pre-fill the reason field. Useful when extending. */
+ initialReason?: string
+ /** Pre-fill the expiry field. Useful when extending (default: +30d from now). */
+ initialExpiresAt?: string | null
+ /**
+ * The run whose failing snapshot prompted this quarantine. Set when extending
+ * (carries forward the original source) or when creating from the run scene.
+ * Forwarded to the parent via `onQuarantine` so the backend can store it.
+ */
+ sourceRunId?: string | null
}
/**
@@ -43,39 +95,60 @@ interface QuarantineActionProps {
* sidebar) and the snapshot history scene (per identifier banner). Local
* state for the modal — the parent owns the API call via `onQuarantine`.
*/
-export function QuarantineAction({ identifier, onQuarantine, triggerLabel }: QuarantineActionProps): JSX.Element {
+export function QuarantineAction({
+ identifier,
+ onQuarantine,
+ triggerLabel,
+ mode = 'create',
+ initialReason,
+ initialExpiresAt,
+ sourceRunId,
+}: QuarantineActionProps): JSX.Element {
+ const isExtend = mode === 'extend'
+ const copy = COPY[mode]
+
const [isOpen, setIsOpen] = useState(false)
- const [reason, setReason] = useState('')
+ const [reason, setReason] = useState(initialReason ?? '')
const [includeSibling, setIncludeSibling] = useState(true)
- const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))
+ const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(computeDefaultExpiry(initialExpiresAt))
+
+ // Re-prefill if the parent swaps which entry we're acting on mid-session.
+ // Skip while the modal is open so a background refresh of the underlying
+ // entry can't silently trample the user's in-progress edits.
+ useEffect(() => {
+ if (isOpen) {
+ return
+ }
+ setReason(initialReason ?? '')
+ setExpiresAt(computeDefaultExpiry(initialExpiresAt))
+ }, [initialReason, initialExpiresAt, isOpen])
const sibling = getThemeSibling(identifier)
const handleSubmit = (): void => {
const identifiers = [identifier]
- if (sibling && includeSibling) {
+ // Extending only affects the entry the user opened — siblings have
+ // their own quarantine and their own expiry to manage.
+ if (!isExtend && sibling && includeSibling) {
identifiers.push(sibling)
}
- onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null)
+ onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null, sourceRunId ?? null)
setIsOpen(false)
- setReason('')
- setExpiresAt(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))
+ if (!isExtend) {
+ setReason('')
+ setExpiresAt(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))
+ }
}
return (
<div>
- <LemonButton
- type="secondary"
- size="small"
- onClick={() => setIsOpen(true)}
- data-attr="visual-review-quarantine-open"
- >
- {triggerLabel ?? 'Quarantine this identifier'}
+ <LemonButton type="secondary" size="small" onClick={() => setIsOpen(true)} data-attr={copy.dataAttrOpen}>
+ {triggerLabel ?? copy.triggerLabel}
</LemonButton>
<LemonModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
- title="Quarantine snapshot"
+ title={copy.modalTitle}
footer={
<>
<LemonButton
@@ -89,24 +162,20 @@ export function QuarantineAction({ identifier, onQuarantine, triggerLabel }: Qua
type="primary"
disabledReason={!reason.trim() ? 'Reason is required' : undefined}
onClick={handleSubmit}
- data-attr="visual-review-quarantine-confirm"
+ data-attr={copy.dataAttrConfirm}
>
- Quarantine
+ {copy.confirmLabel}
</LemonButton>
</>
}
>
<div className="space-y-4">
- <p className="text-sm text-muted">
- Quarantined identifiers appear as quarantined immediately and are excluded from gating when
- future runs finalize — including pending runs on other branches. Snapshots are still captured
- and diffed, just not gated on.
- </p>
+ <p className="text-sm text-muted">{copy.description}</p>
<div>
<label className="text-sm font-medium mb-1 block">Identifier</label>
<div className="font-mono text-xs text-muted bg-bg-3000 rounded px-2 py-1.5">{identifier}</div>
- {sibling && (
+ {!isExtend && sibling && (
<LemonCheckbox
className="mt-1.5"
label={
@@ -143,7 +212,7 @@ export function QuarantineAction({ identifier, onQuarantine, triggerLabel }: Qua
</div>
<div>
- <label className="text-sm font-medium mb-1 block">Expires</label>
+ <label className="text-sm font-medium mb-1 block">{copy.expiresLabel}</label>
<LemonCalendarSelectInput
value={expiresAt}
onChange={setExpiresAt}
diff --git a/products/visual_review/frontend/components/SnapshotCard.tsx b/products/visual_review/frontend/components/SnapshotCard.tsx
index 0b7c54e68d82..13fb893d9f87 100644
--- a/products/visual_review/frontend/components/SnapshotCard.tsx
+++ b/products/visual_review/frontend/components/SnapshotCard.tsx
@@ -1,10 +1,13 @@
+import { useMemo } from 'react'
+
import { IconFlag, IconPulse, IconWarning } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
+import { dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { urls } from 'scenes/urls'
-import type { BaselineEntryApi } from '../generated/api.schemas'
+import type { BaselineEntryApi, BaselineQuarantineSummaryApi } from '../generated/api.schemas'
import { parseArea, parseTheme } from '../lib/parseIdentifier'
// Drift is shown as a percentage with one decimal — anything less is sub-pixel
@@ -16,6 +19,54 @@ function formatDriftPct(value: number): string {
return `${value.toFixed(1)}%`
}
+// Compact "12d left" / "today" / "expired" hint for the card. The exact date
+// is in the tooltip so the strip stays readable inside a 220px-wide thumb.
+function formatExpiryShort(expiresAt: string | null | undefined): string {
+ if (!expiresAt) {
+ return 'no expiry'
+ }
+ const now = dayjs()
+ const expiry = dayjs(expiresAt)
+ if (expiry.isBefore(now)) {
+ return 'expired'
+ }
+ const days = expiry.diff(now, 'day')
+ if (days === 0) {
+ return 'today'
+ }
+ if (days < 30) {
+ return `${days}d left`
+ }
+ return `${Math.round(days / 7)}w left`
+}
+
+function buildQuarantineTooltip(quarantine: BaselineQuarantineSummaryApi): JSX.Element {
+ // One <div> per line so the tooltip renders multi-line — the default
+ // Tooltip container has `white-space: normal`, which would collapse `\n`.
+ const lines: string[] = []
+ if (quarantine.reason) {
+ lines.push(quarantine.reason)
+ }
+ lines.push(
+ quarantine.expires_at ? `Expires ${dayjs(quarantine.expires_at).format('MMM D, YYYY')}` : 'No expiry set'
+ )
+ if (quarantine.created_by) {
+ const name = quarantine.created_by.first_name || quarantine.created_by.email
+ lines.push(`By ${name} · ${dayjs(quarantine.created_at).fromNow()}`)
+ }
+ if (quarantine.source_run) {
+ const prSuffix = quarantine.source_run.pr_number ? ` · PR #${quarantine.source_run.pr_number}` : ''
+ lines.push(`From ${quarantine.source_run.commit_sha.slice(0, 8)} on ${quarantine.source_run.branch}${prSuffix}`)
+ }
+ return (
+ <>
+ {lines.map((line, i) => (
+ <div key={i}>{line}</div>
+ ))}
+ </>
+ )
+}
+
// Anything below this rounds to "0.0%" via the formatter above, which would
// render a misleading "no drift" chip on a card that does have drift. Hide
// the chip entirely below this floor; the data is still in the API response
@@ -57,13 +108,25 @@ export function SnapshotCard({
const href = urls.visualReviewSnapshotHistory(repoId, entry.run_type, entry.identifier)
const hasMeta = driftVisible || tolerateCount > 0 || entry.baseline_change_count > 0
+ const quarantine = entry.quarantine ?? null
+ // Yellow ring (not a 1px border) so the card pulls the eye in a grid
+ // of hundreds — quarantine means "system stopped trusting this".
+ const cardClassName = entry.is_quarantined
+ ? 'border border-warning rounded bg-bg-light overflow-hidden flex flex-col text-default hover:border-warning-dark transition-colors shadow-[0_0_0_1px_var(--warning)]'
+ : 'border border-border rounded bg-bg-light overflow-hidden flex flex-col text-default hover:border-primary transition-colors'
+
+ // Tooltip body is only consumed on hover — compute once per render of
+ // a quarantined card, not on every mouse-enter, and avoid building it
+ // at all for non-quarantined cards (most cards in a typical grid).
+ const quarantineTooltip = useMemo(() => (quarantine ? buildQuarantineTooltip(quarantine) : null), [quarantine])
+
return (
<Link
to={href}
// Without an explicit border-color, Tailwind's `border` falls back
// to `currentColor` — and Link sets `currentColor` to the primary
// orange. That painted every card with an orange frame.
- className="border border-border rounded bg-bg-light overflow-hidden flex flex-col text-default hover:border-primary transition-colors"
+ className={cardClassName}
data-attr="visual-review-snapshot-card"
>
<div
@@ -87,19 +150,32 @@ export function SnapshotCard({
) : (
<span className="text-muted text-xs my-auto">No thumbnail</span>
)}
- {/* Corner is reserved for severity-only signals: quarantine
- means "broken, system stopped trusting this". Activity
- metrics (tolerate / drift / baseline-change) live in the
- meta row below where they can be compared on the same axis. */}
- {entry.is_quarantined && (
- <div className="absolute top-1.5 right-1.5">
- <Tooltip title="Currently quarantined — excluded from gating">
- <span className="inline-flex items-center justify-center h-5 min-w-5 px-1.5 rounded-full text-white text-[10px] font-semibold leading-none bg-warning">
- <IconWarning className="w-3 h-3" />
- </span>
+ {/* Strip surfaces reason + expiry inline so the overview is
+ assessable at a glance — not just a color and icon. The
+ fallback corner badge handles old API responses that
+ don't yet return the summary. */}
+ {entry.is_quarantined &&
+ (quarantine ? (
+ <Tooltip title={quarantineTooltip}>
+ <div className="absolute top-0 left-0 right-0 bg-warning text-white flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-semibold leading-tight">
+ <IconWarning className="w-3 h-3 shrink-0" />
+ <span className="truncate min-w-0 flex-1" title={quarantine.reason}>
+ {quarantine.reason || 'Quarantined'}
+ </span>
+ <span className="shrink-0 opacity-90 tabular-nums">
+ {formatExpiryShort(quarantine.expires_at)}
+ </span>
+ </div>
</Tooltip>
- </div>
- )}
+ ) : (
+ <div className="absolute top-1.5 right-1.5">
+ <Tooltip title="Currently quarantined — excluded from gating">
+ <span className="inline-flex items-center justify-center h-5 min-w-5 px-1.5 rounded-full text-white text-[10px] font-semibold leading-none bg-warning">
+ <IconWarning className="w-3 h-3" />
+ </span>
+ </Tooltip>
+ </div>
+ ))}
</div>
<div className="p-2 flex flex-col gap-1 min-w-0">
@@ -152,6 +228,22 @@ export function SnapshotCard({
</div>
)}
</div>
+ {quarantine && (
+ <div className="flex items-center justify-between gap-2 text-[10px] text-muted truncate">
+ <span className="truncate">
+ {quarantine.created_by
+ ? `by ${quarantine.created_by.first_name || quarantine.created_by.email}`
+ : 'quarantined'}
+ </span>
+ {quarantine.source_run && (
+ <span className="font-mono shrink-0" title={`From run ${quarantine.source_run.commit_sha}`}>
+ {quarantine.source_run.pr_number
+ ? `PR #${quarantine.source_run.pr_number}`
+ : quarantine.source_run.commit_sha.slice(0, 7)}
+ </span>
+ )}
+ </div>
+ )}
</div>
</Link>
)
diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
index 75a1ccc024e4..a16b6ad8a60c 100644
--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
@@ -48,7 +48,7 @@ interface SnapshotDiffViewerProps {
isApproving?: boolean
onMarkTolerated?: () => void
quarantineEntry?: QuarantinedIdentifierEntryApi | null
- onQuarantine?: (reason: string, identifiers: string[], expiresAt: string | null) => void
+ onQuarantine?: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void
onUnquarantine?: () => void
commitSha?: string
prNumber?: number | null
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 0848ec80c2d0..73145d2ec21b 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -46,7 +46,34 @@ export interface PatchedUpdateRepoRequestInputApi {
enable_pr_comments?: boolean | null
}
+export interface UserBasicInfoApi {
+ id: number
+ first_name: string
+ email: string
+}
+
+export interface QuarantineSourceRunApi {
+ id: string
+ branch: string
+ commit_sha: string
+ created_at: string
+ /** @nullable */
+ pr_number?: number | null
+}
+
+export interface BaselineQuarantineSummaryApi {
+ created_by?: UserBasicInfoApi | null
+ source_run?: QuarantineSourceRunApi | null
+ id: string
+ reason: string
+ /** @nullable */
+ expires_at: string | null
+ created_at: string
+}
+
export interface BaselineEntryApi {
+ /** Active quarantine details when `is_quarantined` is true. Null otherwise. */
+ quarantine?: BaselineQuarantineSummaryApi | null
identifier: string
run_type: string
/** @nullable */
@@ -83,14 +110,10 @@ export interface BaselineOverviewApi {
generated_at: string
}
-export interface UserBasicInfoApi {
- id: number
- first_name: string
- email: string
-}
-
export interface QuarantinedIdentifierEntryApi {
created_by?: UserBasicInfoApi | null
+ /** Run whose failing snapshot prompted this quarantine. Null when quarantine was created without run context. */
+ source_run?: QuarantineSourceRunApi | null
id: string
identifier: string
run_type: string
@@ -111,10 +134,21 @@ export interface PaginatedQuarantinedIdentifierEntryListApi {
}
export interface QuarantineInputApi {
- /** @maxLength 512 */
+ /**
+ * Snapshot identifier to quarantine.
+ * @maxLength 512
+ */
identifier: string
- /** @maxLength 255 */
+ /**
+ * Why this snapshot is being quarantined.
+ * @maxLength 255
+ */
reason: string
+ /**
+ * Optional pointer to the run whose failing snapshot prompted this quarantine — used to surface a 'view the failing run' link later.
+ * @nullable
+ */
+ source_run_id?: string | null
/** @nullable */
expires_at?: string | null
}
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index 9ab1d69462aa..dcbc2e9a4956 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -33,8 +33,20 @@ export const visualReviewReposQuarantineCreateBodyIdentifierMax = 512
export const visualReviewReposQuarantineCreateBodyReasonMax = 255
export const VisualReviewReposQuarantineCreateBody = /* @__PURE__ */ zod.object({
- identifier: zod.string().max(visualReviewReposQuarantineCreateBodyIdentifierMax),
- reason: zod.string().max(visualReviewReposQuarantineCreateBodyReasonMax),
+ identifier: zod
+ .string()
+ .max(visualReviewReposQuarantineCreateBodyIdentifierMax)
+ .describe('Snapshot identifier to quarantine.'),
+ reason: zod
+ .string()
+ .max(visualReviewReposQuarantineCreateBodyReasonMax)
+ .describe('Why this snapshot is being quarantined.'),
+ source_run_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ "Optional pointer to the run whose failing snapshot prompted this quarantine — used to surface a 'view the failing run' link later."
+ ),
expires_at: zod.iso.datetime({ offset: true }).nullish(),
})
@@ -46,8 +58,20 @@ export const visualReviewReposQuarantineExpireCreateBodyIdentifierMax = 512
export const visualReviewReposQuarantineExpireCreateBodyReasonMax = 255
export const VisualReviewReposQuarantineExpireCreateBody = /* @__PURE__ */ zod.object({
- identifier: zod.string().max(visualReviewReposQuarantineExpireCreateBodyIdentifierMax),
- reason: zod.string().max(visualReviewReposQuarantineExpireCreateBodyReasonMax),
+ identifier: zod
+ .string()
+ .max(visualReviewReposQuarantineExpireCreateBodyIdentifierMax)
+ .describe('Snapshot identifier to quarantine.'),
+ reason: zod
+ .string()
+ .max(visualReviewReposQuarantineExpireCreateBodyReasonMax)
+ .describe('Why this snapshot is being quarantined.'),
+ source_run_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ "Optional pointer to the run whose failing snapshot prompted this quarantine — used to surface a 'view the failing run' link later."
+ ),
expires_at: zod.iso.datetime({ offset: true }).nullish(),
})
diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
index 2b4d8cb4691e..0e501c5c81cb 100644
--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
@@ -518,8 +518,8 @@ export function VisualReviewRunScene(): JSX.Element {
(!q.expires_at || new Date(q.expires_at) > new Date())
) ?? null
}
- onQuarantine={(reason, identifiers, expiresAt) =>
- quarantineSnapshot(reason, identifiers, expiresAt)
+ onQuarantine={(reason, identifiers, expiresAt, sourceRunId) =>
+ quarantineSnapshot(reason, identifiers, expiresAt, sourceRunId)
}
onUnquarantine={() => unquarantineSnapshot(selectedSnapshot)}
commitSha={run.commit_sha}
diff --git a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx
index 849b1e31b87f..477aae487f95 100644
--- a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { LemonBanner, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
@@ -192,11 +192,12 @@ function QuarantineSection({
label?: string | null
quarantineEntry: QuarantinedIdentifierEntryApi | null
isQuarantined: boolean
- onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null) => void
+ onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void
onUnquarantine: () => void
}): JSX.Element {
if (isQuarantined && quarantineEntry) {
const expires = quarantineEntry.expires_at ? new Date(quarantineEntry.expires_at) : null
+ const sourceRun = quarantineEntry.source_run ?? null
const openConfirmation = (): void => {
LemonDialog.open({
title: `Unquarantine ${label ? `(${label})` : 'this identifier'}?`,
@@ -214,28 +215,78 @@ function QuarantineSection({
return (
<LemonBanner
type="warning"
- action={{
- children: 'Unquarantine',
- status: 'danger',
- 'data-attr': 'visual-review-history-unquarantine',
- onClick: openConfirmation,
- }}
+ // No `action` here — extend lives inline below so the user can
+ // see "what was wrong" first (the source-run link) before
+ // choosing to extend or unquarantine.
>
- <div className="text-sm flex flex-wrap items-center gap-x-2 gap-y-1">
- <span className="font-semibold">Quarantined{label && ` (${label})`}</span>
- <span>— {quarantineEntry.reason || 'no reason given'}</span>
- {expires && (
- <>
+ <div className="text-sm flex flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="font-semibold">Quarantined{label && ` (${label})`}</span>
+ <span>— {quarantineEntry.reason || 'no reason given'}</span>
+ {expires && (
+ <>
+ <span aria-hidden>·</span>
+ <span>
+ until {expires.toLocaleDateString()}{' '}
+ <span className="text-muted">({dayjs(expires).fromNow()})</span>
+ </span>
+ </>
+ )}
+ {!expires && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="text-muted">no expiry set</span>
+ </>
+ )}
+ {quarantineEntry.created_by && (
+ <>
+ <span aria-hidden>·</span>
+ <ProfilePicture user={quarantineEntry.created_by} size="xs" showName />
+ </>
+ )}
+ </div>
+ {sourceRun && (
+ <div className="text-xs text-muted flex flex-wrap items-center gap-x-2 gap-y-0.5">
+ <span>Originally failed on</span>
+ <Link
+ to={urls.visualReviewRun(sourceRun.id)}
+ className="font-mono text-default"
+ data-attr="visual-review-quarantine-source-run"
+ >
+ {sourceRun.commit_sha.slice(0, 8)}
+ </Link>
<span aria-hidden>·</span>
- <span>until {expires.toLocaleDateString()}</span>
- </>
- )}
- {quarantineEntry.created_by && (
- <>
+ <span className="font-mono">{sourceRun.branch}</span>
+ {sourceRun.pr_number && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="font-mono">PR #{sourceRun.pr_number}</span>
+ </>
+ )}
<span aria-hidden>·</span>
- <ProfilePicture user={quarantineEntry.created_by} size="xs" showName />
- </>
+ <TZLabel time={sourceRun.created_at} />
+ </div>
)}
+ <div className="flex items-center gap-2 pt-1">
+ <QuarantineAction
+ identifier={identifier}
+ onQuarantine={onQuarantine}
+ mode="extend"
+ triggerLabel={label ? `Extend (${label})` : 'Extend quarantine'}
+ initialReason={quarantineEntry.reason}
+ initialExpiresAt={quarantineEntry.expires_at}
+ sourceRunId={sourceRun?.id ?? null}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ status="danger"
+ onClick={openConfirmation}
+ data-attr="visual-review-history-unquarantine"
+ >
+ Unquarantine
+ </LemonButton>
+ </div>
</div>
</LemonBanner>
)
diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
index 7ea068705e53..b6411079898c 100644
--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
@@ -48,10 +48,16 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
approveSnapshotSuccess: true,
approveSnapshotFailure: true,
markAsTolerated: (snapshot: SnapshotApi) => ({ snapshot }),
- quarantineSnapshot: (reason: string, identifiers: string[], expiresAt: string | null) => ({
+ quarantineSnapshot: (
+ reason: string,
+ identifiers: string[],
+ expiresAt: string | null,
+ sourceRunId: string | null = null
+ ) => ({
reason,
identifiers,
expiresAt,
+ sourceRunId,
}),
unquarantineSnapshot: (snapshot: SnapshotApi) => ({ snapshot }),
recomputeRun: true,
@@ -369,11 +375,16 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
lemonToast.error(e?.detail || e?.message || 'Failed to mark as tolerated')
}
},
- quarantineSnapshot: async ({ reason, identifiers, expiresAt }) => {
+ quarantineSnapshot: async ({ reason, identifiers, expiresAt, sourceRunId }) => {
const { run } = values
if (!run) {
return
}
+ // Default to the current run when the caller didn't supply a source
+ // (the diff viewer doesn't have one for new quarantines). Extending
+ // an existing quarantine passes through the prior source so the
+ // "what was wrong" link survives across renewals.
+ const effectiveSourceRunId = sourceRunId ?? run.id
try {
await Promise.all(
identifiers.map((identifier) =>
@@ -381,6 +392,7 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
identifier,
reason,
expires_at: expiresAt,
+ source_run_id: effectiveSourceRunId,
})
)
)
diff --git a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts
index 5a3a809138d5..116814800f79 100644
--- a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts
@@ -52,10 +52,16 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis
values: [teamLogic, ['currentProjectId']],
})),
actions({
- quarantineIdentifier: (reason: string, identifiers: string[], expiresAt: string | null) => ({
+ quarantineIdentifier: (
+ reason: string,
+ identifiers: string[],
+ expiresAt: string | null,
+ sourceRunId: string | null = null
+ ) => ({
reason,
identifiers,
expiresAt,
+ sourceRunId,
}),
unquarantineIdentifier: true,
unquarantineSibling: true,
@@ -206,7 +212,7 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis
],
}),
listeners(({ actions, values, props }) => ({
- quarantineIdentifier: async ({ reason, identifiers, expiresAt }) => {
+ quarantineIdentifier: async ({ reason, identifiers, expiresAt, sourceRunId }) => {
try {
await Promise.all(
identifiers.map((identifier) =>
@@ -214,7 +220,14 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis
String(values.currentProjectId),
props.repoId,
props.runType,
- { identifier, reason, expires_at: expiresAt }
+ {
+ identifier,
+ reason,
+ expires_at: expiresAt,
+ // Forward the prior source when extending — keeps the "view
+ // the failing run" link intact across renewals.
+ source_run_id: sourceRunId,
+ }
)
)
)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 28b1f9124b23..4a91b1b27f44 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5026,7 +5026,28 @@ export namespace Schemas {
Zmw: 'ZMW',
} as const;
+ export interface QuarantineSourceRun {
+ id: string;
+ branch: string;
+ commit_sha: string;
+ created_at: string;
+ /** @nullable */
+ pr_number?: number | null;
+ }
+
+ export interface BaselineQuarantineSummary {
+ created_by?: UserBasicInfo | null;
+ source_run?: QuarantineSourceRun | null;
+ id: string;
+ reason: string;
+ /** @nullable */
+ expires_at: string | null;
+ created_at: string;
+ }
+
export interface BaselineEntry {
+ /** Active quarantine details when `is_quarantined` is true. Null otherwise. */
+ quarantine?: BaselineQuarantineSummary | null;
identifier: string;
run_type: string;
/** @nullable */
@@ -22695,6 +22716,8 @@ export namespace Schemas {
export interface QuarantinedIdentifierEntry {
created_by?: UserBasicInfo | null;
+ /** Run whose failing snapshot prompted this quarantine. Null when quarantine was created without run context. */
+ source_run?: QuarantineSourceRun | null;
id: string;
identifier: string;
run_type: string;
@@ -32045,10 +32068,21 @@ export namespace Schemas {
} as const;
export interface QuarantineInput {
- /** @maxLength 512 */
+ /**
+ * Snapshot identifier to quarantine.
+ * @maxLength 512
+ */
identifier: string;
- /** @maxLength 255 */
+ /**
+ * Why this snapshot is being quarantined.
+ * @maxLength 255
+ */
reason: string;
+ /**
+ * Optional pointer to the run whose failing snapshot prompted this quarantine — used to surface a 'view the failing run' link later.
+ * @nullable
+ */
+ source_run_id?: string | null;
/** @nullable */
expires_at?: string | null;
}