: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(inbox): persist and clear report feedback (#116410)
Dylan Martinad6c5fc149b4
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportFeedback.test.tsx b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.test.tsxindex c930ab364907..02e201a1f05a 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportFeedback.test.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, render, screen } from '@testing-library/react'+import { cleanup, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { FEATURE_FLAGS } from 'lib/constants'@@ -20,9 +20,10 @@ jest.mock('products/signals/frontend/inbox/inboxAnalytics', () => ({}))describe('TodayReportFeedback', () => {- beforeEach(() => {+ beforeEach(async () => {useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/': makeReport({ id: 'report-today' }),'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },'/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },@@ -42,6 +43,7 @@ describe('TodayReportFeedback', () => {})jest.mocked(captureInboxReportFeedback).mockClear()render(<TodayReportFeedback report={makeReport({ id: 'report-today' })} />)+ await waitFor(() => expect(screen.getByLabelText('This report was useful')).toBeEnabled())})afterEach(() => {@@ -51,10 +53,46 @@ describe('TodayReportFeedback', () => {it('pops the hog and records the rating from the Today surface on thumbs-up', async () => {await userEvent.click(screen.getByLabelText('This report was useful'))- expect(document.querySelector('[data-attr="inbox-report-feedback-celebration"]')).toBeInTheDocument()- expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1)+ await waitFor(() =>+ expect(document.querySelector('[data-attr="inbox-report-feedback-celebration"]')).toBeInTheDocument()+ )+ await waitFor(() => expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1))expect(captureInboxReportFeedback).toHaveBeenCalledWith(expect.objectContaining({ sentiment: 'positive', surface: 'today' }))+ await userEvent.click(screen.getByLabelText('This report was useful'))+ await waitFor(() =>+ expect(screen.getByLabelText('This report was useful')).toHaveAttribute('aria-pressed', 'false')+ )+ })++ it.each([200, 500])('disables note editing while a save is pending (HTTP %s)', async (status) => {+ await userEvent.click(screen.getByLabelText('This report was not useful'))+ const note = await screen.findByLabelText('Add a note about this report')+ let finishRequest!: () => void+ const responseReady = new Promise<void>((resolve) => {+ finishRequest = resolve+ })+ useMocks({+ post: {+ '/api/projects/:team_id/signals/reports/:id/feedback/': async () => {+ await responseReady+ return [status, { forwarded: false }]+ },+ },+ })++ await userEvent.type(note, 'This report needs more detail{Enter}')+ await waitFor(() => expect(note).toBeDisabled())+ await userEvent.type(note, 'More text')+ expect(note).toHaveValue('This report needs more detail')+ finishRequest()++ if (status === 200) {+ expect(await screen.findByText('Note added: This report needs more detail')).toBeVisible()+ } else {+ await waitFor(() => expect(note).toBeEnabled())+ expect(note).toHaveValue('This report needs more detail')+ }})})diff --git a/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsx b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsxindex 9806fc2b7712..a079b59c74d3 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsx@@ -15,12 +15,19 @@ const NOTE_MAX_LENGTH = 4000export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.Element {const logic = inboxReportDetailLogic({ reportId: report.id, report })- const { feedbackSentiment, feedbackNoteDraft, feedbackNoteSent, feedbackSentNote, feedbackNoteSubmitting } =- useValues(logic)+ const {+ feedbackSentiment,+ feedbackNoteDraft,+ feedbackNoteSent,+ feedbackSentNote,+ feedbackNoteSubmitting,+ feedbackDisabledReason,+ } = useValues(logic)const { rateReport, setFeedbackNoteDraft, submitFeedbackNote } = useActions(logic)const { celebrate, celebration } = useReportFeedbackCelebration()const isPositive = feedbackSentiment === 'positive'const isNegative = feedbackSentiment === 'negative'+ const [askedHere, setAskedHere] = useState(false)const [questionDismissed, setQuestionDismissed] = useState(false)const sendNote = (): void => {if (feedbackNoteDraft.trim()) {@@ -52,13 +59,12 @@ export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.Esize="icon-sm"aria-label="This report was useful"aria-pressed={isPositive}- tooltip="Yes, this was useful"+ tooltip={feedbackDisabledReason ?? (isPositive ? 'Remove thumbs up' : 'Yes, this was useful')}+ disabled={!!feedbackDisabledReason}onClick={() => {- if (!isPositive) {- rateReport('positive', 'today')- setQuestionDismissed(false)- celebrate()- }+ rateReport(isPositive ? null : 'positive', 'today', !isPositive ? celebrate : undefined)+ setQuestionDismissed(false)+ setAskedHere(true)}}data-attr="today-report-feedback-up">@@ -70,12 +76,12 @@ export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.Esize="icon-sm"aria-label="This report was not useful"aria-pressed={isNegative}- tooltip="No, this wasn't useful"+ tooltip={feedbackDisabledReason ?? (isNegative ? 'Remove thumbs down' : "No, this wasn't useful")}+ disabled={!!feedbackDisabledReason}onClick={() => {- if (!isNegative) {- rateReport('negative', 'today')- setQuestionDismissed(false)- }+ rateReport(isNegative ? null : 'negative', 'today')+ setQuestionDismissed(false)+ setAskedHere(true)}}data-attr="today-report-feedback-down">@@ -104,6 +110,7 @@ export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.E<div className="flex items-end gap-1.5"><Textareavalue={feedbackNoteDraft}+ disabled={feedbackNoteSubmitting}onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>setFeedbackNoteDraft(event.target.value)}@@ -117,7 +124,7 @@ export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.Earia-label="Add a note about this report"maxLength={NOTE_MAX_LENGTH}rows={2}- autoFocus+ autoFocus={askedHere}className="max-h-48 min-h-14! min-w-0 flex-1 resize-none"data-attr="today-report-feedback-note"/>diff --git a/products/signals/backend/test/test_feedback_scout_notes.py b/products/signals/backend/test/test_feedback_scout_notes.pyindex 3a305f900635..ebd7da5d8dd0 100644--- a/products/signals/backend/test/test_feedback_scout_notes.py+++ b/products/signals/backend/test/test_feedback_scout_notes.py@@ -12,12 +12,15 @@ from django.apps import appsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+from products.access_control.backend.models.access_control import AccessControlfrom products.signals.backend.models import (SignalReport,SignalReportAction,@@ -76,6 +79,13 @@ class TestFeedbackScoutNotes(APIBaseTest):def _notes(self) -> list[SignalScoutNote]:return list(SignalScoutNote.objects.filter(team=self.team).order_by("created_at"))+ def _set_task_access(self, access_level: AccessControlLevel) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(team=self.team, resource="task", access_level=access_level)+def test_feedback_note_reaches_the_authoring_scout(self) -> None:self._create_scout_skill()report = self._create_report()@@ -180,6 +190,63 @@ class TestFeedbackScoutNotes(APIBaseTest):assert action.count == 2assert action.metadata == {"sentiment": "negative"}+ @parameterized.expand([("positive", "negative", "ready"), ("negative", "positive", "suppressed")])+ def test_feedback_can_be_read_changed_and_cleared(self, first: str, second: str, report_status: str) -> None:+ self._set_task_access("viewer")+ report = self._create_report()+ report.status = report_status+ report.save(update_fields=["status"])+ read_url = self._feedback_url(str(report.id)).replace("/feedback/", "/feedback_state/")+ assert self.client.get(read_url).json() == {"sentiment": None, "note": ""}++ self._feedback(report, sentiment=first, note="Useful evidence")+ assert self.client.get(read_url).json() == {"sentiment": first, "note": "Useful evidence"}++ self._feedback(report, sentiment=second)+ assert self.client.get(read_url).json() == {"sentiment": second, "note": ""}++ self._feedback(report, sentiment=None)+ assert self.client.get(read_url).json() == {"sentiment": None, "note": ""}+ self._feedback(report, sentiment=None)+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)+ assert action.count == 2++ def test_feedback_is_private_to_each_user(self) -> None:+ report = self._create_report()+ self._feedback(report, sentiment="positive", note="Useful evidence")+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "test-password")+ self.client.force_login(other_user)+ read_url = self._feedback_url(str(report.id)).replace("/feedback/", "/feedback_state/")+ assert self.client.get(read_url).json() == {"sentiment": None, "note": ""}+ self._feedback(report, sentiment="negative")+ self._feedback(report, sentiment=None)+ self.client.force_login(self.user)+ assert self.client.get(read_url).json() == {"sentiment": "positive", "note": "Useful evidence"}++ def test_feedback_cannot_be_read_from_another_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY)+ url = self._feedback_url(str(report.id)).replace("/feedback/", "/feedback_state/")+ assert self.client.get(url).status_code == status.HTTP_404_NOT_FOUND++ def test_feedback_requires_report_access(self) -> None:+ self._set_task_access("none")+ report = self._create_report()+ url = self._feedback_url(str(report.id))++ assert self.client.get(url.replace("/feedback/", "/feedback_state/")).status_code == status.HTTP_403_FORBIDDEN+ response = self.client.post(url, {"sentiment": "positive"}, format="json")+ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not SignalReportAction.objects.for_team(self.team.id).filter(report=report).exists()++ def test_clearing_feedback_does_not_forward_a_note(self) -> None:+ report = self._create_report()+ response = self.client.post(+ self._feedback_url(str(report.id)), {"sentiment": None, "note": "A note"}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not SignalReportAction.objects.for_team(self.team.id).filter(report=report).exists()+def test_a_note_following_a_rating_counts_as_one_interaction(self) -> None:# The inbox posts the bare rating on click and the optional note afterwards — one thumb# choice. The note request must amend the action row, not count a second interaction.@@ -192,7 +259,7 @@ class TestFeedbackScoutNotes(APIBaseTest):action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)assert action.count == 1- assert action.metadata == {"sentiment": "positive"}+ assert action.metadata == {"sentiment": "positive", "note": "the staging spike is a known issue"}assert len(self._notes()) == 1def test_a_note_carrying_rating_with_no_prior_row_still_records_the_action(self) -> None:@@ -204,7 +271,7 @@ class TestFeedbackScoutNotes(APIBaseTest):action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)assert action.count == 1- assert action.metadata == {"sentiment": "negative"}+ assert action.metadata == {"sentiment": "negative", "note": "not useful"}def test_feedback_still_succeeds_when_the_note_cannot_be_written(self) -> None:self._create_scout_skill()@@ -236,9 +303,10 @@ class TestFeedbackScoutNotes(APIBaseTest):assert body["forwarded"] is Falseassert not SignalScoutNote.all_teams.exists()- def test_no_note_when_the_token_lacks_the_note_scopes(self) -> None:+ @parameterized.expand([(["task:read"],), (["task:read", "task:write"],)])+ def test_no_note_when_the_token_lacks_the_note_scopes(self, scopes: list[str]) -> None:# The feedback text has no second path to a run, so — like a discussion — forwarding demands- # the note-write key scopes on top of the `task:write` the action itself needs.+ # the note-write key scopes on top of the `task:read` the action itself needs.self._create_scout_skill()report = self._create_report()self._create_run(emitted_report_ids=[str(report.id)])@@ -247,7 +315,7 @@ class TestFeedbackScoutNotes(APIBaseTest):label="Task-only key",user=self.user,secure_value=hash_key_value(raw_key),- scopes=["task:write", "task:read"],+ scopes=scopes,)self.client.logout()self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")@@ -261,6 +329,7 @@ class TestFeedbackScoutNotes(APIBaseTest):# Forwarding re-checks the `llm_skill` editor bar the notes API requires, so a member barred# from skill editing can't reach the steering channel through feedback.self._create_scout_skill()+ self._set_task_access("viewer")report = self._create_report()self._create_run(emitted_report_ids=[str(report.id)])diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex f374e2e68d5e..f0bf76c6730e 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -888,10 +888,16 @@ class SignalReportMergeResponseSerializer(serializers.Serializer):SIGNAL_REPORT_FEEDBACK_NOTE_MAX_LENGTH = SIGNAL_REPORT_DISMISSAL_NOTE_MAX_LENGTH+class SignalReportFeedbackSentiment(models.TextChoices):+ POSITIVE = "positive", "positive"+ NEGATIVE = "negative", "negative"++class SignalReportFeedbackRequestSerializer(serializers.Serializer):sentiment = serializers.ChoiceField(- choices=[("positive", "positive"), ("negative", "negative")],- help_text="The rating left on the report: 'positive' (thumbs up) or 'negative' (thumbs down).",+ choices=SignalReportFeedbackSentiment.choices,+ allow_null=True,+ help_text="The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.",)note = serializers.CharField(max_length=SIGNAL_REPORT_FEEDBACK_NOTE_MAX_LENGTH,@@ -906,6 +912,15 @@ class SignalReportFeedbackRequestSerializer(serializers.Serializer):),)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if attrs["sentiment"] is None and attrs["note"].strip():+ raise serializers.ValidationError({"note": "Select a rating before you add a note."})+ return attrs+++class SignalReportFeedbackStateSerializer(SignalReportFeedbackRequestSerializer):+ note = serializers.CharField(allow_blank=True, help_text="The current user's saved note, or an empty string.")+class SignalReportFeedbackResponseSerializer(serializers.Serializer):forwarded = serializers.BooleanField(@@ -1187,7 +1202,7 @@ class SignalReportViewSet(def safely_get_queryset(self, queryset):if self.action == "read_state":return queryset.filter(team=self.team).exclude(status=SignalReport.Status.DELETED)- if self.action in {"viewed", "pr_ci_statuses", "refresh_metrics"}:+ if self.action in {"viewed", "feedback_state", "feedback", "pr_ci_statuses", "refresh_metrics"}:# None of these actions renders a report, so they skip the rendering annotations and# prefetches every other action's serializer needs. `viewed` is passive telemetry fired# right after the detail request that already rendered the report, `pr_ci_statuses` only@@ -1335,6 +1350,7 @@ class SignalReportViewSet("signals","refund","feedback",+ "feedback_state","viewed","pr_checks","pr_comments",@@ -2930,6 +2946,22 @@ class SignalReportViewSet().data)+ @extend_schema(responses=SignalReportFeedbackStateSerializer)+ @action(detail=True, methods=["get"], required_scopes=["task:read"])+ def feedback_state(self, request: Request, pk=None, **kwargs) -> Response:+ report = self.get_object()+ metadata = (+ SignalReportAction.objects.for_team(self.team.id)+ .filter(report=report, user=cast(User, request.user), type=SignalReportAction.ActionType.FEEDBACK)+ .values_list("metadata", flat=True)+ .first()+ ) or {}+ return Response(+ SignalReportFeedbackStateSerializer(+ {"sentiment": metadata.get("sentiment"), "note": metadata.get("note", "")}+ ).data+ )+@extend_schema(summary="Leave feedback on a report",description=(@@ -2944,7 +2976,7 @@ class SignalReportViewSet(request=SignalReportFeedbackRequestSerializer,responses={200: SignalReportFeedbackResponseSerializer},)- @action(detail=True, methods=["post"], url_path="feedback", required_scopes=["task:write"])+ @action(detail=True, methods=["post"], url_path="feedback", required_scopes=["task:read"])def feedback(self, request, pk=None, **kwargs):"""Persist a report's thumbs rating and forward its note to the authoring scout.@@ -2969,10 +3001,10 @@ class SignalReportViewSet(report_id=str(report.id),user_id=request.user.id,action_type=SignalReportAction.ActionType.FEEDBACK,- metadata={"sentiment": data["sentiment"]},- bump_count=not note,+ metadata={"sentiment": data["sentiment"], **({"note": note} if note else {})},+ bump_count=not note and data["sentiment"] is not None,)- if not note:+ if not note and data["sentiment"] is not None:capture_background_report_events(team=self.team,user=request.user,diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 72fe93e39c1e..a4ec9ceaf3c2 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1064,19 +1064,20 @@ export interface SignalReportClaimApi {* * `positive` - positive* * `negative` - negative*/-export type SentimentEnumApi = (typeof SentimentEnumApi)[keyof typeof SentimentEnumApi]+export type SignalReportFeedbackSentimentEnumApi =+ (typeof SignalReportFeedbackSentimentEnumApi)[keyof typeof SignalReportFeedbackSentimentEnumApi]-export const SentimentEnumApi = {+export const SignalReportFeedbackSentimentEnumApi = {Positive: 'positive',Negative: 'negative',} as constexport interface SignalReportFeedbackRequestApi {- /** The rating left on the report: 'positive' (thumbs up) or 'negative' (thumbs down).+ /** The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.** * `positive` - positive* * `negative` - negative */- sentiment: SentimentEnumApi+ sentiment: SignalReportFeedbackSentimentEnumApi | null/*** Free-form note explaining the rating. Capped at 4000 characters. Optional — a bare thumb carries none. When present and the report was authored by a scout, the note is forwarded to that scout as a steering note.* @maxLength 4000@@ -1089,6 +1090,16 @@ export interface SignalReportFeedbackResponseApi {forwarded: boolean}+export interface SignalReportFeedbackStateApi {+ /** The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.+ *+ * * `positive` - positive+ * * `negative` - negative */+ sentiment: SignalReportFeedbackSentimentEnumApi | null+ /** The current user's saved note, or an empty string. */+ note: string+}+export interface SignalReportMergeRequestApi {/*** Ids of the duplicate reports to fold into this one (1–10). Each must be a live report in this project: a resolved, archived or deleted report is rejected with 409, as is the survivor's own id. Duplicates in the list are de-duplicated. The whole merge applies or none of it does.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex f2bc8e25b1cb..cb2291e9c26d 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -95,6 +95,7 @@ import type {SignalReportDeletionStatusApi,SignalReportFeedbackRequestApi,SignalReportFeedbackResponseApi,+ SignalReportFeedbackStateApi,SignalReportMergeRequestApi,SignalReportMergeResponseApi,SignalReportMetricRefreshRequestApi,@@ -411,6 +412,21 @@ export const signalsReportsFeedbackCreate = async (})}+export const getSignalsReportsFeedbackStateRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/reports/${id}/feedback_state/`+}++export const signalsReportsFeedbackStateRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SignalReportFeedbackStateApi> => {+ return apiMutator<SignalReportFeedbackStateApi>(getSignalsReportsFeedbackStateRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsReportsMergeCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/signals/reports/${id}/merge/`}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 3405ca7eb473..ae3eeb0b0ddc 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -173,10 +173,12 @@ export const signalsReportsFeedbackCreateBodyNoteMax = 4000export const SignalsReportsFeedbackCreateBody = /* @__PURE__ */ zod.object({sentiment: zod- .enum(['positive', 'negative'])- .describe('\* `positive` - positive\n\* `negative` - negative')+ .union([+ zod.enum(['positive', 'negative']).describe('\* `positive` - positive\n\* `negative` - negative'),+ zod.null(),+ ]).describe(- "The rating left on the report: 'positive' (thumbs up) or 'negative' (thumbs down).\n\n\* `positive` - positive\n\* `negative` - negative"+ "The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.\n\n\* `positive` - positive\n\* `negative` - negative"),note: zod.string()diff --git a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsxindex ef08c05793fc..1f7b0d44ec58 100644--- a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx@@ -90,6 +90,7 @@ const successfulPrChecks = {const detailMocks = mswDecorator({get: {+ '/api/projects/:id/signals/reports/:reportId/feedback_state/': { sentiment: null, note: '' },'/api/projects/:id/signals/reports/:reportId/artefacts': (req) => {const reportId = req.params.reportId as stringreturn [200, mockArtefacts(reportId)]diff --git a/products/signals/frontend/inbox/components/detail/ReportFeedbackCelebration.stories.tsx b/products/signals/frontend/inbox/components/detail/ReportFeedbackCelebration.stories.tsxindex 00ecd1b0ed4e..ac4a0386442b 100644--- a/products/signals/frontend/inbox/components/detail/ReportFeedbackCelebration.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportFeedbackCelebration.stories.tsx@@ -38,6 +38,7 @@ export const InFooter: Story = {decorators: [mswDecorator({get: {+ '/api/projects/:id/signals/reports/:reportId/feedback_state/': { sentiment: null, note: '' },'/api/projects/:id/signals/reports/:reportId/artefacts': { results: [] },'/api/projects/:id/signals/reports/:reportId/signals': { signals: [] },'/api/projects/:id/signals/reports/available_reviewers': [],diff --git a/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.test.tsx b/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.test.tsxindex 6507358511e4..88914e7d9bf7 100644--- a/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { act, cleanup, render, screen } from '@testing-library/react'+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { FEATURE_FLAGS } from 'lib/constants'@@ -47,10 +47,11 @@ function setReducedMotion(matches: boolean): void {describe('ReportFeedbackFooter', () => {const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })- beforeEach(() => {+ beforeEach(async () => {jest.useFakeTimers()useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },'/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],@@ -65,6 +66,9 @@ describe('ReportFeedbackFooter', () => {jest.mocked(captureInboxReportFeedback).mockClear()jest.mocked(captureInboxReportFeedbackNote).mockClear()render(<ReportFeedbackFooter report={makeReport({ id: 'report-celebration' })} />)+ await waitFor(() =>+ expect(screen.getByLabelText('This report was useful')).toHaveAttribute('aria-disabled', 'false')+ )})afterEach(() => {@@ -78,8 +82,8 @@ describe('ReportFeedbackFooter', () => {await user.click(thumbsUp)- expect(document.querySelector(CELEBRATION_SELECTOR)).toBeInTheDocument()- expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1)+ await waitFor(() => expect(document.querySelector(CELEBRATION_SELECTOR)).toBeInTheDocument())+ await waitFor(() => expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1))expect(captureInboxReportFeedback).toHaveBeenCalledWith(expect.objectContaining({ sentiment: 'positive' }))act(() => {@@ -87,8 +91,9 @@ describe('ReportFeedbackFooter', () => {})expect(document.querySelector(CELEBRATION_SELECTOR)).not.toBeInTheDocument()- // A re-click is a no-op for feedback, so it earns no second pop either.+ // Clearing the rating does not start the animation.await user.click(thumbsUp)+ await waitFor(() => expect(thumbsUp).toHaveAttribute('aria-pressed', 'false'))expect(document.querySelector(CELEBRATION_SELECTOR)).not.toBeInTheDocument()expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1)})@@ -98,16 +103,35 @@ describe('ReportFeedbackFooter', () => {expect(screen.queryByLabelText('Add a note about this report')).not.toBeInTheDocument()await user.click(screen.getByLabelText('This report was useful'))- expect(screen.getByText('What made it useful?')).toBeVisible()+ expect(await screen.findByText('What made it useful?')).toBeVisible()await user.click(screen.getByLabelText('This report was not useful'))- expect(screen.getByText('What was off?')).toBeVisible()- await user.type(screen.getByLabelText('Add a note about this report'), 'The repro steps were wrong{Enter}')-- expect(captureInboxReportFeedbackNote).toHaveBeenCalledWith(- expect.objectContaining({ sentiment: 'negative', note: 'The repro steps were wrong' })+ expect(await screen.findByText('What was off?')).toBeVisible()+ let finishRequest!: () => void+ const responseReady = new Promise<void>((resolve) => {+ finishRequest = resolve+ })+ useMocks({+ post: {+ '/api/projects/:team_id/signals/reports/:id/feedback/': async () => {+ await responseReady+ return [200, { forwarded: false }]+ },+ },+ })+ const note = screen.getByLabelText('Add a note about this report')+ await user.type(note, 'The repro steps were wrong{Enter}')+ await waitFor(() => expect(note).toBeDisabled())+ await user.type(note, 'More text')+ expect(note).toHaveValue('The repro steps were wrong')+ finishRequest()++ await waitFor(() =>+ expect(captureInboxReportFeedbackNote).toHaveBeenCalledWith(+ expect.objectContaining({ sentiment: 'negative', note: 'The repro steps were wrong' })+ ))- expect(screen.getByText('Note added: The repro steps were wrong')).toBeVisible()+ expect(await screen.findByText('Note added: The repro steps were wrong')).toBeVisible()expect(screen.queryByLabelText('Add a note about this report')).not.toBeInTheDocument()})@@ -117,7 +141,9 @@ describe('ReportFeedbackFooter', () => {await user.click(screen.getByLabelText('This report was not useful'))expect(document.querySelector(CELEBRATION_SELECTOR)).not.toBeInTheDocument()- expect(captureInboxReportFeedback).toHaveBeenCalledWith(expect.objectContaining({ sentiment: 'negative' }))+ await waitFor(() =>+ expect(captureInboxReportFeedback).toHaveBeenCalledWith(expect.objectContaining({ sentiment: 'negative' }))+ )})it.each([@@ -130,7 +156,9 @@ describe('ReportFeedbackFooter', () => {await user.click(screen.getByLabelText('This report was useful'))expect(document.querySelector(CELEBRATION_SELECTOR)).not.toBeInTheDocument()- expect(screen.getByText('Thanks for the feedback!')).toBeVisible()+ await waitFor(() =>+ expect(screen.getByLabelText('This report was useful')).toHaveAttribute('aria-pressed', 'true')+ )expect(captureInboxReportFeedback).toHaveBeenCalledTimes(1)})})diff --git a/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.tsx b/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.tsxindex 26dfdd343cfd..9211cbb56e69 100644--- a/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportFeedbackFooter.tsx@@ -31,8 +31,14 @@ export function ReportFeedbackFooter({align?: 'start' | 'end'}): JSX.Element {const logic = inboxReportDetailLogic({ reportId: report.id, report })- const { feedbackSentiment, feedbackNoteDraft, feedbackNoteSent, feedbackSentNote, feedbackNoteSubmitting } =- useValues(logic)+ const {+ feedbackSentiment,+ feedbackNoteDraft,+ feedbackNoteSent,+ feedbackSentNote,+ feedbackNoteSubmitting,+ feedbackDisabledReason,+ } = useValues(logic)const { rateReport, setFeedbackNoteDraft, submitFeedbackNote } = useActions(logic)const { celebrate, celebration } = useReportFeedbackCelebration()@@ -49,17 +55,11 @@ export function ReportFeedbackFooter({const isPositive = feedbackSentiment === 'positive'const isNegative = feedbackSentiment === 'negative'- // Re-clicking the chosen thumb is a no-op rather than a second identical feedback event.const rate = (sentiment: InboxReportFeedbackSentiment): void => {- if (feedbackSentiment === sentiment) {- return- }- rateReport(sentiment)+ const nextSentiment = feedbackSentiment === sentiment ? null : sentiment+ rateReport(nextSentiment, 'detail_footer', nextSentiment === 'positive' ? celebrate : undefined)setQuestionDismissed(false)setAskedHere(true)- if (sentiment === 'positive') {- celebrate()- }}const askingWhy = !!feedbackSentiment && !feedbackNoteSent && !questionDismissed@@ -89,7 +89,8 @@ export function ReportFeedbackFooter({size="xsmall"type={isPositive ? 'primary' : 'secondary'}icon={isPositive ? <IconThumbsUpFilled /> : <IconThumbsUp />}- tooltip="Yes, this was useful"+ tooltip={isPositive ? 'Remove thumbs up' : 'Yes, this was useful'}+ disabledReason={feedbackDisabledReason}aria-label="This report was useful"aria-pressed={isPositive}onClick={() => rate('positive')}@@ -101,7 +102,8 @@ export function ReportFeedbackFooter({size="xsmall"type={isNegative ? 'primary' : 'secondary'}icon={isNegative ? <IconThumbsDownFilled /> : <IconThumbsDown />}- tooltip="No, this wasn't useful"+ tooltip={isNegative ? 'Remove thumbs down' : "No, this wasn't useful"}+ disabledReason={feedbackDisabledReason}aria-label="This report was not useful"aria-pressed={isNegative}onClick={() => rate('negative')}@@ -133,6 +135,7 @@ export function ReportFeedbackFooter({<div className="min-w-0 flex-1"><LemonTextAreavalue={feedbackNoteDraft}+ disabled={feedbackNoteSubmitting}// Capped here rather than with `maxLength`, whose counter footer would// make the small field a block.onChange={(value) => setFeedbackNoteDraft(value.slice(0, FEEDBACK_NOTE_MAX_LENGTH))}diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 62c13f2b3196..5f72428f9b25 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -146,6 +146,7 @@ export type InboxReportFeedbackSentiment = 'positive' | 'negative'*/export type InboxReportActionType =| 'dismiss'+ | 'clear_feedback'| 'resolve'| 'discuss'| 'restore'diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 87421fc45e01..9ad7fae4c412 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -35,6 +35,7 @@ describe('inboxReportDetailLogic', () => {beforeEach(async () => {useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },'/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/:id/checks/': { results: [] },@@ -153,6 +154,7 @@ describe('inboxReportDetailLogic', () => {beforeEach(async () => {useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },'/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/:id/checks/': { results: [openCheck] },@@ -203,6 +205,7 @@ describe('inboxReportDetailLogic', () => {beforeEach(async () => {useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [artefact] },'/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],@@ -229,6 +232,7 @@ describe('inboxReportDetailLogic', () => {let refreshStarted = falseuseMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': async () => {refreshStarted = trueawait heldRefresh@@ -312,6 +316,7 @@ describe('inboxReportDetailLogic', () => {beforeEach(() => {useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },'/api/projects/:team_id/signals/reports/:id/signals/': {signals: [{ signal_id: 's1' }, { signal_id: 's2' }, { signal_id: 's3' }],@@ -376,13 +381,14 @@ describe('inboxReportDetailLogic', () => {let notePosts: numberlet bareRatingPosts: number- beforeEach(() => {+ beforeEach(async () => {notePosts = 0bareRatingPosts = 0useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },- '/api/projects/:team_id/signals/reports/:id/signals/': [],+ '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],},post: {@@ -400,14 +406,47 @@ describe('inboxReportDetailLogic', () => {initKeaTests()logic = inboxReportDetailLogic({ reportId: REPORT.id, report: REPORT })logic.mount()+ await expectLogic(logic).toFinishAllListeners()})afterEach(() => {logic.unmount()})+ it.each(['positive', 'negative'] as const)('restores and clears a saved %s rating', async (sentiment) => {+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment, note: 'Saved note' },+ },+ })+ logic.actions.loadFeedback()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.feedbackSentiment).toBe(sentiment)+ expect(logic.values.feedbackSentNote).toBe('Saved note')+ logic.actions.rateReport(null)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.feedbackSentiment).toBeNull()+ expect(logic.values.feedbackNoteSent).toBe(false)+ })++ it('keeps the saved rating and note draft when a write fails', async () => {+ logic.actions.rateReport('positive')+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setFeedbackNoteDraft('Keep this note')+ useMocks({ post: { '/api/projects/:team_id/signals/reports/:id/feedback/': [500, {}] } })+ logic.actions.submitFeedbackNote('Keep this note')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.feedbackNoteDraft).toBe('Keep this note')+ expect(logic.values.feedbackNoteSent).toBe(false)+ logic.actions.rateReport(null)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.feedbackSentiment).toBe('positive')+ expect(logic.values.feedbackSubmitting).toBe(false)+ })+it('posts once on a double-click and lets a revised note through after re-rating', async () => {logic.actions.rateReport('positive')+ await expectLogic(logic).toFinishAllListeners()// A double-click dispatches submit twice before the first request settles.logic.actions.submitFeedbackNote('the repro steps were right')logic.actions.submitFeedbackNote('the repro steps were right')@@ -420,6 +459,7 @@ describe('inboxReportDetailLogic', () => {// Re-rating reopens the note flow; the guard must have reset or this submit is silently dropped.logic.actions.rateReport('negative')+ await expectLogic(logic).toFinishAllListeners()logic.actions.submitFeedbackNote('actually this was stale')await expectLogic(logic).toFinishAllListeners()@@ -456,8 +496,9 @@ describe('inboxReportDetailLogic', () => {requestedPrIds = []useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },- '/api/projects/:team_id/signals/reports/:id/signals/': [],+ '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],'/api/projects/:team_id/signals/reports/:id/pr_checks/': ({ request }) => {requestedPrIds.push(new URL(request.url).searchParams.get('pull_request_id'))@@ -552,8 +593,9 @@ describe('inboxReportDetailLogic', () => {const commentsB = [{ id: 2, body: 'B only', kind: 'issue' }]useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },- '/api/projects/:team_id/signals/reports/:id/signals/': [],+ '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],'/api/projects/:team_id/signals/reports/:id/pr_checks/': async ({ request }) => {if (new URL(request.url).searchParams.get('pull_request_id') === 'pr-a') {@@ -645,11 +687,12 @@ describe('inboxReportDetailLogic', () => {artefactRequests = 0useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/artefacts/': () => {artefactRequests += 1return { results: [] }},- '/api/projects/:team_id/signals/reports/:id/signals/': [],+ '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },'/api/projects/:team_id/signals/reports/available_reviewers/': [],},})@@ -759,6 +802,7 @@ describe('inboxReportDetailLogic', () => {let checkRequests = 0useMocks({get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/checks/': () => {checkRequests++return [200, { results: [replacement] }]@@ -807,6 +851,7 @@ describe('inboxReportDetailLogic', () => {'/api/projects/:team_id/signals/reports/:id/checks/:check_id/approve/': [200, approved],},get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },'/api/projects/:team_id/signals/reports/:id/checks/': async () => {requestStarted()await responseReadydiff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex 686acb2068d4..760d69cead54 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -39,6 +39,7 @@ import {signalsReportPrReviewCommentsCreate,signalsReportPrReviewCommentUpdate,signalsReportsFeedbackCreate,+ signalsReportsFeedbackStateRetrieve,signalsReportsSignalsRetrieve,signalsReportsPriorityUpdate,} from 'products/signals/frontend/generated/api'@@ -50,10 +51,12 @@ import type {ReportChartApi,ReportPriorityApi,SignalReportCheckApi,+ SignalReportFeedbackStateApi,SignalReportApi,} from 'products/signals/frontend/generated/api.schemas'import type { SignalNodeApi } from 'products/signals/frontend/generated/api.schemas'+import type { SignalReportFeedbackSentimentEnumApi } from '../../generated/api.schemas'import {deriveTaskPurpose,PURPOSE_ORDER,@@ -304,11 +307,17 @@ export interface inboxReportDetailLogicValues {editingCommentId: string | nullevidenceExpanded: booleanexpandedTaskIds: string[]+ feedbackDisabledReason:+ | 'Could not load feedback. Refresh the page to try again.'+ | 'Loading feedback'+ | 'Saving feedback'+ | undefinedfeedbackNoteDraft: stringfeedbackNoteSent: booleanfeedbackNoteSubmitting: booleanfeedbackSentNote: string | null- feedbackSentiment: InboxReportFeedbackSentiment | null+ feedbackSentiment: SignalReportFeedbackSentimentEnumApi | null+ feedbackSubmitting: booleanhasImplementationPr: booleanhasPersonalGithub: booleanimplementationSlotClaim: ImplementationSlotClaim | null@@ -348,6 +357,8 @@ export interface inboxReportDetailLogicValues {reportTaskToOpen: ReportTaskEntry | nullreportTasks: ReportTaskEntry[] | nullreportTasksLoading: boolean+ savedFeedback: SignalReportFeedbackStateApi | null+ savedFeedbackLoading: booleanselectedPullRequest: ReportPullRequestselectedPullRequestUrl: string | nullselectedTask: ReportTaskEntry | null@@ -395,6 +406,9 @@ export interface inboxReportDetailLogicActions {expandEvidence: () => {value: true}+ feedbackSaved: (feedback: SignalReportFeedbackStateApi) => {+ feedback: SignalReportFeedbackStateApi+ }loadAvailableReviewers: ({ query }?: { query?: string }) => {query?: string}@@ -424,6 +438,21 @@ export interface inboxReportDetailLogicActions {query?: string}}+ loadFeedback: () => any+ loadFeedbackFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFeedbackSuccess: (+ savedFeedback: SignalReportFeedbackStateApi,+ payload?: any+ ) => {+ savedFeedback: SignalReportFeedbackStateApi+ payload?: any+ }loadPrChecks: (_: void) => voidloadPrChecksFailure: (error: string,@@ -560,10 +589,12 @@ export interface inboxReportDetailLogicActions {value: true}rateReport: (- sentiment: InboxReportFeedbackSentiment,- surface?: InboxReportActionSurface+ sentiment: InboxReportFeedbackSentiment | null,+ surface?: InboxReportActionSurface,+ onSuccess?: () => void) => {- sentiment: InboxReportFeedbackSentiment+ onSuccess: (() => void) | undefined+ sentiment: InboxReportFeedbackSentiment | nullsurface: InboxReportActionSurface}searchAvailableReviewers: (query: string) => {@@ -584,6 +615,9 @@ export interface inboxReportDetailLogicActions {setFeedbackNoteSubmitting: (submitting: boolean) => {submitting: boolean}+ setFeedbackSubmitting: (submitting: boolean) => {+ submitting: boolean+ }setOptimisticReviewers: (reviewers: EnrichedReviewer[] | null) => {reviewers: EnrichedReviewer[] | null}@@ -629,6 +663,21 @@ export interface inboxReportDetailLogicActions {export interface inboxReportDetailLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ feedbackSentiment: (+ savedFeedback: SignalReportFeedbackStateApi | null+ ) => SignalReportFeedbackSentimentEnumApi | null+ feedbackSentNote: (savedFeedback: SignalReportFeedbackStateApi | null) => string | null+ feedbackNoteSent: (feedbackSentNote: string | null) => boolean+ feedbackDisabledReason: (+ savedFeedback: SignalReportFeedbackStateApi | null,+ savedFeedbackLoading: boolean,+ feedbackSubmitting: boolean,+ feedbackNoteSubmitting: boolean+ ) =>+ | 'Could not load feedback. Refresh the page to try again.'+ | 'Loading feedback'+ | 'Saving feedback'+ | undefinedisUpdatingReviewers: (optimisticReviewers: EnrichedReviewer[] | null) => booleanreportReviewers: (reportArtefacts: SignalReportArtefact[] | null) => EnrichedReviewer[] | nullisReportActive: (report: SignalReport | null) => boolean@@ -739,9 +788,14 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([toggleExpandedTask: (taskId: string) => ({ taskId }),// Thumbs feedback at the end of the report body. Recorded server-side as a report action// (consumption evidence) – nothing about the report's state changes.- rateReport: (sentiment: InboxReportFeedbackSentiment, surface: InboxReportActionSurface = 'detail_footer') => ({+ rateReport: (+ sentiment: InboxReportFeedbackSentiment | null,+ surface: InboxReportActionSurface = 'detail_footer',+ onSuccess?: () => void+ ) => ({sentiment,surface,+ onSuccess,}),// Optional note, offered only after a rating is in. The rating is never held up waiting for it.setFeedbackNoteDraft: (draft: string) => ({ draft }),@@ -755,9 +809,18 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// Driven by the submit listener only, so the re-entrancy guard and the Send button's// loading state read the same flag.setFeedbackNoteSubmitting: (submitting: boolean) => ({ submitting }),+ setFeedbackSubmitting: (submitting: boolean) => ({ submitting }),+ feedbackSaved: (feedback: SignalReportFeedbackStateApi) => ({ feedback }),}),loaders(({ props, values }) => ({+ savedFeedback: [+ null as SignalReportFeedbackStateApi | null,+ {+ loadFeedback: async () =>+ await signalsReportsFeedbackStateRetrieve(String(teamLogic.values.currentTeamId), props.reportId),+ },+ ],reportArtefacts: [null as SignalReportArtefact[] | null,{@@ -1002,37 +1065,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([setDetailTab: (_, { tab }) => tab,},],- // The thumbs rating this reader gave the open report, so the row can read the choice back.- // The logic is keyed by report id, so each report keeps its own rating for as long as it's open.- feedbackSentiment: [- null as InboxReportFeedbackSentiment | null,- {- rateReport: (_, { sentiment }) => sentiment,- },- ],- // Switching the rating drops an unsent draft so it can't end up attached to a sentiment the- // reader has since changed their mind about.+ savedFeedback: {+ feedbackSaved: (_, { feedback }) => feedback,+ },+ feedbackSubmitting: [false, { setFeedbackSubmitting: (_, { submitting }) => submitting }],feedbackNoteDraft: ['',{setFeedbackNoteDraft: (_, { draft }) => draft,- rateReport: () => '',- submitFeedbackNote: () => '',- },- ],- // The note as sent, so the row can show the reader what went through.- feedbackSentNote: [- null as string | null,- {- submitFeedbackNote: (_, { note }) => note.trim() || null,- rateReport: () => null,- },- ],- feedbackNoteSent: [- false,- {- submitFeedbackNote: () => true,- rateReport: () => false,+ feedbackSaved: () => '',},],feedbackNoteSubmitting: [@@ -1121,6 +1162,31 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([})),selectors({+ feedbackSentiment: [+ (s) => [s.savedFeedback],+ (feedback: SignalReportFeedbackStateApi | null) => feedback?.sentiment ?? null,+ ],+ feedbackSentNote: [+ (s) => [s.savedFeedback],+ (feedback: SignalReportFeedbackStateApi | null) => feedback?.note || null,+ ],+ feedbackNoteSent: [(s) => [s.feedbackSentNote], (note: string | null) => !!note],+ feedbackDisabledReason: [+ (s) => [s.savedFeedback, s.savedFeedbackLoading, s.feedbackSubmitting, s.feedbackNoteSubmitting],+ (+ feedback: SignalReportFeedbackStateApi | null,+ loading: boolean,+ submitting: boolean,+ noteSubmitting: boolean+ ) =>+ loading+ ? 'Loading feedback'+ : submitting || noteSubmitting+ ? 'Saving feedback'+ : !feedback+ ? 'Could not load feedback. Refresh the page to try again.'+ : undefined,+ ],// Mirrors the optimistic override lifecycle: an update is in flight exactly while the// optimistic list is set (cleared once the reload lands or the update fails).isUpdatingReviewers: [@@ -1497,52 +1563,50 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([})}},- rateReport: ({ sentiment, surface }) => {- if (!values.report) {+ rateReport: async ({ sentiment, surface, onSuccess }) => {+ if (!values.report || !values.savedFeedback || values.feedbackSubmitting || values.feedbackNoteSubmitting) {return}- captureInboxReportFeedback({ report: values.report, sentiment, surface })- // Best-effort server-side record of the bare rating: consumption evidence the scout- // inactivity sweep reads, so rating a report keeps its scout from being auto-paused.- // The analytics event above stays the durable record of the rating itself.- void signalsReportsFeedbackCreate(String(teamLogic.values.currentTeamId), values.report.id, {- sentiment,- }).catch(() => {})+ actions.setFeedbackSubmitting(true)+ try {+ await signalsReportsFeedbackCreate(String(teamLogic.values.currentTeamId), props.reportId, {+ sentiment,+ })+ actions.feedbackSaved({ sentiment, note: '' })+ onSuccess?.()+ if (sentiment) {+ captureInboxReportFeedback({ report: values.report, sentiment, surface })+ } else {+ captureInboxReportAction({ report: values.report, actionType: 'clear_feedback', surface })+ }+ } catch {+ lemonToast.error('Could not save your feedback. Please try again.')+ } finally {+ actions.setFeedbackSubmitting(false)+ }},- // Fires on its own event so the rating stays exactly one `Inbox report feedback` per click.submitFeedbackNote: async ({ note, surface }) => {const trimmed = note.trim()- if (!values.report || !values.feedbackSentiment || !trimmed) {- return- }- // Re-entrancy guard: the send button hides on submit, but a double-click within the same- // frame can dispatch this twice before React unmounts it. `leave_note` mints a new row per- // call, so bail before a second POST leaves the scout a duplicate steering note. The flag- // resets in `finally` so a revised note (after re-rating) can still submit, and the Send- // button shows it as a loading state in the meantime.- if (values.feedbackNoteSubmitting) {+ if (+ !values.report ||+ !values.feedbackSentiment ||+ !trimmed ||+ values.feedbackSubmitting ||+ values.feedbackNoteSubmitting+ ) {return}actions.setFeedbackNoteSubmitting(true)const sentiment = values.feedbackSentimenttry {- captureInboxReportFeedbackNote({- report: values.report,+ await signalsReportsFeedbackCreate(String(teamLogic.values.currentTeamId), props.reportId, {sentiment,note: trimmed,- surface,})- // Best-effort: also carry the note into the scout steering channel so the scout that filed- // the report reads it next run. The analytics event above is the durable record, so a- // failure here is swallowed rather than surfaced — the note is already captured.- try {- await signalsReportsFeedbackCreate(String(teamLogic.values.currentTeamId), values.report.id, {- sentiment,- note: trimmed,- })- } catch {- // no-op: forwarding is a convenience on top of the recorded feedback- }+ actions.feedbackSaved({ sentiment, note: trimmed })+ captureInboxReportFeedbackNote({ report: values.report, sentiment, note: trimmed, surface })+ } catch {+ lemonToast.error('Could not save your note. Please try again.')} finally {actions.setFeedbackNoteSubmitting(false)}@@ -1862,6 +1926,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([afterMount(({ actions, props, values, cache }) => {// `loadReportTasks` is cascaded from `loadReportArtefactsSuccess`, so it isn't called here.+ actions.loadFeedback()actions.loadReportArtefacts()actions.loadReportSignals()actions.loadAvailableReviewers()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f12330230930..939b30103759 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101009,18 +101009,6 @@ export namespace Schemas {channel_id: string;}- /**- * * `positive` - positive- * * `negative` - negative- */- export type SentimentEnum = typeof SentimentEnum[keyof typeof SentimentEnum];--- export const SentimentEnum = {- Positive: 'positive',- Negative: 'negative',- } as const;-export interface ServiceAccountAccessUpdate {/** Gateway server to share or stop sharing. */gateway_server_id: string;@@ -101486,12 +101474,24 @@ export namespace Schemas {report_id: string;}+ /**+ * * `positive` - positive+ * * `negative` - negative+ */+ export type SignalReportFeedbackSentimentEnum = typeof SignalReportFeedbackSentimentEnum[keyof typeof SignalReportFeedbackSentimentEnum];+++ export const SignalReportFeedbackSentimentEnum = {+ Positive: 'positive',+ Negative: 'negative',+ } as const;+export interface SignalReportFeedbackRequest {- /** The rating left on the report: 'positive' (thumbs up) or 'negative' (thumbs down).+ /** The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.** * `positive` - positive* * `negative` - negative */- sentiment: SentimentEnum;+ sentiment: SignalReportFeedbackSentimentEnum | null;/*** Free-form note explaining the rating. Capped at 4000 characters. Optional — a bare thumb carries none. When present and the report was authored by a scout, the note is forwarded to that scout as a steering note.* @maxLength 4000@@ -101504,6 +101504,16 @@ export namespace Schemas {forwarded: boolean;}+ export interface SignalReportFeedbackState {+ /** The report rating: 'positive' (thumbs up), 'negative' (thumbs down), or null to clear it.+ *+ * * `positive` - positive+ * * `negative` - negative */+ sentiment: SignalReportFeedbackSentimentEnum | null;+ /** The current user's saved note, or an empty string. */+ note: string;+ }+export interface SignalReportMergeRequest {/*** Ids of the duplicate reports to fold into this one (1–10). Each must be a live report in this project: a resolved, archived or deleted report is rejected with 409, as is the survivor's own id. Duplicates in the list are de-duplicated. The whole merge applies or none of it does.