: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 pending suggestions on the workflow page (#91710)
Daniel Marchukd90b6510762b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 99b96481ff17..4321204b1f4a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -229,6 +229,7 @@ export const FEATURE_FLAGS = {SCOUTS_SUGGESTIONS_UI: 'scouts-suggestions-ui', // owner: #team-self-driving, gates the pre-computed scout suggestions strip on the inbox scouts tab (the producer is the separate signals-scout-suggestions flag)SELF_DRIVING_FREE_TRIAL: 'self-driving-free-trial', // owner: #team-self-driving, the org is on a Self-driving free trial: reports only, no pull requests (also checked server-side)SELF_DRIVING_QUOTA_ENFORCEMENT: 'self-driving-quota-enforcement', // owner: #team-self-driving, gates self-driving PR-limit enforcement (also checked server-side)+ SELF_OPTIMISING_WORKFLOWS: 'self-optimising-workflows', // owner: #team-workflows, gates agent-suggested workflow changes (also checked server-side)SESSION_REPLAY_BACKEND_LOGS: 'session-replay-backend-logs', // owner: #team-replaySESSION_REPLAY_DOCTOR: 'session-replay-doctor', // owner: #team-replaySETTINGS_BOUNCE_RATE_PAGE_VIEW_MODE: 'settings-bounce-rate-page-view-mode', // owner: #team-web-analytics@@ -527,9 +528,9 @@ export const FEATURE_FLAGS = {TASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-aiTASKS: 'tasks', // owner: #team-ai-observabilityTASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observability+ TAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra, asks the decision model which core events an events search with no results describes, then suggests them in the empty stateTAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. Every arm promotes the predicted group on the All tab; only banner also suggests the right tab- TAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra, asks the decision model which core events an events search with no results describes, then suggests them in the empty stateTEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cardsTOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 1132c4add39d..2982671831bc 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -7,8 +7,10 @@ import { SpinnerOverlay } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { NotFound } from 'lib/components/NotFound'+import { FEATURE_FLAGS } from 'lib/constants'import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'@@ -22,6 +24,9 @@ import { ActivityScope } from '~/types'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'import { NewWorkflowAgent } from './NewWorkflowAgent'import { newWorkflowLogic } from './newWorkflowLogic'+import { WorkflowSuggestions } from './suggestions/WorkflowSuggestions'+import { WorkflowSuggestionsNotice } from './suggestions/WorkflowSuggestionsNotice'+import { WorkflowSuggestionsTabLabel } from './suggestions/WorkflowSuggestionsTabLabel'import { Workflow } from './Workflow'import {EMAIL_EDITOR_AGENT_HEADLINES,@@ -88,6 +93,9 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {useMemo(() => ({ workflow, id: workflowSceneProps.id ?? 'new' }), [workflow, workflowSceneProps.id]),500)+ const { featureFlags } = useValues(featureFlagLogic)+ const selfOptimisingEnabled = !!featureFlags[FEATURE_FLAGS.SELF_OPTIMISING_WORKFLOWS]+ const isSavedWorkflow = !!props.id && props.id !== 'new'const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)const { aiComposerAvailable } = useValues(newWorkflowLogic)// Deep links that carry a starting point, and the escape hatch, land in the editor instead (see `aiComposerAvailable`).@@ -168,6 +176,13 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {*/content: <WorkflowMetrics id={workflowSceneProps.id!} />,},+ selfOptimisingEnabled+ ? {+ label: <WorkflowSuggestionsTabLabel id={workflowSceneProps.id!} />,+ key: 'suggestions',+ content: <WorkflowSuggestions id={workflowSceneProps.id!} />,+ }+ : null,{label: 'Assets',key: 'assets',@@ -196,17 +211,21 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {},]+ // A deep link to a tab the flag hides would leave LemonTabs with no active tab and a blank page.+ const activeTab = tabs.some((tab) => tab?.key === currentTab) ? currentTab : 'workflow'+return (<SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene"><BindLogic logic={workflowLogic} props={workflowProps}><WorkflowSceneHeader {...props} /><WorkflowEmailPauseBanner />+ {selfOptimisingEnabled && isSavedWorkflow && <WorkflowSuggestionsNotice id={props.id!} />}{/* Only show Logs and Metrics tabs if the workflow has already been created */}{!props.id || props.id === 'new' ? (<Workflow {...workflowProps} />) : (<LemonTabs- activeKey={currentTab}+ activeKey={activeTab}onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}tabs={tabs}sceneInsetdiff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsxindex 433758121fb5..89cff9840462 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx@@ -216,6 +216,38 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificati}}+ if (logItem.activity == 'proposal_approved') {+ return {+ summary: activityLogSummary(+ logItem,+ 'Approved a suggested change',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> approved a suggested change into the staged draft of the{' '}+ {objectNoun}: {nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)}+ </>+ ),+ }+ }++ if (logItem.activity == 'proposal_rejected') {+ return {+ summary: activityLogSummary(+ logItem,+ 'Rejected a suggested change',+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)+ ),+ description: (+ <>+ <ActivityLogUserName logItem={logItem} /> rejected a suggested change to the {objectNoun}:{' '}+ {nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)}+ </>+ ),+ }+ }+if (logItem.activity == 'draft_discarded') {return {summary: activityLogSummary(diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsxnew file mode 100644index 000000000000..b99733983fb7--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx@@ -0,0 +1,54 @@+import { LemonTag } from '@posthog/lemon-ui'++import type { WorkflowProposalApi, WorkflowProposalOutcomeApi } from '../../generated/api.schemas'+import { WorkflowMetricReading } from './WorkflowMetricReading'++export function WorkflowAppliedOutcome({+ proposal,+ outcome,+}: {+ proposal: WorkflowProposalApi+ outcome: WorkflowProposalOutcomeApi+}): JSX.Element {+ return (+ <div className="@container border rounded p-3 bg-surface-primary flex flex-col gap-2">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold">{proposal.title}</span>+ <LemonTag type="success">Applied as version {proposal.applied_version}</LemonTag>+ </div>+ <p className="mb-0 text-secondary text-sm">+ Measured over {outcome.window}, before and after. Different periods, so treat a difference as a signal+ to look closer, not as proof.+ </p>+ <div className="grid grid-cols-1 @md:grid-cols-2 gap-3 text-sm">+ {(['before', 'after'] as const).map((side) => {+ const reading = outcome[side]+ return (+ <div key={side} className="flex flex-col gap-1">+ <span className="font-semibold">+ {side === 'before' ? 'Before' : 'After'}+ {reading ? ` (v${reading.version})` : ''}+ </span>+ {reading ? (+ <>+ <WorkflowMetricReading reading={reading.target} />+ <WorkflowMetricReading reading={reading.click_through} />+ {reading.guardrails.map((guardrail) => (+ <WorkflowMetricReading key={guardrail.metric} reading={guardrail} />+ ))}+ </>+ ) : (+ <span className="text-secondary">No data</span>+ )}+ </div>+ )+ })}+ </div>+ {outcome.unavailable_guardrails.length > 0 && (+ <span className="text-xs text-secondary">+ Not measured: {outcome.unavailable_guardrails.join(', ')}+ </span>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsxnew file mode 100644index 000000000000..08e1f862d467--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsx@@ -0,0 +1,18 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import type { WorkflowProposalMetricApi } from '../../generated/api.schemas'+import { MIN_EVIDENCE_SAMPLE, formatValue } from './suggestionEvidence'++export function WorkflowMetricReading({ reading }: { reading: WorkflowProposalMetricApi }): JSX.Element {+ return (+ <span className="flex items-center gap-1 flex-wrap">+ {reading.metric} {formatValue(reading.value, 'rate') ?? 'no data'}+ <span className="text-secondary">(n={reading.n})</span>+ {reading.below_minimum_sample && (+ <Tooltip title={`Under ${MIN_EVIDENCE_SAMPLE} observations. Not enough to call this a result.`}>+ <LemonTag type="warning">Too little data</LemonTag>+ </Tooltip>+ )}+ </span>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsxnew file mode 100644index 000000000000..3a70b90f4f92--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx@@ -0,0 +1,96 @@+import { useActions, useValues } from 'kea'++import { IconBolt } from '@posthog/icons'+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import type { WorkflowProposalApi } from '../../generated/api.schemas'+import { workflowLogic } from '../workflowLogic'+import { workflowProposalsLogic } from './workflowProposalsLogic'+import { WorkflowSuggestionDetails } from './WorkflowSuggestionDetails'+import { WorkflowSuggestionEvidence } from './WorkflowSuggestionEvidence'++export function WorkflowSuggestionCard({ id, proposal }: { id: string; proposal: WorkflowProposalApi }): JSX.Element {+ const { resolvingId, resolvingAction, approveDisabledReason } = useValues(workflowProposalsLogic({ id }))+ const { approveProposal, rejectProposal } = useActions(workflowProposalsLogic({ id }))+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))++ const busyElsewhere = resolvingId !== null && resolvingId !== proposal.id++ return (+ <div className="border rounded p-3 bg-surface-primary flex flex-col gap-2">+ <div className="flex items-start gap-2 flex-wrap">+ <IconBolt className="text-lg shrink-0 mt-0.5" />+ <div className="flex flex-col gap-1 grow">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold">{proposal.title}</span>+ <Tooltip title="PostHog's scout is the only thing that files a suggestion.">+ <LemonTag type="highlight">Suggested by PostHog</LemonTag>+ </Tooltip>+ {proposal.is_stale && (+ <Tooltip title="Someone changed the same step since this was suggested. Approving it would undo their edit, so ask for a fresh suggestion.">+ <LemonTag type="warning">Out of date</LemonTag>+ </Tooltip>+ )}+ </div>+ <p className="mb-0 text-secondary">{proposal.rationale}</p>+ <WorkflowSuggestionEvidence evidence={proposal.evidence} />+ <span className="text-xs text-secondary">+ Suggested <TZLabel time={proposal.created_at} /> against version {proposal.base_version}+ </span>+ </div>+ <div className="flex items-center gap-2 shrink-0 ml-auto">+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ <LemonButton+ type="secondary"+ size="small"+ data-attr="workflow-suggestion-reject"+ onClick={() => rejectProposal(proposal.id)}+ loading={resolvingId === proposal.id && resolvingAction === 'reject'}+ disabledReason={busyElsewhere ? 'Another suggestion is being resolved' : undefined}+ >+ Reject+ </LemonButton>+ </AccessControlAction>+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ <LemonButton+ type="primary"+ size="small"+ data-attr="workflow-suggestion-approve"+ onClick={() => approveProposal(proposal.id)}+ loading={resolvingId === proposal.id && resolvingAction === 'approve'}+ disabledReason={+ busyElsewhere ? 'Another suggestion is being resolved' : approveDisabledReason+ }+ >+ Approve as draft+ </LemonButton>+ </AccessControlAction>+ </div>+ </div>+ <LemonCollapse+ size="small"+ panels={[+ {+ key: 'details',+ header: 'What it changes and why',+ content: <WorkflowSuggestionDetails proposal={proposal} />,+ },+ ]}+ />+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsxnew file mode 100644index 000000000000..710c4c1a38de--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx@@ -0,0 +1,26 @@+import type { WorkflowProposalApi } from '../../generated/api.schemas'++export function WorkflowSuggestionDetails({ proposal }: { proposal: WorkflowProposalApi }): JSX.Element {+ const changedFields = Object.keys(proposal.content)++ return (+ <div className="flex flex-col gap-2 text-sm">+ <div>+ <span className="font-semibold">Workflow fields it changes: </span>+ {changedFields.length ? changedFields.join(', ') : 'none'}+ </div>+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Evidence</span>+ <pre className="text-xs bg-surface-secondary rounded p-2 overflow-x-auto mb-0">+ {JSON.stringify(proposal.evidence, null, 2)}+ </pre>+ </div>+ {proposal.source_id && (+ <div>+ <span className="font-semibold">Source: </span>+ {proposal.source_id}+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsxnew file mode 100644index 000000000000..33a3948e885f--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx@@ -0,0 +1,62 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { MIN_EVIDENCE_SAMPLE, formatValue, readGuardrails, readUnit } from './suggestionEvidence'++export function WorkflowSuggestionEvidence({ evidence }: { evidence: Record<string, unknown> }): JSX.Element | null {+ const metric = typeof evidence.metric === 'string' ? evidence.metric : null+ if (!metric) {+ return null+ }+ const unit = readUnit(evidence.unit)+ const current = formatValue(evidence.current_value, unit)+ const target = formatValue(evidence.target_value, unit)+ const window = typeof evidence.window === 'string' ? evidence.window : null+ const sample = typeof evidence.n === 'number' ? evidence.n : null+ const guardrails = readGuardrails(evidence)+ const unavailable = Array.isArray(evidence.guardrails_unavailable)+ ? evidence.guardrails_unavailable.filter((name): name is string => typeof name === 'string')+ : []+ const lowSample = sample !== null && sample < MIN_EVIDENCE_SAMPLE++ return (+ <div className="flex flex-col gap-1 text-sm">+ <span className="flex items-center gap-2 flex-wrap">+ <span>+ {metric}: {current ?? 'no data'}+ {target ? `, target ${target}` : ''}+ {window ? ` over ${window}` : ''}+ {sample !== null ? ` (${sample} observations)` : ''}+ </span>+ {sample === null && (+ <Tooltip title="This suggestion did not say how many observations its number came from, so there is no way to tell a result from noise.">+ <LemonTag type="warning">No sample size</LemonTag>+ </Tooltip>+ )}+ {lowSample && (+ <Tooltip+ title={`Under ${MIN_EVIDENCE_SAMPLE} observations. Treat this as a hunch to check, not a finding.`}+ >+ <LemonTag type="warning">Too little data</LemonTag>+ </Tooltip>+ )}+ </span>+ {guardrails.length > 0 && (+ <span className="text-secondary">+ Alongside:{' '}+ {guardrails+ .map(+ (guardrail) =>+ `${guardrail.metric} ${formatValue(guardrail.value, readUnit(guardrail.unit)) ?? 'no data'}`+ )+ .join(', ')}+ {unavailable.length > 0 ? `. Not measured: ${unavailable.join(', ')}` : ''}+ </span>+ )}+ {guardrails.length === 0 && (+ <Tooltip title="No counter-metrics were sent with this suggestion, so a change that lifts the target by harming something else would not show here.">+ <LemonTag type="warning">No counter-metrics</LemonTag>+ </Tooltip>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsxnew file mode 100644index 000000000000..74f8610cd1da--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx@@ -0,0 +1,44 @@+import { useValues } from 'kea'++import { Spinner } from '@posthog/lemon-ui'++import { WorkflowAppliedOutcome } from './WorkflowAppliedOutcome'+import { workflowProposalsLogic } from './workflowProposalsLogic'+import { WorkflowSuggestionCard } from './WorkflowSuggestionCard'++export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {+ const { pendingProposals, appliedProposals, outcomes, proposalsResponse, proposalsResponseLoading } = useValues(+ workflowProposalsLogic({ id })+ )++ const measuredApplied = appliedProposals.filter((proposal) => outcomes[proposal.id]?.after)++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Waiting for you</h3>+ {proposalsResponse === null && proposalsResponseLoading ? (+ <Spinner />+ ) : pendingProposals.length === 0 ? (+ <p className="mb-0 text-secondary">+ Nothing to review. PostHog reads this workflow's metrics and files a suggestion here when it+ finds a change worth making. Nothing reaches anyone until you approve a suggestion and publish+ it.+ </p>+ ) : (+ pendingProposals.map((proposal) => (+ <WorkflowSuggestionCard key={proposal.id} id={id} proposal={proposal} />+ ))+ )}+ </div>+ {measuredApplied.length > 0 && (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Applied</h3>+ {measuredApplied.map((proposal) => (+ <WorkflowAppliedOutcome key={proposal.id} proposal={proposal} outcome={outcomes[proposal.id]} />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsxnew file mode 100644index 000000000000..f57076dc811b--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsNotice.tsx@@ -0,0 +1,30 @@+import { useValues } from 'kea'+import { router } from 'kea-router'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { urls } from 'scenes/urls'++import { workflowProposalsLogic } from './workflowProposalsLogic'++export function WorkflowSuggestionsNotice({ id }: { id: string }): JSX.Element | null {+ const { pendingProposals } = useValues(workflowProposalsLogic({ id }))++ if (pendingProposals.length === 0) {+ return null+ }++ return (+ <LemonBanner+ type="info"+ action={{+ children: 'Review',+ 'data-attr': 'workflow-suggestions-review',+ onClick: () => router.actions.push(urls.workflow(id, 'suggestions')),+ }}+ >+ {pendingProposals.length === 1+ ? 'PostHog suggests a change to this workflow.'+ : `PostHog suggests ${pendingProposals.length} changes to this workflow.`}+ </LemonBanner>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsxnew file mode 100644index 000000000000..fec507e53f52--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsTabLabel.tsx@@ -0,0 +1,20 @@+import { useValues } from 'kea'++import { LemonTag } from '@posthog/lemon-ui'++import { workflowProposalsLogic } from './workflowProposalsLogic'++export function WorkflowSuggestionsTabLabel({ id }: { id: string }): JSX.Element {+ const { pendingProposals } = useValues(workflowProposalsLogic({ id }))++ return (+ <span className="flex items-center gap-1.5">+ Suggestions+ {pendingProposals.length > 0 && (+ <LemonTag type="completion" size="small">+ {pendingProposals.length}+ </LemonTag>+ )}+ </span>+ )+}diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.tsnew file mode 100644index 000000000000..3620eb98978b--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts@@ -0,0 +1,28 @@+import { formatValue, readUnit } from './suggestionEvidence'++describe('suggestionEvidence', () => {+ it.each([+ ['a rate', 0.0865, 'rate' as const, '8.6%'],+ ['a rate of zero', 0, 'rate' as const, '0.0%'],+ ['a rate of one', 1, 'rate' as const, '100.0%'],+ ['a count of one', 1, 'count' as const, '1'],+ ['a count', 240, 'count' as const, '240'],+ ['no unit', 0.0865, null, '0.0865'],+ ])('formats %s', (_name, value, unit, expected) => {+ expect(formatValue(value, unit)).toBe(expected)+ })++ it('has nothing to show for a value that is not a number', () => {+ expect(formatValue(null, 'rate')).toBeNull()+ expect(formatValue('8.65%', 'rate')).toBeNull()+ })++ it.each([+ ['rate', 'rate'],+ ['count', 'count'],+ ['percent', null],+ [undefined, null],+ ])('reads the unit %s', (raw, expected) => {+ expect(readUnit(raw)).toBe(expected)+ })+})diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.tsnew file mode 100644index 000000000000..0e489d48a187--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts@@ -0,0 +1,31 @@+// A rate under this many observations is noise. Mirrors MIN_EVIDENCE_SAMPLE in+// products/workflows/backend/metrics.py.+export const MIN_EVIDENCE_SAMPLE = 20++// Mirrors EVIDENCE_UNITS in products/workflows/backend/api/hog_flow.py.+export type EvidenceUnit = 'rate' | 'count'++export interface GuardrailReading {+ metric: string+ value: number | null+ n?: number+ unit?: EvidenceUnit+}++export function readGuardrails(evidence: Record<string, unknown>): GuardrailReading[] {+ const raw = Array.isArray(evidence.guardrails) ? evidence.guardrails : []+ return raw.filter((entry): entry is GuardrailReading => !!entry && typeof entry === 'object' && 'metric' in entry)+}++export function readUnit(value: unknown): EvidenceUnit | null {+ return value === 'rate' || value === 'count' ? value : null+}++// The producer says what the number is. The unit is never guessed from the value's range, where+// a count of 1 would read as 100%.+export function formatValue(value: unknown, unit: EvidenceUnit | null): string | null {+ if (typeof value !== 'number') {+ return null+ }+ return unit === 'rate' ? `${(value * 100).toFixed(1)}%` : String(value)+}diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.tsnew file mode 100644index 000000000000..7a1c4677aedb--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts@@ -0,0 +1,233 @@+import { expectLogic } from 'kea-test-utils'++import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { workflowLogic } from '../workflowLogic'+import { workflowProposalsLogic } from './workflowProposalsLogic'++jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))++const confirmTheDialog = (): void => {+ const call = (LemonDialog.open as jest.Mock).mock.calls.at(-1)+ call[0].primaryButton.onClick()+}++const WORKFLOW_ID = 'wf-proposals-1'+const PROPOSAL_ID = 'proposal-1'+const DRAFT_STAMP = '2026-05-02T00:00:00.000Z'++describe('workflowProposalsLogic', () => {+ let logic: ReturnType<typeof workflowProposalsLogic.build>+ let approveBodies: Record<string, any>[]+ let approveStatus: number+ let proposalsListStatus: number+ let workflowVersion: number+ let workflowStatus: string+ let workflowDraft: Record<string, any> | null+ let workflowDraftStamp: string | null++ const proposal = {+ id: PROPOSAL_ID,+ title: 'Shorten the subject line',+ rationale: 'Open rate is under target.',+ content: { actions: [] },+ evidence: { metric: 'email open rate', current_value: 0.11, target_value: 0.2, window: '-7d' },+ base_version: 3,+ is_stale: false,+ status: 'suggested',+ source_id: 'run:1:finding:subject',+ created_at: '2026-05-01T00:00:00.000Z',+ resolved_at: null,+ resolved_by: null,+ applied_version: null,+ }++ beforeEach(() => {+ approveBodies = []+ approveStatus = 200+ proposalsListStatus = 200+ workflowVersion = 3+ workflowStatus = 'active'+ workflowDraft = { actions: [] }+ workflowDraftStamp = DRAFT_STAMP+ ;(LemonDialog.open as jest.Mock).mockClear()+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': () => [+ 200,+ {+ id: WORKFLOW_ID,+ name: 'Test',+ version: workflowVersion,+ status: workflowStatus,+ actions: [],+ edges: [],+ draft: workflowDraft,+ draft_updated_at: workflowDraftStamp,+ updated_at: '2026-05-01T00:00:00.000Z',+ },+ ],+ '/api/projects/:team_id/hog_flows/:id/proposals/': () =>+ proposalsListStatus === 200+ ? [200, { count: 1, results: [proposal] }]+ : [proposalsListStatus, { detail: 'nope' }],+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ post: {+ '/api/projects/:team_id/hog_flows/:id/proposals/:proposal_id/approve/': async ({ request }) => {+ approveBodies.push((await request.json()) as Record<string, any>)+ return [approveStatus, approveStatus === 200 ? proposal : { code: 'stale_update' }]+ },+ '/api/projects/:team_id/hog_flows/:id/proposals/:proposal_id/reject/': {+ ...proposal,+ status: 'rejected',+ },+ },+ })+ initKeaTests()+ logic = workflowProposalsLogic({ id: WORKFLOW_ID })+ logic.mount()+ })++ it('loads the pending queue on mount', async () => {+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])+ expect(logic.values.pendingProposals.map((p) => p.id)).toEqual([PROPOSAL_ID])+ })++ it('keeps the pending queue and reports failure when a reload hits a server error', async () => {+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])+ expect(logic.values.pendingProposals.map((p) => p.id)).toEqual([PROPOSAL_ID])++ proposalsListStatus = 500+ await expectLogic(logic, () => {+ logic.actions.loadProposals()+ }).toDispatchActions(['loadProposalsFailure'])++ expect(logic.values.pendingProposals.map((p) => p.id)).toEqual([PROPOSAL_ID])+ })++ it('treats the flag-off 404 as an empty queue with no failure', async () => {+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])++ proposalsListStatus = 404+ await expectLogic(logic, () => {+ logic.actions.loadProposals()+ }).toDispatchActions(['loadProposals', 'loadProposalsSuccess'])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.pendingProposals).toEqual([])+ })++ it('reloads the queue when the workflow version moves', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])++ workflowVersion = 4+ await expectLogic(logic, () => {+ flowLogic.actions.loadWorkflow()+ }).toDispatchActions(['loadProposals', 'loadApplied'])+ expect(logic.values.lastSeenVersion).toBe(4)+ })++ it('reloads the queue when a discard rewrites the draft stamp without moving the version', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])++ workflowDraft = null+ workflowDraftStamp = null+ await expectLogic(logic, () => {+ flowLogic.actions.loadWorkflow()+ }).toDispatchActions(['loadProposals', 'loadApplied'])+ expect(logic.values.lastSeenVersion).toBe(3)+ expect(logic.values.lastSeenDraftStamp).toBeNull()+ })++ it('approving sends the draft stamp it saw as the overwrite fence', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.approveProposal(PROPOSAL_ID)+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic, () => {+ confirmTheDialog()+ }).toDispatchActions([flowLogic.actionTypes.loadWorkflow])++ expect(approveBodies).toEqual([{ overwrite: true, expected_draft_updated_at: DRAFT_STAMP }])+ expect(logic.values.resolvingId).toBeNull()+ })++ it('approving with nothing staged asks the server not to overwrite a draft staged since', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ workflowDraft = null+ workflowDraftStamp = null+ await expectLogic(flowLogic, () => {+ flowLogic.actions.loadWorkflow()+ }).toDispatchActions(['loadWorkflowSuccess'])+ ;(LemonDialog.open as jest.Mock).mockClear()++ logic.actions.approveProposal(PROPOSAL_ID)+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic, () => {+ confirmTheDialog()+ }).toDispatchActions([flowLogic.actionTypes.loadWorkflow])++ expect(approveBodies).toEqual([{ overwrite: false, expected_draft_updated_at: null }])+ })++ it('will not stage a suggestion on a workflow with no publish or discard controls', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ workflowStatus = 'draft'+ await expectLogic(flowLogic, () => {+ flowLogic.actions.loadWorkflow()+ }).toDispatchActions(['loadWorkflowSuccess'])+ ;(LemonDialog.open as jest.Mock).mockClear()++ expect(logic.values.approveDisabledReason).toBe('Only a live workflow can stage a suggestion as a draft')++ logic.actions.approveProposal(PROPOSAL_ID)+ await expectLogic(logic).toFinishAllListeners()+ expect(LemonDialog.open as jest.Mock).not.toHaveBeenCalled()++ logic.actions.confirmApproveProposal(PROPOSAL_ID, null)+ await expectLogic(logic).toFinishAllListeners()+ expect(approveBodies).toEqual([])+ })++ it('a 409 reloads the workflow and the queue instead of leaving stale state on screen', async () => {+ approveStatus = 409+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ await expectLogic(logic, () => {+ logic.actions.confirmApproveProposal(PROPOSAL_ID, DRAFT_STAMP)+ }).toDispatchActions([flowLogic.actionTypes.loadWorkflow, logic.actionTypes.loadProposals])++ expect(logic.values.resolvingId).toBeNull()+ })++ it('ignores a second resolve while one is in flight', async () => {+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])+ logic.actions.setResolvingId(PROPOSAL_ID)++ logic.actions.confirmApproveProposal(PROPOSAL_ID, DRAFT_STAMP)+ logic.actions.confirmRejectProposal(PROPOSAL_ID)+ await expectLogic(logic).toFinishAllListeners()++ expect(approveBodies).toEqual([])+ })+})diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsnew file mode 100644index 000000000000..6f73749f4ba5--- /dev/null+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts@@ -0,0 +1,431 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import {+ hogFlowsProposalsApproveCreate,+ hogFlowsProposalsList,+ hogFlowsProposalsOutcomeRetrieve,+ hogFlowsProposalsRejectCreate,+} from '../../generated/api'+import type {+ PaginatedWorkflowProposalListApi,+ WorkflowProposalApi,+ WorkflowProposalOutcomeApi,+} from '../../generated/api.schemas'+import type { HogFlow } from '../hogflows/types'+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++export interface WorkflowProposalsLogicProps {+ id: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowProposalsLogicValues {+ currentTeamIdStrict: number | string // teamLogic+ hasStagedDraft: boolean // workflowLogic+ hasUnsavedChanges: boolean // workflowLogic+ originalWorkflow: HogFlow | null // workflowLogic+ showDraftActions: boolean // workflowLogic+ appliedProposals: WorkflowProposalApi[]+ appliedResponse: PaginatedWorkflowProposalListApi | null+ appliedResponseLoading: boolean+ approveDisabledReason: string | undefined+ lastSeenDraftStamp: string | null+ lastSeenVersion: number | null+ outcomes: Record<string, WorkflowProposalOutcomeApi>+ pendingProposals: WorkflowProposalApi[]+ proposalsResponse: PaginatedWorkflowProposalListApi | null+ proposalsResponseLoading: boolean+ resolvingAction: 'approve' | 'reject' | null+ resolvingId: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowProposalsLogicActions {+ approveProposal: (proposalId: string) => {+ proposalId: string+ }+ confirmApproveProposal: (+ proposalId: string,+ expectedDraftUpdatedAt: string | null+ ) => {+ expectedDraftUpdatedAt: string | null+ proposalId: string+ }+ confirmRejectProposal: (proposalId: string) => {+ proposalId: string+ }+ loadApplied: () => any+ loadAppliedFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAppliedSuccess: (+ appliedResponse: PaginatedWorkflowProposalListApi,+ payload?: any+ ) => {+ appliedResponse: PaginatedWorkflowProposalListApi+ payload?: any+ }+ loadOutcome: (proposalId: string) => {+ proposalId: string+ }+ loadProposals: () => any+ loadProposalsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProposalsSuccess: (+ proposalsResponse: PaginatedWorkflowProposalListApi,+ payload?: any+ ) => {+ proposalsResponse: PaginatedWorkflowProposalListApi+ payload?: any+ }+ rejectProposal: (proposalId: string) => {+ proposalId: string+ }+ removeResolvedProposal: (proposalId: string) => {+ proposalId: string+ }+ setLastSeen: (+ version: number | null,+ draftStamp: string | null+ ) => {+ draftStamp: string | null+ version: number | null+ }+ setOutcome: (+ proposalId: string,+ outcome: WorkflowProposalOutcomeApi+ ) => {+ outcome: WorkflowProposalOutcomeApi+ proposalId: string+ }+ setResolvingId: (+ proposalId: string | null,+ action?: 'approve' | 'reject' | null+ ) => {+ action: 'approve' | 'reject' | null+ proposalId: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowProposalsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ appliedProposals: (appliedResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]+ pendingProposals: (proposalsResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]+ approveDisabledReason: (hasUnsavedChanges: boolean, showDraftActions: boolean) => string | undefined+ }+}++export type workflowProposalsLogicType = MakeLogicType<+ workflowProposalsLogicValues,+ workflowProposalsLogicActions,+ WorkflowProposalsLogicProps,+ workflowProposalsLogicMeta+>++export const workflowProposalsLogic = kea<workflowProposalsLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'suggestions', 'workflowProposalsLogic']),+ props({} as WorkflowProposalsLogicProps),+ key(({ id }) => id),+ connect(({ id }: WorkflowProposalsLogicProps) => ({+ values: [+ teamLogic,+ ['currentTeamIdStrict'],+ workflowLogic({ id }),+ ['hasStagedDraft', 'hasUnsavedChanges', 'showDraftActions', 'originalWorkflow'],+ ],+ })),+ actions({+ approveProposal: (proposalId: string) => ({ proposalId }),+ confirmApproveProposal: (proposalId: string, expectedDraftUpdatedAt: string | null) => ({+ proposalId,+ expectedDraftUpdatedAt,+ }),+ rejectProposal: (proposalId: string) => ({ proposalId }),+ confirmRejectProposal: (proposalId: string) => ({ proposalId }),+ removeResolvedProposal: (proposalId: string) => ({ proposalId }),+ setResolvingId: (proposalId: string | null, action: 'approve' | 'reject' | null = null) => ({+ proposalId,+ action,+ }),+ loadOutcome: (proposalId: string) => ({ proposalId }),+ setLastSeen: (version: number | null, draftStamp: string | null) => ({ version, draftStamp }),+ setOutcome: (proposalId: string, outcome: WorkflowProposalOutcomeApi) => ({ proposalId, outcome }),+ }),+ reducers({+ // The server has resolved this one. Dropping it here means a reload that fails afterwards+ // cannot leave a resolved suggestion in the queue with live buttons.+ proposalsResponse: {+ removeResolvedProposal: (+ response: PaginatedWorkflowProposalListApi | null,+ { proposalId }: { proposalId: string }+ ): PaginatedWorkflowProposalListApi | null =>+ response+ ? {+ ...response,+ results: (response.results ?? []).filter((proposal) => proposal.id !== proposalId),+ }+ : response,+ },+ resolvingId: [+ null as string | null,+ {+ setResolvingId: (_, { proposalId }) => proposalId,+ },+ ],+ resolvingAction: [+ null as 'approve' | 'reject' | null,+ {+ setResolvingId: (_, { action }) => action,+ },+ ],+ lastSeenVersion: [+ null as number | null,+ {+ setLastSeen: (_, { version }) => version,+ },+ ],+ // Discard and restore return an approved suggestion to the queue without moving the version,+ // but both rewrite the draft stamp, so the queue follows that too.+ lastSeenDraftStamp: [+ null as string | null,+ {+ setLastSeen: (_, { draftStamp }) => draftStamp,+ },+ ],+ // Merge each finished request's entry here at reducer time, not inside the request. A request+ // that read prior state to build the merged map would read it stale, so two near-simultaneous+ // loads would drop each other's entry.+ outcomes: [+ {} as Record<string, WorkflowProposalOutcomeApi>,+ {+ setOutcome: (state, { proposalId, outcome }) => ({ ...state, [proposalId]: outcome }),+ },+ ],+ }),+ loaders(({ props, values }) => ({+ appliedResponse: [+ null as PaginatedWorkflowProposalListApi | null,+ {+ loadApplied: async () => {+ try {+ return await hogFlowsProposalsList(String(values.currentTeamIdStrict), props.id, {+ status: 'applied',+ limit: APPLIED_OUTCOME_LIMIT,+ })+ } catch (error) {+ // Only the flag-off 404 is an empty queue; anything else rejects so the loader keeps the last list.+ if (error instanceof ApiError && error.status === 404) {+ return { count: 0, results: [] }+ }+ throw error+ }+ },+ },+ ],+ proposalsResponse: [+ null as PaginatedWorkflowProposalListApi | null,+ {+ loadProposals: async () => {+ try {+ return await hogFlowsProposalsList(String(values.currentTeamIdStrict), props.id, {+ status: 'suggested',+ })+ } catch (error) {+ // 404 is the flag being off; anything else rejects so the loader keeps the last list.+ if (error instanceof ApiError && error.status === 404) {+ return { count: 0, results: [] }+ }+ throw error+ }+ },+ },+ ],+ })),+ selectors({+ appliedProposals: [+ (s) => [s.appliedResponse],+ (response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],+ ],+ pendingProposals: [+ (s) => [s.proposalsResponse],+ (response: PaginatedWorkflowProposalListApi | null): WorkflowProposalApi[] => response?.results ?? [],+ ],+ approveDisabledReason: [+ (s) => [s.hasUnsavedChanges, s.showDraftActions],+ (hasUnsavedChanges: boolean, showDraftActions: boolean): string | undefined => {+ // Approving stages the suggestion server-side and reloads the workflow, which drops+ // whatever the form still holds — the same trade discardDisabledReason guards.+ if (hasUnsavedChanges) {+ return 'Save your changes first'+ }+ // Without the publish and discard controls the staged draft would have no way out.+ if (!showDraftActions) {+ return 'Only a live workflow can stage a suggestion as a draft'+ }+ return undefined+ },+ ],+ }),+ listeners(({ actions, props, values }) => ({+ approveProposal: ({ proposalId }) => {+ if (values.resolvingId !== null || values.approveDisabledReason) {+ return+ }+ // The stamp of the draft this confirmation is about. Approve sends it as a fence, so a+ // draft staged or edited after this dialog opened returns 409 instead of being clobbered.+ const expectedDraftUpdatedAt = values.originalWorkflow?.draft_updated_at ?? null+ LemonDialog.open({+ title: 'Approve this suggestion?',+ description: values.hasStagedDraft+ ? 'This replaces your current staged draft with the suggested change. The live workflow keeps running until you publish.'+ : 'This opens the suggested change on the canvas as a draft. The live workflow keeps running until you publish.',+ primaryButton: {+ children: 'Approve as draft',+ onClick: () => actions.confirmApproveProposal(proposalId, expectedDraftUpdatedAt),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ },+ confirmApproveProposal: async ({ proposalId, expectedDraftUpdatedAt }) => {+ if (values.resolvingId !== null) {+ return+ }+ // The form can go dirty while the dialog is open, so the reason is checked again here.+ if (values.approveDisabledReason) {+ lemonToast.error(values.approveDisabledReason)+ return+ }+ actions.setResolvingId(proposalId, 'approve')+ try {+ await hogFlowsProposalsApproveCreate(String(values.currentTeamIdStrict), props.id, proposalId, {+ // With no stamp to fence against, overwrite would wave through a draft staged+ // since this dialog opened; false makes the server answer 409 instead.+ overwrite: expectedDraftUpdatedAt !== null,+ expected_draft_updated_at: expectedDraftUpdatedAt,+ })+ lemonToast.success('Suggestion staged as a draft. Publish it to go live.')+ actions.removeResolvedProposal(proposalId)+ workflowLogic({ id: props.id }).actions.loadWorkflow()+ actions.loadProposals()+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ if (error.code === 'proposal_already_resolved') {+ lemonToast.info('This suggestion was already resolved.')+ actions.removeResolvedProposal(proposalId)+ } else {+ lemonToast.error(+ error.code === 'proposal_out_of_date' && error.detail+ ? error.detail+ : 'The staged draft changed while you were confirming. Review it and try again.'+ )+ }+ workflowLogic({ id: props.id }).actions.loadWorkflow()+ actions.loadProposals()+ } else {+ lemonToast.error('Could not approve this suggestion. Please try again.')+ }+ } finally {+ actions.setResolvingId(null)+ }+ },+ rejectProposal: ({ proposalId }) => {+ if (values.resolvingId !== null) {+ return+ }+ LemonDialog.open({+ title: 'Reject this suggestion?',+ description: 'It stays in the workflow history as rejected. Nothing changes on the workflow.',+ primaryButton: {+ children: 'Reject',+ status: 'danger',+ onClick: () => actions.confirmRejectProposal(proposalId),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ },+ confirmRejectProposal: async ({ proposalId }) => {+ if (values.resolvingId !== null) {+ return+ }+ actions.setResolvingId(proposalId, 'reject')+ try {+ await hogFlowsProposalsRejectCreate(String(values.currentTeamIdStrict), props.id, proposalId, {})+ lemonToast.success('Suggestion rejected')+ actions.removeResolvedProposal(proposalId)+ actions.loadProposals()+ } catch (error) {+ if (error instanceof ApiError && error.code === 'proposal_already_resolved') {+ // Already resolved elsewhere, so "try again" would point at a button that cannot work.+ lemonToast.info('This suggestion was already resolved.')+ actions.removeResolvedProposal(proposalId)+ actions.loadProposals()+ } else {+ lemonToast.error('Could not reject this suggestion. Please try again.')+ }+ } finally {+ actions.setResolvingId(null)+ }+ },+ })),+ listeners(({ actions, props, values }) => ({+ loadAppliedSuccess: () => {+ for (const proposal of values.appliedProposals) {+ if (!values.outcomes[proposal.id]) {+ actions.loadOutcome(proposal.id)+ }+ }+ },+ loadOutcome: async ({ proposalId }) => {+ try {+ const outcome = await hogFlowsProposalsOutcomeRetrieve(+ String(values.currentTeamIdStrict),+ props.id,+ proposalId+ )+ actions.setOutcome(proposalId, outcome)+ } catch {}+ },+ })),+ listeners(({ actions, values, props }) => ({+ // Publish, discard and restore happen outside this panel; the version and the draft stamp cover all three.+ [workflowLogic({ id: props.id }).actionTypes.loadWorkflowSuccess]: () => {+ const version = values.originalWorkflow?.version ?? null+ const draftStamp = values.originalWorkflow?.draft_updated_at ?? null+ if (version === null || (version === values.lastSeenVersion && draftStamp === values.lastSeenDraftStamp)) {+ return+ }+ actions.setLastSeen(version, draftStamp)+ actions.loadProposals()+ actions.loadApplied()+ },+ })),+ afterMount(({ actions, values }) => {+ actions.setLastSeen(values.originalWorkflow?.version ?? null, values.originalWorkflow?.draft_updated_at ?? null)+ actions.loadProposals()+ actions.loadApplied()+ }),+])diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.tsindex 89030c52664e..2aa8c3016e97 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', 'assets', 'history'] as const+export const WorkflowTabs = ['workflow', 'invocations', 'metrics', 'suggestions', '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' | 'workflow'+ tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'suggestions' | 'workflow'}}