: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(workflows): show suggestions on the workflow page (#107802)
Daniel Marchukfdbb142b0165
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 6039306f979e..509010288a05 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -16,8 +16,9 @@ from django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.signing import BadSignature, SignatureExpired, TimestampSignerfrom django.db import IntegrityError, models, transaction-from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery+from django.db.models import Count, Exists, OuterRef, Q, QuerySet, Subqueryfrom django.db.models.expressions import RawSQL+from django.db.models.functions import Coalescefrom django.http import Http404, HttpResponsefrom django.utils import timezonefrom django.utils.dateparse import parse_datetime@@ -2674,6 +2675,12 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod"with the publish endpoint or throw it away with discard_draft."),)+ pending_suggestions = serializers.SerializerMethodField(+ help_text="How many suggested changes are waiting for a person on this workflow. Counted on the list only."+ )+ suggestions_enabled = serializers.SerializerMethodField(+ help_text="Whether someone turned suggestions on for this workflow. Read on the list only."+ )class Meta:model = HogFlow@@ -2702,6 +2709,8 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod"billable_action_types","user_access_level","last_run",+ "pending_suggestions",+ "suggestions_enabled",]read_only_fields = fields@@ -2718,6 +2727,16 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Modlast_run = last_runs.get(instance.id)return HogFlowLastRunSerializer(last_run).data if last_run else None+ @extend_schema_field(serializers.IntegerField(allow_null=True))+ def get_pending_suggestions(self, hog_flow: HogFlow) -> int | None:+ # Annotated on the list queryset only; the detail serializer leaves it out.+ return getattr(hog_flow, "pending_suggestions", None)++ @extend_schema_field(serializers.BooleanField(allow_null=True))+ def get_suggestions_enabled(self, hog_flow: HogFlow) -> bool | None:+ # A workflow with suggestions on but none waiting is still worth telling apart in the list.+ return getattr(hog_flow, "suggestions_enabled", None)+def to_representation(self, instance):# Never return secret function inputs. Replace each set secret with the {"secret": True}# presence marker in the live actions and, when present, the staged draft's actions. Values@@ -4937,7 +4956,29 @@ class HogFlowViewSet(if self.action == "list":# `id` breaks ties so LIMIT/OFFSET paging stays stable: rows sharing an updated_at can# otherwise repeat on one page and never appear on another.- queryset = queryset.order_by("-updated_at", "-id")++ pending = (+ WorkflowProposal.objects.filter(hog_flow=OuterRef("pk"), status=WorkflowProposal.Status.SUGGESTED)+ .order_by()+ .values("hog_flow")+ .annotate(count=Count("id"))+ .values("count")+ )+ queryset = queryset.annotate(+ pending_suggestions=Coalesce(Subquery(pending), 0),+ suggestions_enabled=Exists(+ HogFlowOptimization.objects.filter(hog_flow=OuterRef("pk"), enabled=True).values("pk")+ ),+ )+ # A suggestion waits on a person, so the page that shows them sorts it above recency. Every+ # other reader of this list — the MCP tool, any other surface — keeps recency, or a stale+ # workflow with one suggestion would push a fresh one off their first page.+ # `id` breaks ties so LIMIT/OFFSET paging stays stable: rows sharing an updated_at can+ # otherwise repeat on one page and never appear on another.+ if self.request.GET.get("suggestions_first") in ("true", "1"):+ queryset = queryset.order_by("-pending_suggestions", "-updated_at", "-id")+ else:+ queryset = queryset.order_by("-updated_at", "-id")created_by = self.request.GET.get("created_by")if created_by:diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pyindex 5c5585e0dbb1..3cd2bc107717 100644--- a/products/workflows/backend/tests/api/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -475,6 +475,30 @@ class TestWorkflowProposals(APIBaseTest):assert draft["exit_condition"] == "exit_only_at_end"assert {action["name"] for action in draft["actions"]} >= {"renamed"}+ def test_the_workflow_list_counts_what_is_waiting(self, _mock_flag):+ flow_id = self._create_active_flow()+ other_id = self._create_active_flow()+ self._propose(flow_id, source_id="waiting:1")+ self._propose(flow_id, source_id="waiting:2")+ rejected = self._propose(flow_id, source_id="waiting:3")+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{rejected['id']}/reject/", {})++ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/?suggestions_first=true").json()["results"]+ # Something waiting on a person sorts above the workflow edited most recently, but only for+ # the page that asks: every other reader keeps recency.+ assert listed[0]["id"] == flow_id+ recency = self.client.get(f"/api/projects/{self.team.id}/hog_flows/").json()["results"]+ assert recency[0]["id"] == other_id+ counts = {item["id"]: item["pending_suggestions"] for item in listed}+ assert counts[flow_id] == 2+ assert counts[other_id] == 0+ # A workflow with suggestions on but none waiting still reads as self-improving in the list.+ enabled = {item["id"]: item["suggestions_enabled"] for item in listed}+ assert enabled[flow_id] is True+ assert enabled[other_id] is True+ detail = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()+ assert "pending_suggestions" not in detail+def test_the_evidence_step_must_be_one_the_workflow_has(self, _mock_flag):flow_id = self._create_active_flow()response = self.client.post(diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 418007590927..de9b480ad762 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -179,7 +179,7 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {selfOptimisingEnabled? {label: <WorkflowSuggestionsTabLabel id={workflowSceneProps.id!} />,- key: 'suggestions',+ key: 'self-driving',content: <WorkflowSuggestions id={workflowSceneProps.id!} />,}: null,diff --git a/products/workflows/frontend/Workflows/WorkflowsTable.tsx b/products/workflows/frontend/Workflows/WorkflowsTable.tsxindex 3222ab3ef6d7..cb049c676017 100644--- a/products/workflows/frontend/Workflows/WorkflowsTable.tsx+++ b/products/workflows/frontend/Workflows/WorkflowsTable.tsx@@ -6,6 +6,7 @@ import { LemonCheckbox, LemonDivider, LemonInput, LemonSelect, LemonTag, Link, Timport { AccessControlAction } from 'lib/components/AccessControlAction'import { AppMetricsSparkline } from 'lib/components/AppMetrics/AppMetricsSparkline'import { MemberSelect } from 'lib/components/MemberSelect'+import { FEATURE_FLAGS } from 'lib/constants'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { More } from 'lib/lemon-ui/LemonButton/More'@@ -13,6 +14,7 @@ import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/Leimport { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { capitalizeFirstLetter } from 'lib/utils/strings'import { urls } from 'scenes/urls'@@ -107,6 +109,8 @@ function WorkflowActionsSummary({ workflow }: { workflow: HogFlow }): JSX.Elemen}export function WorkflowsTable(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const selfOptimisingEnabled = !!featureFlags[FEATURE_FLAGS.SELF_OPTIMISING_WORKFLOWS]const logic = workflowsLogic()const {workflowsLoading,@@ -185,7 +189,27 @@ export function WorkflowsTable(): JSX.Element {) : (<LemonTableLinkto={urls.workflow(item.id, 'workflow')}- title={item.name}+ title={+ <span className="flex items-center gap-2 flex-wrap">+ {item.name}+ {selfOptimisingEnabled &&+ item.status === 'active' &&+ item.suggestions_enabled && (+ // Reads only: the row link already renders an anchor, and an+ // interactive element inside it is unreachable by keyboard.+ <LemonTag+ type={item.pending_suggestions ? 'completion' : 'option'}+ data-attr="workflow-list-suggestions"+ >+ {!item.pending_suggestions+ ? 'Self-driving'+ : item.pending_suggestions === 1+ ? '1 suggestion'+ : `${item.pending_suggestions} suggestions`}+ </LemonTag>+ )}+ </span>+ }description={item.description}truncateDescription/>diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowStagedSuggestion.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowStagedSuggestion.tsxnew file mode 100644index 000000000000..080fd91df158--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowStagedSuggestion.tsx@@ -0,0 +1,61 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import type { WorkflowProposalApi } from '../../generated/api.schemas'+import { workflowLogic } from '../workflowLogic'++export function WorkflowStagedSuggestion({ id, proposal }: { id: string; proposal: WorkflowProposalApi }): JSX.Element {+ const { draftActionPending, publishDisabledReason, workflowUserAccessLevel } = useValues(workflowLogic({ id }))+ const { publishDraft } = useActions(workflowLogic({ id }))+ const approver = proposal.resolved_by?.first_name || proposal.resolved_by?.email+ return (+ <div className="border rounded p-3 bg-surface-primary flex items-center gap-3 flex-wrap">+ <div className="flex flex-col gap-1 grow">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold">{proposal.title}</span>+ <LemonTag type="highlight">Staged as draft</LemonTag>+ </div>+ <span className="text-xs text-secondary">+ Approved{approver ? ` by ${approver}` : ''}{' '}+ {proposal.resolved_at && <TZLabel time={proposal.resolved_at} />}. It is the workflow's draft now;+ publish the draft to make it live.+ </span>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ data-attr="workflow-suggestion-open-draft"+ onClick={() => router.actions.push(urls.workflow(id, 'workflow'))}+ >+ Open draft+ </LemonButton>+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ {({ disabledReason }) => (+ <LemonButton+ type="primary"+ size="small"+ data-attr="workflow-suggestion-publish"+ loading={draftActionPending === 'publish'}+ disabledReason={disabledReason ?? publishDisabledReason}+ // The same publish the header runs, preview and confirm included.+ onClick={() => publishDraft()}+ >+ Publish+ </LemonButton>+ )}+ </AccessControlAction>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsxindex 2df1f3ae963e..eab17e5a374b 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx@@ -1,10 +1,13 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { Spinner } from '@posthog/lemon-ui'+import { LemonButton, Spinner } from '@posthog/lemon-ui'import { WorkflowAppliedOutcome } from './WorkflowAppliedOutcome'import { workflowProposalsLogic } from './workflowProposalsLogic'+import { WorkflowStagedSuggestion } from './WorkflowStagedSuggestion'import { WorkflowSuggestionCard } from './WorkflowSuggestionCard'+import { WorkflowSuggestionsIntroduction } from './WorkflowSuggestionsIntroduction'+import { WorkflowSuggestionsSwitch } from './WorkflowSuggestionsSwitch'function SuggestionsOffNotice(): JSX.Element {return (@@ -18,6 +21,20 @@ function SuggestionsOffNotice(): JSX.Element {)}+function SuggestionsUnreadableList({ onRetry }: { onRetry: () => void }): JSX.Element {+ return (+ <div className="flex flex-col items-start gap-2">+ <h3 className="mb-0">Could not load this workflow's suggestions</h3>+ <p className="mb-0 text-secondary">+ Nothing changed. Whatever was filed is still there, waiting to be read.+ </p>+ <LemonButton type="secondary" onClick={onRetry}>+ Try again+ </LemonButton>+ </div>+ )+}+function SuggestionsUnreadableNotice(): JSX.Element {return (<div className="flex flex-col gap-2">@@ -32,6 +49,7 @@ function SuggestionsUnreadableNotice(): JSX.Element {export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {const {pendingProposals,+ approvedProposals,appliedProposals,outcomes,optimizationEnabled,@@ -39,16 +57,34 @@ export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {optimizationLoading,optimizationUnreadable,proposalsResponse,+ approvedResponse,+ appliedResponse,proposalsResponseLoading,+ approvedResponseLoading,+ appliedResponseLoading,+ listsUnreadable,} = useValues(workflowProposalsLogic({ id }))+ const { reloadLists } = useActions(workflowProposalsLogic({ id }))const measuredApplied = appliedProposals.filter((proposal) => outcomes[proposal.id]?.after)+ // Each list answers separately; "nothing here" is unknown until all have.+ const listsUnknown = proposalsResponse === null || approvedResponse === null || appliedResponse === null+ const listsSettling =+ proposalsResponseLoading ||+ approvedResponseLoading ||+ appliedResponseLoading ||+ appliedProposals.some((proposal) => !outcomes[proposal.id])- if (optimization === null && optimizationLoading) {+ if ((optimization === null && optimizationLoading) || (optimizationEnabled && listsUnknown && !listsUnreadable)) {return <Spinner />}- const nothingFiled = pendingProposals.length === 0 && measuredApplied.length === 0+ if (optimizationEnabled && listsUnknown) {+ return <SuggestionsUnreadableList onRetry={reloadLists} />+ }++ const nothingFiled = pendingProposals.length === 0 && approvedProposals.length === 0 && measuredApplied.length === 0+// A failed read leaves the setting unknown, so it cannot stand in for "off".const notice = optimizationUnreadable ? (<SuggestionsUnreadableNotice />@@ -56,8 +92,16 @@ export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {<SuggestionsOffNotice />) : null- if (notice && nothingFiled) {- return notice+ if (nothingFiled) {+ // Off with nothing filed is the introduction; an unreadable setting keeps its own notice, since it+ // is not "off". Either one with a queue still shows the queue, which the server keeps resolvable.+ if (notice) {+ return optimizationUnreadable ? notice : <WorkflowSuggestionsIntroduction id={id} enabled={false} />+ }++ if (!listsSettling) {+ return <WorkflowSuggestionsIntroduction id={id} enabled />+ }}return (@@ -65,21 +109,39 @@ export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {{/* Off, or unreadable, still leaves what was already filed for someone to resolve. */}{notice}<div className="flex flex-col gap-2">- <h3 className="mb-0">Waiting for you</h3>- {proposalsResponse === null && proposalsResponseLoading ? (- <Spinner />- ) : pendingProposals.length === 0 ? (+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="mb-0">Waiting for you</h3>+ <WorkflowSuggestionsSwitch id={id} />+ </div>+ {pendingProposals.length === 0 ? (<p className="mb-0 text-secondary">Nothing to review. PostHog reads this workflow's metrics on a schedule and files a suggestionhere when it finds a change worth making. Nothing reaches anyone until you approve a suggestionand publish it.</p>) : (- pendingProposals.map((proposal) => (- <WorkflowSuggestionCard key={proposal.id} id={id} proposal={proposal} />- ))+ <>+ {/* The queue renders whole rather than paging, so say when it did not fit. */}+ {(proposalsResponse?.count ?? 0) > pendingProposals.length && (+ <p className="mb-0 text-secondary">+ Showing the newest {pendingProposals.length} of {proposalsResponse?.count}. Resolve some+ to see the rest.+ </p>+ )}+ {pendingProposals.map((proposal) => (+ <WorkflowSuggestionCard key={proposal.id} id={id} proposal={proposal} />+ ))}+ </>)}</div>+ {approvedProposals.length > 0 && (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Staged as draft</h3>+ {approvedProposals.map((proposal) => (+ <WorkflowStagedSuggestion key={proposal.id} id={id} proposal={proposal} />+ ))}+ </div>+ )}{measuredApplied.length > 0 && (<div className="flex flex-col gap-2"><h3 className="mb-0">Applied</h3>diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsIntroduction.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsIntroduction.tsxnew file mode 100644index 000000000000..bbf41cf98b9e--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsIntroduction.tsx@@ -0,0 +1,42 @@+import * as research from '@posthog/brand/hoggies/png/research'+import * as stampApproved from '@posthog/brand/hoggies/png/stamp-approved'++import { pngHoggie } from 'lib/brand/hoggies'+import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'++import { WorkflowSuggestionsSwitch } from './WorkflowSuggestionsSwitch'++const HedgehogStampApproved = pngHoggie(stampApproved)+const HedgehogResearch = pngHoggie(research)++const DOCS_URL = 'https://posthog.com/docs/workflows/suggestions'++export function WorkflowSuggestionsIntroduction({ id, enabled }: { id: string; enabled: boolean }): JSX.Element {+ if (!enabled) {+ return (+ <ProductIntroduction+ thingName="suggestion"+ titleOverride="Let PostHog suggest improvements"+ description="PostHog reads how this workflow performs, such as how many people open and click each email, and suggests one concrete change when a step underperforms. Nothing reaches anyone until you approve a suggestion and publish it."+ actionElementOverride={<WorkflowSuggestionsSwitch id={id} />}+ docsURL={DOCS_URL}+ customHog={HedgehogStampApproved}+ hogLayout="responsive"+ useMainContentContainerQueries+ />+ )+ }++ return (+ <ProductIntroduction+ thingName="suggestion"+ titleOverride="Watching this workflow"+ description="PostHog reads this workflow's metrics once a day and files a suggestion here when it finds a change worth making. It waits for a version to collect a couple of days of opens before judging it, so a fresh publish takes a few days to read."+ actionElementOverride={<WorkflowSuggestionsSwitch id={id} />}+ docsURL={DOCS_URL}+ customHog={HedgehogResearch}+ hogLayout="responsive"+ useMainContentContainerQueries+ />+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsxindex 9bb6428f2c36..bd90935e5af2 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx@@ -13,7 +13,10 @@ export function WorkflowSuggestionsMenuItem({ id }: { id: string }): JSX.ElementworkflowProposalsLogic({ id }))const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))- const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))+ const { workflowUserAccessLevel, workflow } = useValues(workflowLogic({ id }))+ // Only turning it on needs a live workflow; the server takes `enabled: false` either way. Blocking+ // both would strand an opted-in workflow opted in the moment it is archived.+ const notLive = !!workflow && workflow.status !== 'active' && !optimizationEnabled// A viewer cannot flip it, so the item is inert instead of a request that ends in an error toast.const accessDisabledReason = getAccessControlDisabledReason(@@ -25,7 +28,7 @@ export function WorkflowSuggestionsMenuItem({ id }: { id: string }): JSX.Elementreturn (<SceneMenuBarCheckboxItemchecked={optimizationEnabled}- disabled={optimizationLoading || optimizationUnreadable || !!accessDisabledReason}+ disabled={optimizationLoading || optimizationUnreadable || !!accessDisabledReason || notLive}onCheckedChange={(checked) => setOptimizationEnabled(checked)}data-attr="workflow-menubar-suggest-improvements">diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsxindex f57076dc811b..29ce1bfa3dcf 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsx@@ -16,10 +16,11 @@ export function WorkflowSuggestionsNotice({ id }: { id: string }): JSX.Element |return (<LemonBannertype="info"+ className="shrink-0"action={{children: 'Review','data-attr': 'workflow-suggestions-review',- onClick: () => router.actions.push(urls.workflow(id, 'suggestions')),+ onClick: () => router.actions.push(urls.workflow(id, 'self-driving')),}}>{pendingProposals.length === 1diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsxindex c45583520804..ee24b12fe578 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx@@ -14,7 +14,12 @@ export function WorkflowSuggestionsPanelToggle({ id }: { id: string }): JSX.ElemworkflowProposalsLogic({ id }))const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))- const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))+ const { workflowUserAccessLevel, workflow } = useValues(workflowLogic({ id }))+ // Only turning it on needs a live workflow, so an archived workflow can still be switched off.+ const notLiveReason =+ !!workflow && workflow.status !== 'active' && !optimizationEnabled+ ? 'Suggestions need a live workflow. Enable it first.'+ : undefinedreturn (<AccessControlAction@@ -30,9 +35,10 @@ export function WorkflowSuggestionsPanelToggle({ id }: { id: string }): JSX.Elemchecked={optimizationEnabled}onChange={(checked) => setOptimizationEnabled(checked)}// A failed read must not show "off" for a workflow that may be on.- disabled={optimizationLoading || optimizationUnreadable || !!disabledReason}+ disabled={optimizationLoading || optimizationUnreadable || !!disabledReason || !!notLiveReason}tooltip={disabledReason ??+ notLiveReason ??(optimizationUnreadable? 'Could not read whether suggestions are on for this workflow. Reload the page to try again.': 'PostHog reads how this workflow performs and suggests changes for you to review. Nothing reaches anyone until you approve a suggestion and publish it.')diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsxnew file mode 100644index 000000000000..5dfd62c5f468--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsx@@ -0,0 +1,56 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch, Tooltip } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { workflowLogic } from '../workflowLogic'+import { workflowProposalsLogic } from './workflowProposalsLogic'++export function WorkflowSuggestionsSwitch({ id }: { id: string }): JSX.Element {+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ workflowProposalsLogic({ id })+ )+ const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))+ const { workflowUserAccessLevel, originalWorkflow } = useValues(workflowLogic({ id }))+ // A draft or archived workflow cannot be opted in; the switch stays visible and says why. Turning+ // it off stays available, or archiving a workflow would strand it opted in.+ const notLiveReason =+ originalWorkflow && originalWorkflow.status !== 'active' && !optimizationEnabled+ ? 'Suggestions need a live workflow. Enable it first.'+ : undefined++ return (+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ {({ disabledReason }) => {+ // A failed read leaves the switch showing a default, so acting on it would write from a state+ // nobody read. The panel toggle refuses the same way.+ const unreadableReason = optimizationUnreadable+ ? 'Could not read whether suggestions are on for this workflow. Reload the page to try again.'+ : undefined+ const reason = disabledReason ?? notLiveReason ?? unreadableReason+ // LemonSwitch's own tooltip covers only the knob, so the reason wraps the whole control.+ return (+ <Tooltip title={reason}>+ <div className="flex items-center">+ <LemonSwitch+ bordered+ label="Suggest improvements"+ checked={optimizationEnabled}+ disabled={optimizationLoading || !!reason}+ onChange={(checked) => setOptimizationEnabled(checked)}+ data-attr="workflow-suggestions-enable"+ />+ </div>+ </Tooltip>+ )+ }}+ </AccessControlAction>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsxindex fec507e53f52..6648bc44e852 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsx@@ -1,19 +1,35 @@import { useValues } from 'kea'-import { LemonTag } from '@posthog/lemon-ui'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'+import { workflowLogic } from '../workflowLogic'import { workflowProposalsLogic } from './workflowProposalsLogic'export function WorkflowSuggestionsTabLabel({ id }: { id: string }): JSX.Element {- const { pendingProposals } = useValues(workflowProposalsLogic({ id }))+ const { pendingProposals, optimizationEnabled } = useValues(workflowProposalsLogic({ id }))+ const { workflow } = useValues(workflowLogic({ id }))+ // Archiving leaves the opt-in row enabled, and nothing is watched any more, so the row alone+ // would keep saying "On" for a workflow that cannot produce a suggestion.+ const watching = optimizationEnabled && workflow?.status === 'active'return (<span className="flex items-center gap-1.5">- Suggestions- {pendingProposals.length > 0 && (+ Self-driving+ <LemonTag type="completion" size="small">+ Beta+ </LemonTag>+ {pendingProposals.length > 0 ? (<LemonTag type="completion" size="small">{pendingProposals.length}</LemonTag>+ ) : (+ watching && (+ <Tooltip title="PostHog is watching this workflow and will suggest changes here.">+ <LemonTag type="option" size="small">+ On+ </LemonTag>+ </Tooltip>+ ))}</span>)diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.tsindex e1e3e4bf5ff7..289cce239190 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts@@ -107,6 +107,15 @@ describe('workflowProposalsLogic', () => {}).toDispatchActions(['loadProposalsFailure'])expect(logic.values.pendingProposals.map((p) => p.id)).toEqual([PROPOSAL_ID])+ // Without this the panel cannot tell a failed list from one nobody asked for, and spins forever.+ expect(logic.values.listsUnreadable).toBe(true)++ proposalsListStatus = 200+ await expectLogic(logic, () => {+ logic.actions.reloadLists()+ }).toDispatchActions(['loadProposalsSuccess'])++ expect(logic.values.listsUnreadable).toBe(false)})it('treats the flag-off 404 as an empty queue with no failure', async () => {diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsindex f5963014a926..73a0465e4eff 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts@@ -25,6 +25,9 @@ import { workflowLogic } from '../workflowLogic'// Applied is terminal and each one costs an outcome request, so only the newest few load.const APPLIED_OUTCOME_LIMIT = 3+// Pending and approved both render whole, so ask for more than a workflow can realistically carry+// rather than the server's page size — a second page nobody fetches reads as suggestions vanishing.+const QUEUE_LIMIT = 100export interface WorkflowProposalsLogicProps {id: string@@ -41,8 +44,12 @@ export interface workflowProposalsLogicValues {appliedResponse: PaginatedWorkflowProposalListApi | nullappliedResponseLoading: booleanapproveDisabledReason: string | undefined+ approvedProposals: WorkflowProposalApi[]+ approvedResponse: PaginatedWorkflowProposalListApi | null+ approvedResponseLoading: booleanlastSeenDraftStamp: string | nulllastSeenVersion: number | null+ listsUnreadable: booleanoptimization: HogFlowOptimizationApi | nulloptimizationEnabled: booleanoptimizationLoading: boolean@@ -86,6 +93,21 @@ export interface workflowProposalsLogicActions {appliedResponse: PaginatedWorkflowProposalListApipayload?: any}+ loadApproved: () => any+ loadApprovedFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadApprovedSuccess: (+ approvedResponse: PaginatedWorkflowProposalListApi,+ payload?: any+ ) => {+ approvedResponse: PaginatedWorkflowProposalListApi+ payload?: any+ }loadOptimization: () => anyloadOptimizationFailure: (error: string,@@ -122,6 +144,9 @@ export interface workflowProposalsLogicActions {rejectProposal: (proposalId: string) => {proposalId: string}+ reloadLists: () => {+ value: true+ }removeResolvedProposal: (proposalId: string) => {proposalId: string}@@ -176,6 +201,7 @@ export interface workflowProposalsLogicActions {export interface workflowProposalsLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ approvedProposals: (approvedResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]appliedProposals: (appliedResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]optimizationEnabled: (optimization: HogFlowOptimizationApi | null) => booleanpendingProposals: (proposalsResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]@@ -219,6 +245,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([clearOutcomes: () => ({}),setLastSeen: (version: number | null, draftStamp: string | null) => ({ version, draftStamp }),setOptimizationUnreadable: (unreadable: boolean) => ({ unreadable }),+ reloadLists: true,setOptimizationEnabled: (enabled: boolean) => ({ enabled }),setOutcome: (proposalId: string, outcome: WorkflowProposalOutcomeApi) => ({ proposalId, outcome }),}),@@ -237,6 +264,17 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([}: response,},+ // A list that rejects leaves its response null with nothing loading, which reads the same as+ // "not asked yet". Without this the panel waits on a request that already failed.+ listsUnreadable: [+ false,+ {+ loadProposalsFailure: () => true,+ loadApprovedFailure: () => true,+ loadAppliedFailure: () => true,+ reloadLists: () => false,+ },+ ],resolvingId: [null as string | null,{@@ -284,6 +322,24 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([],}),loaders(({ actions, props, values }) => ({+ approvedResponse: [+ null as PaginatedWorkflowProposalListApi | null,+ {+ loadApproved: async () => {+ try {+ return await hogFlowsProposalsList(String(values.currentTeamIdStrict), props.id, {+ status: 'approved',+ limit: QUEUE_LIMIT,+ })+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ return { count: 0, results: [] }+ }+ throw error+ }+ },+ },+ ],appliedResponse: [null as PaginatedWorkflowProposalListApi | null,{@@ -330,6 +386,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([try {return await hogFlowsProposalsList(String(values.currentTeamIdStrict), props.id, {status: 'suggested',+ limit: QUEUE_LIMIT,})} catch (error) {// 404 is the flag being off; anything else rejects so the loader keeps the last list.@@ -343,6 +400,10 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([],})),selectors({+ approvedProposals: [+ (s) => [s.approvedResponse],+ (response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],+ ],appliedProposals: [(s) => [s.appliedResponse],(response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],@@ -372,6 +433,11 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([],}),listeners(({ actions, props, values }) => ({+ reloadLists: () => {+ actions.loadProposals()+ actions.loadApproved()+ actions.loadApplied()+ },approveProposal: ({ proposalId }) => {if (values.resolvingId !== null || values.approveDisabledReason) {return@@ -414,6 +480,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([actions.removeResolvedProposal(proposalId)workflowLogic({ id: props.id }).actions.loadWorkflow()actions.loadProposals()+ actions.loadApproved()} catch (error) {if (error instanceof ApiError && error.status === 409) {if (error.code === 'proposal_already_resolved') {@@ -507,12 +574,14 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([// The reload below skips a proposal that already has an outcome, so the stale one goes first.actions.clearOutcomes()actions.loadProposals()+ actions.loadApproved()actions.loadApplied()},})),afterMount(({ actions, values }) => {actions.setLastSeen(values.originalWorkflow?.version ?? null, values.originalWorkflow?.draft_updated_at ?? null)actions.loadProposals()+ actions.loadApproved()actions.loadApplied()actions.loadOptimization()}),diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.tsindex 2aa8c3016e97..a1e183739821 100644--- a/products/workflows/frontend/Workflows/workflowSceneLogic.ts+++ b/products/workflows/frontend/Workflows/workflowSceneLogic.ts@@ -8,7 +8,7 @@ import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { ActivityScope, Breadcrumb } from '~/types'-export const WorkflowTabs = ['workflow', 'invocations', 'metrics', 'suggestions', 'assets', 'history'] as const+export const WorkflowTabs = ['workflow', 'invocations', 'metrics', 'self-driving', 'assets', 'history'] as constexport type WorkflowTab = (typeof WorkflowTabs)[number]export interface WorkflowSceneLogicProps {@@ -26,7 +26,7 @@ export interface workflowSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowSceneLogicActions {setCurrentTab: (tab: WorkflowTab) => {- tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'suggestions' | 'workflow'+ tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'self-driving' | 'workflow'}}@@ -105,6 +105,11 @@ export const workflowSceneLogic = kea<workflowSceneLogicType>([router.actions.replace(urls.workflow(id ?? 'new', 'invocations'), searchParams)return}+ // The tab was called 'suggestions' before it was named after self-driving.+ if (tab === 'suggestions') {+ router.actions.replace(urls.workflow(id ?? 'new', 'self-driving'), searchParams)+ return+ }if (tab !== values.currentTab) {actions.setCurrentTab(tab as WorkflowTab)}diff --git a/products/workflows/frontend/Workflows/workflowsLogic.ts b/products/workflows/frontend/Workflows/workflowsLogic.tsindex a4399ebe1faa..4375238fd7f3 100644--- a/products/workflows/frontend/Workflows/workflowsLogic.ts+++ b/products/workflows/frontend/Workflows/workflowsLogic.ts@@ -71,6 +71,7 @@ interface WorkflowsListParams {created_by?: stringtype?: HogFlowListType[]trigger?: string+ suggestions_first?: booleanlimit: numberoffset: number}@@ -427,6 +428,9 @@ export const workflowsLogic = kea<workflowsLogicType>([type: filters.type !== 'all' ? [filters.type] : WORKFLOWS_PAGE_TYPES,// The API filters triggers by JSON containment, so the type goes over as a JSON object.trigger: filters.triggerType !== 'all' ? JSON.stringify({ type: filters.triggerType }) : undefined,+ // Only this page sorts a waiting suggestion above recency; every other reader of the+ // list keeps recency, so one stale workflow cannot push fresh ones off their first page.+ suggestions_first: true,limit: WORKFLOWS_PER_PAGE,offset: filters.page ? (filters.page - 1) * WORKFLOWS_PER_PAGE : 0,}),diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 8c26d8bf0c31..bc483e15ee4c 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -396,6 +396,16 @@ export interface HogFlowMinimalApi {readonly user_access_level: string | null/** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */readonly last_run: HogFlowLastRunApi | null+ /**+ * How many suggested changes are waiting for a person on this workflow. Counted on the list only.+ * @nullable+ */+ readonly pending_suggestions: number | null+ /**+ * Whether someone turned suggestions on for this workflow. Read on the list only.+ * @nullable+ */+ readonly suggestions_enabled: boolean | null}export interface PaginatedHogFlowMinimalListApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2ef01e9430da..618bb0929220 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -52422,6 +52422,16 @@ export namespace Schemas {readonly user_access_level: string | null;/** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */readonly last_run: HogFlowLastRun | null;+ /**+ * How many suggested changes are waiting for a person on this workflow. Counted on the list only.+ * @nullable+ */+ readonly pending_suggestions: number | null;+ /**+ * Whether someone turned suggestions on for this workflow. Read on the list only.+ * @nullable+ */+ readonly suggestions_enabled: boolean | null;}export interface HogFlowOptimization {