: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): notify the owning team in slack on quarantine (#109094)
Julian Bez020ff3b0b46b
diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex 6ac290cc7079..b2d6269612ee 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -113,6 +113,18 @@ A repository that owes nothing posts nothing.`--mode preview`, the default, prints and logs the plain text behind every message without posting.`--mode live` posts.+### Quarantine notice++The quarantine dialog has a "Notify the owning team in Slack" switch, on by default.+When it is on, the first identifier of the request carries `notify_owners: true`, so the theme variants of one story send one notice.+The API field `notify_owners` defaults to false, so scripts and agents that quarantine in bulk post nothing unless they ask.+A Celery task, `notify quarantine owners`, runs after the row commits.+It finds the owner with the same lookup as the flakiness page, and posts to the channel the digest uses, so a team that opted out of the digest gets no notice either.+The message names the person who quarantined and shows the story, the reason, the expiry, and a button to the snapshot.+It works for Storybook runs only, and it is best effort: a story no team owns, a project with no Slack integration, or a refused post sends nothing, and nothing retries.+The task expires after 15 minutes in the queue, so a backed-up queue drops the notice instead of posting it late.+The notice does not replace the weekly digest's expiry reminder: the digest lists a dated quarantine in the week before it runs out, and never lists one with no expiry.+## The flow### Single-command flow (`vr submit`)diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 88fa5c484186..74c9e240b40a 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -856,6 +856,7 @@ def quarantine_identifier(source=source,user_id=user_id,team_id=team_id,+ notify_owners=input.notify_owners,)user_basic_infos = _fetch_user_basic_infos({user_id})return _to_quarantined_entry(entry, user_basic_infos)diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex d93862bf4762..b8a6b0e9d22f 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -447,6 +447,7 @@ class QuarantineInput:# "what was wrong" later. Omitted when quarantining from the snapshot# history page where no run is in context.source_run_id: UUID | None = None+ notify_owners: bool = False@dataclass(frozen=True)diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.pyindex b3cb6e202c40..829623440bcd 100644--- a/products/visual_review/backend/logic/debt_digest.py+++ b/products/visual_review/backend/logic/debt_digest.py@@ -48,12 +48,10 @@ from django.conf import settingsfrom django.utils import timezoneimport structlog-from owners_yaml.resolver import Purpose, team_channel-from owners_yaml.schema import Producer, TeamEntry+from owners_yaml.schema import TeamEntryfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priority-from posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user import Userfrom posthog.ownership.github_files import fetcher_for_teamfrom posthog.ownership.paths import UNOWNED_TEAM, PathOwnership, resolve_path_owners@@ -63,18 +61,12 @@ from posthog.slack.channels import (MAX_SECTION_CHARS,MAX_TEXT_CHARS,SlackButton,- SlackChannel,- SlackPostRefused,actions_block,clip_text,context_block,divider_block,- fetch_channel_map,fields_block,- find_channel,header_block,- post_message,- post_with_join,section_block,)from posthog.slack.formatting import escape_slack_mrkdwn@@ -83,16 +75,11 @@ from posthog.utils import human_list, pluralizefrom ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYSfrom ..facade.enums import RunTypefrom ..models import QuarantinedIdentifier, Repo, Run-from . import quarantine, run_queries, story_index, toleration+from . import quarantine, run_queries, story_index, team_channels, toleration+from .team_channels import SlackMessagelogger = structlog.get_logger(__name__)-# The digest is automation, so it asks the registry where automation posts rather than where the-# team's people are. That falls back to the people channel when a team never separates the two.-_CHANNEL_PURPOSE: Purpose = "notifications"-# Named so a team can keep this digest out of its channel while other bots keep posting there.-_PRODUCER: Producer = "visual_review"-# Whose digest carries the items no team owns. The people who built the product can read a story# name and find who to ask; nobody else can. Routed like any other team, so there is no second# delivery path to keep working.@@ -228,14 +215,6 @@ class RepoDigests:maintainers: MaintainersDigest | None-@frozen-class SlackMessage:- """One post: the blocks Slack renders, and the plain text it shows wherever they do not."""-- blocks: list[dict[str, Any]]- text: str--@frozenclass MessagePart:"""One block, and the plain line that stands in for it in the message's fallback text."""@@ -263,14 +242,6 @@ class Post:triage_count: int-@frozen-class Delivery:- """Where one team's digest goes."""-- channel_id: str- channel_name: str--def _snapshot_url(repo: Repo, run_type: str, identifier: str) -> str:return (f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/repos/{repo.id}"@@ -296,12 +267,12 @@ def _quarantined_story_url(repo: Repo, story: str) -> str:return url if len(url) <= MAX_BUTTON_URL_CHARS else _repo_flakiness_url(repo)-def _snapshot_button(repo: Repo, item: DebtItem, text: str) -> SlackButton:- """The item's button, pointing at the repo's list when the snapshot URL is too long for Slack.+def snapshot_button(repo: Repo, run_type: str, identifier: str, text: str) -> SlackButton:+ """The snapshot's button, pointing at the repo's list when the snapshot URL is too long for Slack.Same reason as `_linked_line` below: an encoded identifier can outgrow the cap on its own."""- url = _snapshot_url(repo, item.run_type, item.identifier)+ url = _snapshot_url(repo, run_type, identifier)return SlackButton(text=text, url=url if len(url) <= MAX_BUTTON_URL_CHARS else _repo_snapshots_url(repo))@@ -349,9 +320,10 @@ def _author_name(entry: QuarantinedIdentifier, authors: dict[int, str]) -> str:return escape_slack_mrkdwn(authors.get(entry.created_by_id or 0, "someone"))-def _quarantine_facts(entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:+def quarantine_facts(entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:+ expiry = f"Expires *{_expiry_word(entry.expires_at, now)}*" if entry.expires_at is not None else "No expiry"return (- f"Expires *{_expiry_word(entry.expires_at, now)}* · opened by {_author_name(entry, authors)}\n"+ f"{expiry} · opened by {_author_name(entry, authors)}\n"f'_"{escape_slack_mrkdwn(clip_text(entry.reason, _MAX_REASON_CHARS))}"_')@@ -380,7 +352,7 @@ def _pileup_line(repo: Repo, run_type: str, identifier: str, count: int) -> str:return _linked_line(repo, body, run_type, identifier)-def _display_names(user_ids: set[int]) -> dict[int, str]:+def display_names(user_ids: set[int]) -> dict[int, str]:if not user_ids:return {}return {@@ -433,7 +405,7 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:run_types = {entry.run_type for entry in expiring} | {key.run_type for key in piled_up}sources = _attribution_sources(repo, run_types, newest_run_by_type)- authors = _display_names({entry.created_by_id for entry in expiring if entry.created_by_id})+ authors = display_names({entry.created_by_id for entry in expiring if entry.created_by_id})return RepoDebt(expiring_quarantines=[@@ -442,7 +414,7 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:run_type=entry.run_type,attribution=_attribution(sources, entry.run_type, entry.identifier),line=_quarantine_line(repo, entry, authors, now),- facts=_quarantine_facts(entry, authors, now),+ facts=quarantine_facts(entry, authors, now),)for entry in expiring],@@ -617,7 +589,9 @@ def _item_text(entry: ListedEntry, extra: str = "") -> str:def _item_part(repo: Repo, item: DebtItem, button_text: str, line: str | None = None) -> MessagePart:return MessagePart(- block=section_block(_item_text(_single_entry(item)), _snapshot_button(repo, item, button_text)),+ block=section_block(+ _item_text(_single_entry(item)), snapshot_button(repo, item.run_type, item.identifier, button_text)+ ),line=item.line if line is None else line,)@@ -785,27 +759,6 @@ def maintainers_messages(repo: Repo, digest: MaintainersDigest) -> list[SlackMesreturn _split_into_messages(groups, _unavailable_parts(unavailable), preamble)-def resolve_channel(- team_slug: str, registry: Mapping[str, TeamEntry], channels_by_name: Mapping[str, SlackChannel]-) -> Delivery | None:- """The team's own notifications channel, or None when it opted out or the name does not resolve."""- answer = team_channel(team_slug, registry, _CHANNEL_PURPOSE, _PRODUCER)- if answer.channel is None:- logger.info("visual_review.debt_digest_team_opted_out", team_slug=team_slug)- return None- name = answer.channel.removeprefix("#")- match = find_channel(channels_by_name, name, allow_shared=False)- if match.channel is None:- logger.info(- "visual_review.debt_digest_channel_unusable",- team_slug=team_slug,- channel_name=name,- reason=match.reason,- )- return None- return Delivery(channel_id=match.channel.channel_id, channel_name=name)--def plan_posts(repo: Repo, digests: RepoDigests, now: datetime) -> list[Post]:"""Every message this run sends, in the order it sends them.@@ -873,16 +826,15 @@ def send_debt_digest(repo: Repo, mode: str) -> list[str]:if mode == MODE_PREVIEW:return [_preview_one(repo, post, ownership.registry) for post in posts]- integration = Integration.objects.filter(team_id=repo.team_id, kind="slack").first()- if integration is None:- logger.info("visual_review.debt_digest_no_slack_integration", team_id=repo.team_id)+ workspace = team_channels.open_workspace(repo.team_id)+ if workspace is None:return []- channels_by_name = fetch_channel_map(integration, source="visual_review")rendered: list[str] = []for post in posts:try:- rendered.append(_send_one(repo, post, ownership.registry, channels_by_name, integration))+ if team_channels.post_to_team(workspace, post.team_slug, ownership.registry, post.lead, post.replies):+ rendered.append(_post_text(post))except Exception as e:# One team's Slack failure must not cost the rest of the repo its reminder, and there is# nothing to retry against: next Monday's run sends the same items again.@@ -904,7 +856,7 @@ def _preview_one(repo: Repo, post: Post, registry: Mapping[str, TeamEntry]) -> srendered = _post_text(post)# Preview holds no channel map, because fetching one needs the integration it deliberately does# not touch. So the routing here only ever reports the team's own opt-out.- resolved = resolve_channel(post.team_slug, registry, {})+ resolved = team_channels.resolve_channel(post.team_slug, registry, {})logger.info("visual_review.debt_digest_preview",repo_id=str(repo.id),@@ -917,33 +869,6 @@ def _preview_one(repo: Repo, post: Post, registry: Mapping[str, TeamEntry]) -> sreturn rendered-def _send_one(- repo: Repo,- post: Post,- registry: Mapping[str, TeamEntry],- channels_by_name: Mapping[str, SlackChannel],- integration: Integration,-) -> str:- delivery = resolve_channel(post.team_slug, registry, channels_by_name)- if delivery is None:- return ""-- slack = SlackIntegration(integration, source="visual_review")- try:- thread_ts = post_with_join(- slack, delivery.channel_id, post.lead.blocks, post.lead.text, channel_name=delivery.channel_name- )- except SlackPostRefused as e:- logger.warning("visual_review.debt_digest_post_refused", team_slug=post.team_slug, error=str(e))- return ""- # Without a parent to hang them on, the item blocks land in the channel as separate top-level- # posts, which is the noise the thread exists to remove.- if thread_ts is not None:- for reply in post.replies:- post_message(slack, delivery.channel_id, reply.blocks, reply.text, thread_ts=thread_ts)- return _post_text(post)--def repos_in_scope() -> list[Repo]:"""Every repo that opted in, oldest first.diff --git a/products/visual_review/backend/logic/owners.py b/products/visual_review/backend/logic/owners.pyindex 1a3ffc72c231..802068ae7055 100644--- a/products/visual_review/backend/logic/owners.py+++ b/products/visual_review/backend/logic/owners.py@@ -3,7 +3,9 @@from collections.abc import Iterable, Mappingimport structlog+from owners_yaml.schema import TeamEntry+from posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.ownership.github_files import fetcher_for_teamfrom posthog.ownership.paths import UNOWNED_TEAM, resolve_path_owners@@ -21,22 +23,30 @@ logger = structlog.get_logger(__name__)_MAX_OWNED_PATHS = 2_000-def owner_teams(- repo: Repo, keys: Iterable[SnapshotKey], newest_run_by_type: Mapping[str, Run]-) -> dict[SnapshotKey, str]:- """The owning team of each Storybook snapshot whose story file is known.+@frozen+class SnapshotOwners:+ """The owning team of each snapshot whose story file is known, and the registry that routes to it."""++ team_by_key: dict[SnapshotKey, str]+ path_by_key: dict[SnapshotKey, str]+ registry: Mapping[str, TeamEntry]+++def snapshot_owners(repo: Repo, keys: Iterable[SnapshotKey], newest_run_by_type: Mapping[str, Run]) -> SnapshotOwners:+ """The owning team and story file of each Storybook snapshot whose story file is known.A key is left out when there is no team to name: the run type has no story index, the newestdefault-branch run sent none, the story is not in it, or the ownership files could not be read.`UNOWNED_TEAM` means the file is known and no ownership entry covers it."""+ nobody = SnapshotOwners(team_by_key={}, path_by_key={}, registry={})storybook_keys = [key for key in keys if key.run_type == RunType.STORYBOOK]if not storybook_keys:- return {}+ return nobodyindex = story_index.latest_story_index(repo, newest_run_by_type)if isinstance(index, str):- return {}+ return nobodypath_by_key: dict[SnapshotKey, str] = {}for key in storybook_keys:@@ -44,20 +54,32 @@ def owner_teams(if path is not None:path_by_key[key] = pathif not path_by_key:- return {}+ return nobodypaths = sorted(set(path_by_key.values()))if len(paths) > _MAX_OWNED_PATHS:logger.warning("visual_review.owner_teams_too_many_paths", repo_id=str(repo.id), paths=len(paths))- return {}+ return nobodyownership = resolve_path_owners(repo.repo_full_name,paths,- # A person is waiting on the snapshot list, so the reads run on the interactive lane.+ # A person is waiting on the snapshot list or just asked for a notice, so the reads run on the+ # interactive lane.files=fetcher_for_team(repo.team_id, repo.repo_full_name, priority=Priority.NORMAL),)if not ownership.resolved:logger.info("visual_review.owner_teams_unresolved", repo_id=str(repo.id))- return {}- return {key: ownership.team_by_path.get(path, UNOWNED_TEAM) for key, path in path_by_key.items()}+ return nobody+ return SnapshotOwners(+ team_by_key={key: ownership.team_by_path.get(path, UNOWNED_TEAM) for key, path in path_by_key.items()},+ path_by_key=path_by_key,+ registry=ownership.registry,+ )+++def owner_teams(+ repo: Repo, keys: Iterable[SnapshotKey], newest_run_by_type: Mapping[str, Run]+) -> dict[SnapshotKey, str]:+ """The owning team of each Storybook snapshot whose story file is known. See `snapshot_owners`."""+ return snapshot_owners(repo, keys, newest_run_by_type).team_by_keydiff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.pyindex acc70828ce1d..e4dfccd4f7be 100644--- a/products/visual_review/backend/logic/quarantine.py+++ b/products/visual_review/backend/logic/quarantine.py@@ -102,6 +102,7 @@ def quarantine_identifier(expires_at: datetime | None = None,source_run_id: UUID | None = None,source: ActorType = ActorType.HUMAN,+ notify_owners: bool = False,) -> QuarantinedIdentifier:repos.get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by teamnow = timezone.now()@@ -128,7 +129,7 @@ def quarantine_identifier(run_type=run_type,team_id=team_id,).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).update(expires_at=now)- return QuarantinedIdentifier.objects.using(WRITER_DB).create(+ entry = QuarantinedIdentifier.objects.using(WRITER_DB).create(repo_id=repo_id,identifier=identifier,run_type=run_type,@@ -139,6 +140,21 @@ def quarantine_identifier(source_run=source_run,source=source,)+ if notify_owners:+ from ..tasks.tasks import ( # noqa: PLC0415 — avoids the logic/tasks circular import+ QUARANTINE_NOTICE_EXPIRY_SECONDS,+ notify_quarantine_owners,+ )++ entry_id = str(entry.id)+ transaction.on_commit(+ lambda: notify_quarantine_owners.apply_async(+ args=(team_id, entry_id), expires=QUARANTINE_NOTICE_EXPIRY_SECONDS+ ),+ using=WRITER_DB,+ robust=True,+ )+ return entrydef unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:diff --git a/products/visual_review/backend/logic/quarantine_notice.py b/products/visual_review/backend/logic/quarantine_notice.pynew file mode 100644index 000000000000..7ea7589796e6--- /dev/null+++ b/products/visual_review/backend/logic/quarantine_notice.py@@ -0,0 +1,97 @@+"""Tell the team that owns a story, in its Slack channel, that somebody just quarantined it.++The person who quarantines asks for this, so the owning team hears about it at once instead of in+the weekly debt digest. It reuses the digest's pieces: the same owner lookup, the same channel, and+the same rendering of a quarantine. A story no team owns gets no notice, because the message says+"owned by you" and the maintainers already see unowned items in the digest.++Best effort. A quarantine never fails because its notice could not be sent, and nothing retries a+notice.+"""++from __future__ import annotations++from uuid import UUID++from django.utils import timezone++import structlog++from posthog.ownership.paths import UNOWNED_TEAM+from posthog.slack.channels import clip_text, section_block+from posthog.slack.formatting import escape_slack_mrkdwn++from ..db import WRITER_DB+from ..facade.enums import ActorType+from ..models import QuarantinedIdentifier, Repo+from . import owners, run_queries, story_index, team_channels+from .debt_digest import display_names, quarantine_facts, snapshot_button+from .run_queries import SnapshotKey+from .team_channels import SlackMessage++logger = structlog.get_logger(__name__)++_MAX_IDENTIFIER_CHARS = 160+++def build_message(repo: Repo, entry: QuarantinedIdentifier, actor: str, source_path: str) -> SlackMessage:+ by = f"{actor} (using an AI agent)" if entry.source == ActorType.AGENT else actor+ lead = f"*{escape_slack_mrkdwn(by)}* quarantined a story owned by you. Please check."+ # The story without its theme: one notice covers every theme variant quarantined with it.+ story = escape_slack_mrkdwn(clip_text(story_index.split_theme(entry.identifier).rest, _MAX_IDENTIFIER_CHARS))+ facts = quarantine_facts(entry, {entry.created_by_id or 0: actor}, timezone.now())+ return SlackMessage(+ blocks=[+ section_block(lead),+ section_block(+ f"*{story}* {escape_slack_mrkdwn(entry.run_type)}\n{facts}",+ snapshot_button(repo, entry.run_type, entry.identifier, "Open snapshot"),+ ),+ # The path comes from the repository, so it renders as plain text: in mrkdwn a backtick in it+ # would close the code span and let Slack auto-link whatever follows.+ {+ "type": "context",+ "elements": [+ {+ "type": "plain_text",+ "text": clip_text(f"{repo.repo_full_name} · {source_path}", 2000),+ "emoji": False,+ }+ ],+ },+ ],+ text=f"{lead} {story}",+ )+++def send_quarantine_notice(entry_id: UUID, team_id: int) -> bool:+ """Post one quarantine to the channel of the team that owns its story. False when nothing was posted."""+ entry = (+ QuarantinedIdentifier.objects.using(WRITER_DB)+ .select_related("repo")+ .filter(id=entry_id, team_id=team_id)+ .first()+ )+ if entry is None or (entry.expires_at is not None and entry.expires_at <= timezone.now()):+ logger.info("visual_review.quarantine_notice_inactive", entry_id=str(entry_id), team_id=team_id)+ return False+ repo = entry.repo++ key = SnapshotKey(run_type=entry.run_type, identifier=entry.identifier)+ found = owners.snapshot_owners(+ repo, [key], run_queries.newest_run_by_run_type(run_queries.latest_default_branch_runs(repo.id))+ )+ team_slug = found.team_by_key.get(key)+ if team_slug is None or team_slug == UNOWNED_TEAM:+ logger.info("visual_review.quarantine_notice_no_owner", entry_id=str(entry_id), team_id=team_id)+ return False++ workspace = team_channels.open_workspace(repo.team_id)+ if workspace is None:+ return False+ author_id = entry.created_by_id or 0+ actor = display_names({author_id} if author_id else set()).get(author_id, "Someone")+ message = build_message(repo, entry, actor, found.path_by_key[key])+ posted = team_channels.post_to_team(workspace, team_slug, found.registry, message)+ logger.info("visual_review.quarantine_notice", entry_id=str(entry_id), team_slug=team_slug, posted=posted)+ return posteddiff --git a/products/visual_review/backend/logic/team_channels.py b/products/visual_review/backend/logic/team_channels.pynew file mode 100644index 000000000000..9a65fdfd0163--- /dev/null+++ b/products/visual_review/backend/logic/team_channels.py@@ -0,0 +1,134 @@+"""Posting to a team's Slack channel, routed through the repository's ownership registry."""++from __future__ import annotations++from collections.abc import Mapping, Sequence+from typing import Any++from django.core.cache import cache++import structlog+from owners_yaml.resolver import Purpose, team_channel+from owners_yaml.schema import Producer, TeamEntry++from posthog.dataclasses import frozen+from posthog.models.integration import Integration, SlackIntegration+from posthog.slack.channels import (+ SlackChannel,+ SlackPostRefused,+ fetch_channel_map,+ find_channel,+ is_shared_channel,+ post_message,+ post_with_join,+)++logger = structlog.get_logger(__name__)++# Visual review posts are automation, so they ask the registry where automation posts rather than+# where the team's people are. That falls back to the people channel when a team never separates the two.+_CHANNEL_PURPOSE: Purpose = "notifications"+# Named so a team can keep visual review out of its channel while other bots keep posting there.+_PRODUCER: Producer = "visual_review"++# Listing channels walks every page of a rate-limited Slack endpoint, and a rate-limited walk returns+# a partial map. Quarantine notices can arrive in bursts, so one listing serves them all for a while.+# The cached shared flag can be stale, so post_to_team checks the channel again before each post.+_CHANNEL_MAP_TTL_SECONDS = 10 * 60+++@frozen+class SlackMessage:+ """One post: the blocks Slack renders, and the plain text it shows wherever they do not."""++ blocks: list[dict[str, Any]]+ text: str+++@frozen+class Delivery:+ """Where one team's post goes."""++ channel_id: str+ channel_name: str+++@frozen+class Workspace:+ """The project's Slack connection, and its channels by name. Read once and shared across teams."""++ integration: Integration+ channels_by_name: Mapping[str, SlackChannel]+++def open_workspace(team_id: int) -> Workspace | None:+ """The project's Slack workspace, or None when the project has no Slack integration."""+ integration = Integration.objects.filter(team_id=team_id, kind="slack").first()+ if integration is None:+ logger.info("visual_review.team_post_no_slack_integration", team_id=team_id)+ return None+ cache_key = f"visual_review_slack_channels:{integration.id}"+ channels_by_name = cache.get(cache_key)+ if channels_by_name is None:+ channels_by_name = fetch_channel_map(integration, source="visual_review")+ cache.set(cache_key, channels_by_name, timeout=_CHANNEL_MAP_TTL_SECONDS)+ return Workspace(integration=integration, channels_by_name=channels_by_name)+++def resolve_channel(+ team_slug: str, registry: Mapping[str, TeamEntry], channels_by_name: Mapping[str, SlackChannel]+) -> Delivery | None:+ """The team's own notifications channel, or None when it opted out or the name does not resolve."""+ answer = team_channel(team_slug, registry, _CHANNEL_PURPOSE, _PRODUCER)+ if answer.channel is None:+ logger.info("visual_review.team_channel_opted_out", team_slug=team_slug)+ return None+ name = answer.channel.removeprefix("#")+ match = find_channel(channels_by_name, name, allow_shared=False)+ if match.channel is None:+ logger.info("visual_review.team_channel_unusable", team_slug=team_slug, channel_name=name, reason=match.reason)+ return None+ return Delivery(channel_id=match.channel.channel_id, channel_name=name)+++def _is_still_internal(slack: SlackIntegration, channel_id: str) -> bool:+ """Whether the channel is still unshared right now. Fails closed when Slack cannot say."""+ try:+ channel = slack.client.conversations_info(channel=channel_id).get("channel")+ except Exception as e:+ logger.warning("visual_review.team_channel_info_failed", channel_id=channel_id, error=str(e))+ return False+ if not channel:+ return False+ return not is_shared_channel(channel)+++def post_to_team(+ workspace: Workspace,+ team_slug: str,+ registry: Mapping[str, TeamEntry],+ lead: SlackMessage,+ replies: Sequence[SlackMessage] = (),+) -> bool:+ """Post the lead to the team's channel and the replies in its thread. False when nothing was posted."""+ delivery = resolve_channel(team_slug, registry, workspace.channels_by_name)+ if delivery is None:+ return False++ slack = SlackIntegration(workspace.integration, source="visual_review")+ if not _is_still_internal(slack, delivery.channel_id):+ logger.info("visual_review.team_channel_now_shared", team_slug=team_slug, channel_name=delivery.channel_name)+ return False+ try:+ thread_ts = post_with_join(+ slack, delivery.channel_id, lead.blocks, lead.text, channel_name=delivery.channel_name+ )+ except SlackPostRefused as e:+ logger.warning("visual_review.team_post_refused", team_slug=team_slug, error=str(e))+ return False+ # Without a parent to hang them on, the replies land in the channel as separate top-level posts,+ # which is the noise the thread exists to remove.+ if thread_ts is not None:+ for reply in replies:+ post_message(slack, delivery.channel_id, reply.blocks, reply.text, thread_ts=thread_ts)+ return Truediff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex e583eb3d1674..bc48c7f26bbf 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -371,6 +371,15 @@ class QuarantineInputSerializer(DataclassSerializer):"used to surface a 'view the failing run' link later."),)+ notify_owners = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Post the quarantine to the Slack channel of the team that owns the story, naming the user "+ "who quarantined it. Only Storybook snapshots have an owning team. Best effort: skipped when "+ "the story has no owning team or the project has no Slack integration."+ ),+ )class Meta:dataclass = QuarantineInputdiff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex 72ee74586786..a58f91d6c87c 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -34,6 +34,8 @@ _DEBT_DIGEST_LOCK_SECONDS = 900# A child task worth running is a child task worth running today. A worker draining a backlog past# this drops it, and the next morning's run recomputes what is still owed._DEBT_DIGEST_EXPIRY_SECONDS = 60 * 60+# A notice that sat in a backed-up queue no longer reports something that just happened.+QUARANTINE_NOTICE_EXPIRY_SECONDS = 15 * 60# Past the sweep budget in logic/retention.py and below the grace period a deploy gives a busy# worker. A sweep that overruns its budget then fails with a logged error. Without the limit the@@ -241,3 +243,19 @@ def send_visual_review_debt_digest(team_id: int, repo_id: str) -> None:returndebt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE)+++@shared_task(+ name="products.visual_review.backend.tasks.notify_quarantine_owners",+ ignore_result=True,+)+@with_team_scope()+def notify_quarantine_owners(team_id: int, entry_id: str) -> None:+ """Tell the team that owns a just-quarantined story, in its Slack channel."""+ from ..logic import quarantine_notice # noqa: PLC0415 — avoids the logic/tasks circular import++ try:+ quarantine_notice.send_quarantine_notice(UUID(entry_id), team_id)+ except Exception:+ # Nothing retries a notice: a late one no longer reports something that just happened.+ logger.warning("visual_review.quarantine_notice_failed", entry_id=entry_id, team_id=team_id, exc_info=True)diff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.pyindex 53839c5cca39..ae2ee1af5be7 100644--- a/products/visual_review/backend/tests/logic/test_debt_digest.py+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py@@ -21,7 +21,15 @@ from products.visual_review.backend.facade.contracts import (SnapshotManifestItem,)from products.visual_review.backend.facade.enums import RunType-from products.visual_review.backend.logic import artifact_store, debt_digest, quarantine, repos, runs, story_index+from products.visual_review.backend.logic import (+ artifact_store,+ debt_digest,+ quarantine,+ repos,+ runs,+ story_index,+ team_channels,+)from products.visual_review.backend.models import Run, ToleratedHashfrom products.visual_review.backend.tests.conftest import PRODUCT_DATABASES@@ -334,7 +342,7 @@ class TestRendering:repo = _repo()line = debt_digest._quarantine_line(repo, entry, {}, _MONDAY)- facts = debt_digest._quarantine_facts(entry, {}, _MONDAY)+ facts = debt_digest.quarantine_facts(entry, {}, _MONDAY)item = _item(_PLACED, identifier="Button<!channel>", line=line, facts=facts)digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=[item], variant_pileups=[])rendered = str(debt_digest.thread_messages(repo, digest, _MONDAY)[0])@@ -356,7 +364,7 @@ class TestRendering:# A weekday name seven days out names the day the reader is reading on, so that one dates itself.entry = MagicMock(reason="flaky", expires_at=_MONDAY + expires_in, created_by_id=None)- assert debt_digest._quarantine_facts(entry, {}, _MONDAY).startswith(f"Expires *{expected}*")+ assert debt_digest.quarantine_facts(entry, {}, _MONDAY).startswith(f"Expires *{expected}*")def test_links_to_the_snapshot_page_with_encoded_segments(self) -> None:line = debt_digest._pileup_line(_repo(), "storybook", "scenes/Button--dark", 4)@@ -385,7 +393,7 @@ class TestRendering:created_by_id=None,)line = debt_digest._quarantine_line(repo, entry, {}, _MONDAY)- item = _item(_PLACED, identifier=identifier, line=line, facts=debt_digest._quarantine_facts(entry, {}, _MONDAY))+ item = _item(_PLACED, identifier=identifier, line=line, facts=debt_digest.quarantine_facts(entry, {}, _MONDAY))digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=[item] * 2, variant_pileups=[])messages = debt_digest.thread_messages(repo, digest, _MONDAY)@@ -441,17 +449,17 @@ class TestRouting:def test_a_team_that_opted_out_is_skipped(self) -> None:registry = {"team-devex": TeamEntry(notifications={"visual_review": False})}- assert debt_digest.resolve_channel("team-devex", registry, self._CHANNELS) is None+ assert team_channels.resolve_channel("team-devex", registry, self._CHANNELS) is Nonedef test_a_shared_channel_is_refused(self) -> None:# A name match onto a shared channel would send an internal reminder out of the workspace.- assert debt_digest.resolve_channel("team-shared", {}, self._CHANNELS) is None+ assert team_channels.resolve_channel("team-shared", {}, self._CHANNELS) is None@pytest.mark.parametrize("mode", ["preveiw", "shadow", ""])def test_an_unknown_mode_evaluates_nothing_and_posts_nothing(self, mode: str) -> None:with (patch("products.visual_review.backend.logic.debt_digest.collect_debt") as collect,- patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ patch("products.visual_review.backend.logic.team_channels.post_with_join") as post,):assert debt_digest.send_debt_digest(MagicMock(), mode=mode) == []@@ -660,8 +668,8 @@ class TestCollectAndSend:"products.visual_review.backend.logic.debt_digest.resolve_path_owners",return_value=_ownership({_SOURCE_PATH: "team-devex", _PRODUCT_PATH: "team-devex"}),),- patch("products.visual_review.backend.logic.debt_digest.fetch_channel_map") as channel_map,- patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ patch("products.visual_review.backend.logic.team_channels.fetch_channel_map") as channel_map,+ patch("products.visual_review.backend.logic.team_channels.post_with_join") as post,):rendered = debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_PREVIEW)@@ -684,7 +692,7 @@ class TestCollectAndSend:with (_with_index(_INDEX),patch("products.visual_review.backend.logic.debt_digest.resolve_path_owners", return_value=blind),- patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ patch("products.visual_review.backend.logic.team_channels.post_with_join") as post,):assert debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE) == []@@ -701,22 +709,23 @@ class TestCollectAndSend:"products.visual_review.backend.logic.debt_digest.resolve_path_owners",return_value=_ownership({_SOURCE_PATH: "team-one", _OTHER_PATH: "team-two", _PRODUCT_PATH: "team-two"}),),- patch("products.visual_review.backend.logic.debt_digest.Integration") as integration,- patch("products.visual_review.backend.logic.debt_digest.SlackIntegration"),+ patch("products.visual_review.backend.logic.team_channels.Integration") as integration,+ patch("products.visual_review.backend.logic.team_channels.SlackIntegration") as slack,patch(- "products.visual_review.backend.logic.debt_digest.fetch_channel_map",+ "products.visual_review.backend.logic.team_channels.fetch_channel_map",return_value={"team-one": SlackChannel(channel_id="C1", shared=False),"team-two": SlackChannel(channel_id="C2", shared=False),},),patch(- "products.visual_review.backend.logic.debt_digest.post_with_join",+ "products.visual_review.backend.logic.team_channels.post_with_join",side_effect=[SlackPostRefused("no"), "1700000000.1"],) as post,- patch("products.visual_review.backend.logic.debt_digest.post_message") as thread_post,+ patch("products.visual_review.backend.logic.team_channels.post_message") as thread_post,):integration.objects.filter.return_value.first.return_value = MagicMock()+ slack.return_value.client.conversations_info.return_value = {"channel": {"id": "C1"}}debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE)assert post.call_count == 2diff --git a/products/visual_review/backend/tests/logic/test_quarantine_notice.py b/products/visual_review/backend/tests/logic/test_quarantine_notice.pynew file mode 100644index 000000000000..b53792fe5d74--- /dev/null+++ b/products/visual_review/backend/tests/logic/test_quarantine_notice.py@@ -0,0 +1,132 @@+import pytest+from unittest.mock import MagicMock, call, patch++from django.utils import timezone++from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership+from posthog.slack.channels import SlackChannel++from products.visual_review.backend.db import WRITER_DB+from products.visual_review.backend.facade.enums import RunType+from products.visual_review.backend.logic import quarantine, quarantine_notice, repos, story_index+from products.visual_review.backend.models import QuarantinedIdentifier+from products.visual_review.backend.tasks.tasks import QUARANTINE_NOTICE_EXPIRY_SECONDS+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES++_SOURCE_PATH = "frontend/src/scenes/Button`www.example.com`.stories.tsx"+_IDENTIFIER = "scenes-app-button--primary--light"+_INDEX = story_index.StoryIndex(path_by_story_id={"scenes-app-button--primary": _SOURCE_PATH})++[email protected]_db(databases=PRODUCT_DATABASES)+class TestSendQuarantineNotice:+ @pytest.fixture+ def repo(self, team):+ return repos.create_repo(team_id=team.id, repo_external_id=66661, repo_full_name="org/test-notice")++ @pytest.fixture+ def post(self):+ channels = "products.visual_review.backend.logic.team_channels"+ with (+ patch("products.visual_review.backend.logic.story_index.latest_story_index", return_value=_INDEX),+ patch(+ "products.visual_review.backend.logic.owners.resolve_path_owners",+ return_value=PathOwnership(team_by_path={_SOURCE_PATH: "team-devex"}, registry={}, resolved=True),+ ) as owners,+ patch(f"{channels}.Integration") as integration,+ patch(f"{channels}.SlackIntegration") as slack,+ patch(+ f"{channels}.fetch_channel_map",+ return_value={"team-devex": SlackChannel(channel_id="C1", shared=False)},+ ) as channel_map,+ patch(f"{channels}.post_with_join", return_value="1700000000.1") as post,+ ):+ integration.objects.filter.return_value.first.return_value = MagicMock()+ slack.return_value.client.conversations_info.return_value = {"channel": {"is_shared": False}}+ post.slack = slack+ post.owners = owners+ post.channel_map = channel_map+ yield post++ def _quarantine(self, repo, user, identifier: str = _IDENTIFIER) -> QuarantinedIdentifier:+ return quarantine.quarantine_identifier(+ repo_id=repo.id,+ identifier=identifier,+ run_type=RunType.STORYBOOK,+ reason="Animation <!channel> timing",+ user_id=user.id,+ team_id=repo.team_id,+ )++ def test_posts_to_the_owning_team_naming_who_quarantined(self, repo, team, user, post):+ entry = self._quarantine(repo, user)++ assert quarantine_notice.send_quarantine_notice(entry.id, team.id) is True+ second = self._quarantine(repo, user, identifier="scenes-app-button--primary--dark")+ assert quarantine_notice.send_quarantine_notice(second.id, team.id) is True++ assert post.channel_map.call_count == 1+ _, channel_id, blocks, text = post.call_args.args+ assert channel_id == "C1"+ assert text.startswith(f"*{user.first_name or user.email}* quarantined a story owned by you. Please check.")+ assert "*scenes-app-button--primary* storybook" in blocks[1]["text"]["text"]+ assert "<!channel>" not in str(blocks)+ assert blocks[2]["elements"] == [+ {"type": "plain_text", "text": f"org/test-notice · {_SOURCE_PATH}", "emoji": False}+ ]++ @pytest.mark.parametrize(+ "case",+ ["unowned", "story_absent", "lifted", "shared_since_listing", "channel_unreadable"],+ )+ def test_nothing_is_posted_without_an_owning_team_an_active_quarantine_or_an_internal_channel(+ self, repo, team, user, post, case+ ):+ if case == "unowned":+ post.owners.return_value = PathOwnership(+ team_by_path={_SOURCE_PATH: UNOWNED_TEAM}, registry={}, resolved=True+ )+ entry = self._quarantine(+ repo, user, "scenes-app-gone--primary--light" if case == "story_absent" else _IDENTIFIER+ )+ if case == "shared_since_listing":+ post.slack.return_value.client.conversations_info.return_value = {"channel": {"is_ext_shared": True}}+ if case == "channel_unreadable":+ post.slack.return_value.client.conversations_info.return_value = {"ok": True}+ if case == "lifted":+ QuarantinedIdentifier.objects.using(WRITER_DB).filter(id=entry.id).update(expires_at=timezone.now())++ assert quarantine_notice.send_quarantine_notice(entry.id, team.id) is False+ assert post.call_count == 0++[email protected]_db(databases=PRODUCT_DATABASES)+class TestQuarantineDispatchesNotice:+ @pytest.mark.parametrize(+ "notify_owners,broker_error",+ [(True, None), (False, None), (True, ConnectionError("broker down"))],+ )+ def test_the_notice_is_queued_only_when_asked_for_and_never_fails_the_quarantine(+ self, team, user, django_capture_on_commit_callbacks, notify_owners, broker_error+ ):+ repo = repos.create_repo(team_id=team.id, repo_external_id=66662, repo_full_name="org/test-dispatch")+ with (+ patch(+ "products.visual_review.backend.tasks.tasks.notify_quarantine_owners.apply_async",+ side_effect=broker_error,+ ) as apply_async,+ django_capture_on_commit_callbacks(using=WRITER_DB, execute=True),+ ):+ entry = quarantine.quarantine_identifier(+ repo_id=repo.id,+ identifier=_IDENTIFIER,+ run_type=RunType.STORYBOOK,+ reason="flaky",+ user_id=user.id,+ team_id=team.id,+ notify_owners=notify_owners,+ )++ expected = [call(args=(team.id, str(entry.id)), expires=QUARANTINE_NOTICE_EXPIRY_SECONDS)]+ assert apply_async.call_args_list == (expected if notify_owners else [])+ assert QuarantinedIdentifier.objects.using(WRITER_DB).filter(id=entry.id).exists()diff --git a/products/visual_review/frontend/components/QuarantineAction.tsx b/products/visual_review/frontend/components/QuarantineAction.tsxindex 9c4b994c6621..c7981eedd4ad 100644--- a/products/visual_review/frontend/components/QuarantineAction.tsx+++ b/products/visual_review/frontend/components/QuarantineAction.tsx@@ -18,6 +18,7 @@ interface QuarantineActionProps {initialReason?: stringinitialExpiresAt?: string | nullsourceRunId?: string | null+ runType?: string/*** Set while a quarantine write for this identifier is in flight. The create* endpoint supersedes the prior active row, so a second submit writes a@@ -39,6 +40,7 @@ export function QuarantineAction({initialReason,initialExpiresAt,sourceRunId,+ runType,pendingReason,}: QuarantineActionProps): JSX.Element {const [isOpen, setIsOpen] = useState(false)@@ -65,6 +67,7 @@ export function QuarantineAction({initialReason={initialReason}initialExpiresAt={initialExpiresAt}sourceRunId={sourceRunId}+ runType={runType}/></div>)diff --git a/products/visual_review/frontend/components/QuarantineModal.tsx b/products/visual_review/frontend/components/QuarantineModal.tsxindex 26eeacdcb3e3..06b7ddefe73b 100644--- a/products/visual_review/frontend/components/QuarantineModal.tsx+++ b/products/visual_review/frontend/components/QuarantineModal.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from 'react'-import { LemonButton, LemonCheckbox, LemonInput, LemonModal } from '@posthog/lemon-ui'+import { LemonButton, LemonCheckbox, LemonInput, LemonModal, LemonSwitch } from '@posthog/lemon-ui'import { DatePicker } from 'lib/components/DatePicker/DatePicker'import { dayjs } from 'lib/dayjs'@@ -14,6 +14,9 @@ const SUGGESTED_REASONS = [const DEFAULT_EXPIRY_DAYS = 30+// Owners come from the Storybook story index, so no other run type has a team to notify.+const NOTIFIABLE_RUN_TYPE = 'storybook'+const COPY = {create: {modalTitle: 'Quarantine snapshot',@@ -67,7 +70,8 @@ export type OnQuarantine = (reason: string,identifiers: string[],expiresAt: string | null,- sourceRunId: string | null+ sourceRunId: string | null,+ notifyOwners: boolean) => voidinterface QuarantineModalProps {@@ -93,6 +97,8 @@ interface QuarantineModalProps {* Forwarded to the parent via `onQuarantine` so the backend can store it.*/sourceRunId?: string | null+ /** The snapshot's run type. The owner notice switch shows only for Storybook snapshots. */+ runType?: string}/**@@ -108,12 +114,15 @@ export function QuarantineModal({initialReason,initialExpiresAt,sourceRunId,+ runType,}: QuarantineModalProps): JSX.Element {const isExtend = mode === 'extend'+ const canNotifyOwners = !isExtend && runType === NOTIFIABLE_RUN_TYPEconst copy = COPY[mode]const [reason, setReason] = useState(initialReason ?? '')const [includeSibling, setIncludeSibling] = useState(true)+ const [notifyOwners, setNotifyOwners] = useState(true)const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(() => computeDefaultExpiry(initialExpiresAt))// Re-prefill if the parent swaps which entry we're acting on mid-session.@@ -125,6 +134,7 @@ export function QuarantineModal({}setReason(initialReason ?? '')setIncludeSibling(true)+ setNotifyOwners(true)setExpiresAt(computeDefaultExpiry(initialExpiresAt))}, [initialReason, initialExpiresAt, isOpen])@@ -137,7 +147,13 @@ export function QuarantineModal({if (!isExtend && sibling && includeSibling) {identifiers.push(sibling)}- onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null, sourceRunId ?? null)+ onQuarantine(+ reason,+ identifiers,+ expiresAt ? expiresAt.toISOString() : null,+ sourceRunId ?? null,+ canNotifyOwners && notifyOwners+ )onClose()}@@ -214,6 +230,25 @@ export function QuarantineModal({maxDate={dayjs().add(1, 'year')}/></div>++ {canNotifyOwners && (+ <LemonSwitch+ checked={notifyOwners}+ onChange={setNotifyOwners}+ bordered+ fullWidth+ data-attr="visual-review-quarantine-notify-owners"+ label={+ <div>+ <div className="text-sm font-medium">Notify the owning team in Slack</div>+ <div className="text-xs text-muted font-normal">+ Posts to the team's channel now, with your name. Skipped if the story has no owner+ in owners.yaml or the project has no Slack integration.+ </div>+ </div>+ }+ />+ )}</div></LemonModal>)diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsxindex f086b6f7bd4c..22e6c023d663 100644--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx@@ -564,7 +564,11 @@ export function SnapshotDiffViewer({{/* Quarantine */}{hasChanges && !isQuarantined && onQuarantine && (- <QuarantineAction identifier={snapshot.identifier} onQuarantine={onQuarantine} />+ <QuarantineAction+ identifier={snapshot.identifier}+ onQuarantine={onQuarantine}+ runType={runType}+ />)}{nudgedIdentifier && onQuarantine && (<QuarantineModal@@ -573,6 +577,7 @@ export function SnapshotDiffViewer({identifier={nudgedIdentifier}onQuarantine={onQuarantine}initialReason="Keeps changing in unrelated PRs"+ runType={runType}/>)}{isQuarantined && onUnquarantine && (diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 49f3172a1f93..7d16c0d6769f 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -291,6 +291,8 @@ export interface QuarantineInputApi {* @nullable*/source_run_id?: string | null+ /** Post the quarantine to the Slack channel of the team that owns the story, naming the user who quarantined it. Only Storybook snapshots have an owning team. Best effort: skipped when the story has no owning team or the project has no Slack integration. */+ notify_owners?: boolean/** @nullable */expires_at?: string | null}diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.tsindex 545077052c90..b22c8d7116a3 100644--- a/products/visual_review/frontend/generated/api.zod.ts+++ b/products/visual_review/frontend/generated/api.zod.ts@@ -41,6 +41,8 @@ export const visualReviewReposQuarantineCreateBodyIdentifierMax = 512export const visualReviewReposQuarantineCreateBodyReasonMax = 255+export const visualReviewReposQuarantineCreateBodyNotifyOwnersDefault = false+export const VisualReviewReposQuarantineCreateBody = /* @__PURE__ */ zod.object({identifier: zod.string()@@ -56,6 +58,12 @@ export const VisualReviewReposQuarantineCreateBody = /* @__PURE__ */ zod.object(.describe("Optional pointer to the run whose failing snapshot prompted this quarantine — used to surface a 'view the failing run' link later."),+ notify_owners: zod+ .boolean()+ .default(visualReviewReposQuarantineCreateBodyNotifyOwnersDefault)+ .describe(+ 'Post the quarantine to the Slack channel of the team that owns the story, naming the user who quarantined it. Only Storybook snapshots have an owning team. Best effort: skipped when the story has no owning team or the project has no Slack integration.'+ ),expires_at: zod.iso.datetime({ offset: true }).nullish(),})diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsxindex 48dd6e8fb804..838e45e63364 100644--- a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx@@ -313,14 +313,23 @@ export function VisualReviewFlakinessScene(): JSX.Element {initialReason={entry.quarantine?.reason}initialExpiresAt={entry.quarantine?.expires_at}sourceRunId={entry.quarantine?.source_run?.id ?? null}- onQuarantine={(reason, identifiers, expiresAt, sourceRunId) => {- identifiers.forEach((identifier) =>+ runType={entry.run_type}+ onQuarantine={(+ reason,+ identifiers,+ expiresAt,+ sourceRunId,+ notifyOwners+ ) => {+ identifiers.forEach((identifier, index) =>quarantineIdentifier(identifier,entry.run_type,reason,expiresAt,- sourceRunId+ sourceRunId,+ // One notice per story, not per theme variant.+ notifyOwners && index === 0))}}diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex 7873c9d32575..f62a1832b2a1 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -608,8 +608,8 @@ export function VisualReviewRunScene(): JSX.Element {(!q.expires_at || new Date(q.expires_at) > new Date())) ?? null}- onQuarantine={(reason, identifiers, expiresAt, sourceRunId) =>- quarantineSnapshot(reason, identifiers, expiresAt, sourceRunId)+ onQuarantine={(reason, identifiers, expiresAt, sourceRunId, notifyOwners) =>+ quarantineSnapshot(reason, identifiers, expiresAt, sourceRunId, notifyOwners)}onUnquarantine={() => unquarantineSnapshot(selectedSnapshot)}commitSha={run.commit_sha}diff --git a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsxindex 477aae487f95..d9552dd79bff 100644--- a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx@@ -14,6 +14,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { QuarantineAction } from '../components/QuarantineAction'+import type { OnQuarantine } from '../components/QuarantineModal'import { SnapshotChangeBadge, hasSnapshotChangeBadge } from '../components/SnapshotChangeBadge'import { VisualReviewTabs } from '../components/VisualReviewTabs'import type { QuarantinedIdentifierEntryApi, SnapshotHistoryEntryApi } from '../generated/api.schemas'@@ -187,12 +188,14 @@ function QuarantineSection({isQuarantined,onQuarantine,onUnquarantine,+ runType,}: {identifier: string+ runType: stringlabel?: string | nullquarantineEntry: QuarantinedIdentifierEntryApi | nullisQuarantined: boolean- onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void+ onQuarantine: OnQuarantineonUnquarantine: () => void}): JSX.Element {if (isQuarantined && quarantineEntry) {@@ -297,6 +300,7 @@ function QuarantineSection({identifier={identifier}onQuarantine={onQuarantine}triggerLabel={label ? `Quarantine (${label})` : undefined}+ runType={runType}/></div>)@@ -382,6 +386,7 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {{!quarantineEntryLoading && (<QuarantineSectionidentifier={identifier}+ runType={runType}label={primaryTheme}quarantineEntry={quarantineEntry}isQuarantined={isQuarantined}@@ -392,6 +397,7 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {{!siblingQuarantineEntryLoading && (<QuarantineSectionidentifier={siblingIdentifier}+ runType={runType}label={primaryTheme === 'light' ? 'dark' : 'light'}quarantineEntry={siblingQuarantineEntry}isQuarantined={isSiblingQuarantined}@@ -404,6 +410,7 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {!quarantineEntryLoading && (<QuarantineSectionidentifier={identifier}+ runType={runType}quarantineEntry={quarantineEntry}isQuarantined={isQuarantined}onQuarantine={quarantineIdentifier}diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.tsindex 539f472ff98f..cfb938e1f2ea 100644--- a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts@@ -240,10 +240,12 @@ export interface visualReviewFlakinessSceneLogicActions {runType: string,reason: string,expiresAt: string | null,- sourceRunId: string | null+ sourceRunId: string | null,+ notifyOwners?: boolean) => {expiresAt: string | nullidentifier: string+ notifyOwners: booleanreason: stringrunType: stringsourceRunId: string | null@@ -326,13 +328,15 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogrunType: string,reason: string,expiresAt: string | null,- sourceRunId: string | null+ sourceRunId: string | null,+ notifyOwners: boolean = false) => ({identifier,runType,reason,expiresAt,sourceRunId,+ notifyOwners,}),unquarantineIdentifier: (identifier: string, runType: string) => ({ identifier, runType }),quarantineSettled: (identifier: string, runType: string) => ({ identifier, runType }),@@ -511,7 +515,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogactions.landOnPreset(populated)}},- quarantineIdentifier: async ({ identifier, runType, reason, expiresAt, sourceRunId }) => {+ quarantineIdentifier: async ({ identifier, runType, reason, expiresAt, sourceRunId, notifyOwners }) => {try {await visualReviewReposQuarantineCreate(String(values.currentProjectId), props.repoId, runType, {identifier,@@ -521,6 +525,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog// old row and creates a replacement, so dropping this loses the link// to the run that prompted the quarantine.source_run_id: sourceRunId,+ notify_owners: notifyOwners,})lemonToast.success('Quarantined. Runs stop gating on this snapshot.')} catch (e: any) {diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.tsindex abc8f81674f0..64d27b1c2de7 100644--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts@@ -180,10 +180,12 @@ export interface visualReviewRunSceneLogicActions {reason: string,identifiers: string[],expiresAt: string | null,- sourceRunId?: string | null+ sourceRunId?: string | null,+ notifyOwners?: boolean) => {expiresAt: string | nullidentifiers: string[]+ notifyOwners: booleanreason: stringsourceRunId: string | null}@@ -265,12 +267,14 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([reason: string,identifiers: string[],expiresAt: string | null,- sourceRunId: string | null = null+ sourceRunId: string | null = null,+ notifyOwners: boolean = false) => ({reason,identifiers,expiresAt,sourceRunId,+ notifyOwners,}),unquarantineSnapshot: (snapshot: SnapshotApi) => ({ snapshot }),recomputeRun: true,@@ -645,7 +649,7 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([lemonToast.error(e?.detail || e?.message || 'Failed to mark as tolerated')}},- quarantineSnapshot: async ({ reason, identifiers, expiresAt, sourceRunId }) => {+ quarantineSnapshot: async ({ reason, identifiers, expiresAt, sourceRunId, notifyOwners }) => {const { run } = valuesif (!run) {return@@ -657,12 +661,14 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([const effectiveSourceRunId = sourceRunId ?? run.idtry {await Promise.all(- identifiers.map((identifier) =>+ identifiers.map((identifier, index) =>visualReviewReposQuarantineCreate(String(values.currentProjectId), run.repo_id, run.run_type, {identifier,reason,expires_at: expiresAt,source_run_id: effectiveSourceRunId,+ // Theme variants of one story share a team, so only the first asks for a notice.+ notify_owners: notifyOwners && index === 0,})))diff --git a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.tsindex f378b13f9a68..efdf6b623d37 100644--- a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts@@ -146,10 +146,12 @@ export interface visualReviewSnapshotHistorySceneLogicActions {reason: string,identifiers: string[],expiresAt: string | null,- sourceRunId?: string | null+ sourceRunId?: string | null,+ notifyOwners?: boolean) => {expiresAt: string | nullidentifiers: string[]+ notifyOwners: booleanreason: stringsourceRunId: string | null}@@ -198,12 +200,14 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHisreason: string,identifiers: string[],expiresAt: string | null,- sourceRunId: string | null = null+ sourceRunId: string | null = null,+ notifyOwners: boolean = false) => ({reason,identifiers,expiresAt,sourceRunId,+ notifyOwners,}),unquarantineIdentifier: true,unquarantineSibling: true,@@ -354,10 +358,10 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis],}),listeners(({ actions, values, props }) => ({- quarantineIdentifier: async ({ reason, identifiers, expiresAt, sourceRunId }) => {+ quarantineIdentifier: async ({ reason, identifiers, expiresAt, sourceRunId, notifyOwners }) => {try {await Promise.all(- identifiers.map((identifier) =>+ identifiers.map((identifier, index) =>visualReviewReposQuarantineCreate(String(values.currentProjectId),props.repoId,@@ -369,6 +373,8 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis// Forward the prior source when extending — keeps the "view// the failing run" link intact across renewals.source_run_id: sourceRunId,+ // Theme variants of one story share a team, so only the first asks for a notice.+ notify_owners: notifyOwners && index === 0,}))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7f41a1e66c70..04dc6ec4226f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -85544,6 +85544,8 @@ export namespace Schemas {* @nullable*/source_run_id?: string | null;+ /** Post the quarantine to the Slack channel of the team that owns the story, naming the user who quarantined it. Only Storybook snapshots have an owning team. Best effort: skipped when the story has no owning team or the project has no Slack integration. */+ notify_owners?: boolean;/** @nullable */expires_at?: string | null;}