: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
fix(homepage): keep thread forms and notebook code off the home load (#122347)
Paul D'Ambra0be92b0e4f47
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex 2cf76c983ec3..036de65537d9 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -179,6 +179,10 @@ const ROOTS = ['products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx','products/posthog_ai/frontend/components/tool/widgets/RecordingsWidget.tsx','src/queries/Query/Query.tsx',+ // The input box renders the thread's question and approval forms only while the agent+ // waits for an answer, and notebook code only when a notebook update arrives.+ 'products/posthog_ai/frontend/api/primitives.ts',+ 'src/scenes/notebooks/Notebook/notebookLogic.ts',],},{diff --git a/frontend/src/scenes/max/MaxForms.stories.tsx b/frontend/src/scenes/max/MaxForms.stories.tsxindex 5d83082dc51f..31fd0c165095 100644--- a/frontend/src/scenes/max/MaxForms.stories.tsx+++ b/frontend/src/scenes/max/MaxForms.stories.tsx@@ -19,6 +19,10 @@ import { maxThreadLogic } from './maxThreadLogic'const meta: Meta = {title: 'Scenes-App/PostHog AI/Forms',...sharedMeta,+ parameters: {+ ...sharedMeta.parameters,+ testOptions: { waitForSelector: '[data-attr="max-multi-question-form"]' },+ },}export default metadiff --git a/frontend/src/scenes/max/MaxTools.stories.tsx b/frontend/src/scenes/max/MaxTools.stories.tsxindex 6251071bef42..7c41054bac3a 100644--- a/frontend/src/scenes/max/MaxTools.stories.tsx+++ b/frontend/src/scenes/max/MaxTools.stories.tsx@@ -1136,6 +1136,7 @@ export const DangerousOperationPendingApproval: Story = {parameters: {testOptions: {waitForLoadersToDisappear: false,+ waitForSelector: '[data-attr="max-dangerous-operation-input"]',},},}@@ -1324,6 +1325,7 @@ The following services will need to be notified:parameters: {testOptions: {waitForLoadersToDisappear: false,+ waitForSelector: '[data-attr="max-dangerous-operation-input"]',},},}diff --git a/frontend/src/scenes/max/components/DangerousOperationInput.tsx b/frontend/src/scenes/max/components/DangerousOperationInput.tsxnew file mode 100644index 000000000000..0ebb3a5eea1c--- /dev/null+++ b/frontend/src/scenes/max/components/DangerousOperationInput.tsx@@ -0,0 +1,76 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconCheck, IconWarning, IconX } from '@posthog/icons'+import { LemonDivider } from '@posthog/lemon-ui'++import { DangerousOperationResponse } from '~/queries/schema/schema-assistant-messages'++import { MarkdownMessage, type Option, OptionSelector } from 'products/posthog_ai/frontend/api/primitives'++import { maxThreadLogic } from '../maxThreadLogic'++interface DangerousOperationInputProps {+ operation: DangerousOperationResponse+}++export function DangerousOperationInput({ operation }: DangerousOperationInputProps): JSX.Element {+ const { continueAfterApproval, continueAfterRejection } = useActions(maxThreadLogic)+ const { streamingActive } = useValues(maxThreadLogic)+ const [status, setStatus] = useState<'pending' | 'approving' | 'rejecting' | 'custom'>('pending')++ const options: Option[] = [+ { label: 'Approve and execute', value: 'approve', icon: <IconCheck /> },+ { label: 'Reject this operation', value: 'reject', icon: <IconX /> },+ ]++ const handleSelect = (value: string | null): void => {+ if (value === 'approve') {+ setStatus('approving')+ continueAfterApproval(operation.proposalId)+ } else if (value === 'reject') {+ setStatus('rejecting')+ continueAfterRejection(operation.proposalId)+ }+ }++ const handleCustomSubmit = (customResponse: string): void => {+ setStatus('custom')+ continueAfterRejection(operation.proposalId, customResponse)+ }++ const isLoading = status !== 'pending'++ return (+ <div className="flex flex-col gap-2 p-3" data-attr="max-dangerous-operation-input">+ <div className="flex items-center gap-2 text-sm">+ <IconWarning className="text-warning size-4" />+ <span className="font-medium">Approval required</span>+ </div>+ {operation.toolName !== 'finalize_plan' && (+ <p className="text-xs text-secondary m-0">Review the changes below before approving:</p>+ )}+ <LemonDivider className="my-0 -mx-3 w-[calc(100%+var(--spacing)*6)]" />+ <div className="max-h-60 overflow-y-auto">+ <MarkdownMessage content={operation.preview} id={`approval-${operation.proposalId}`} />+ </div>+ <LemonDivider className="my-0 -mx-3 w-[calc(100%+var(--spacing)*6)]" />+ <OptionSelector+ options={options}+ onSelect={handleSelect}+ allowCustom+ customPlaceholder="Explain what you'd like instead..."+ onCustomSubmit={handleCustomSubmit}+ disabled={streamingActive}+ loading={isLoading}+ loadingMessage={+ status === 'approving'+ ? 'Approving...'+ : status === 'custom'+ ? 'Sending response...'+ : 'Rejecting...'+ }+ />+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/InputFormArea.tsx b/frontend/src/scenes/max/components/InputFormArea.tsxindex 14fcffda67f2..6cac7114c542 100644--- a/frontend/src/scenes/max/components/InputFormArea.tsx+++ b/frontend/src/scenes/max/components/InputFormArea.tsx@@ -1,416 +1,26 @@-import { useActions, useValues } from 'kea'-import { useCallback, useMemo, useRef, useState } from 'react'-import useResizeObserver from 'use-resize-observer'+import { useValues } from 'kea'+import { Suspense, useMemo } from 'react'-import { IconCheck, IconWarning, IconX } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonTabs, LemonTag, Spinner } from '@posthog/lemon-ui'+import { LemonTag } from '@posthog/lemon-ui'-import {- DangerousOperationResponse,- MultiQuestionForm,- MultiQuestionFormQuestion,-} from '~/queries/schema/schema-assistant-messages'--import {- isFieldValid,- MarkdownMessage,- MultiFieldQuestion,- type Option,- OptionSelector,- PermissionInput,- QuestionField,- QuestionInput,-} from 'products/posthog_ai/frontend/api/primitives'+import { lazyWithRetry } from 'lib/utils/retryImport'import { maxThreadLogic } from '../maxThreadLogic'-function isQuestionComplete(- q: MultiQuestionFormQuestion,- answers: Record<string, string | string[]>,- confirmedQuestions?: Set<string>,- skippedQuestions?: Set<string>-): boolean {- if (skippedQuestions?.has(q.id)) {- return true- }- if (q.fields?.length) {- // Multi_field questions with defaults (toggles, sliders) can appear "valid" on mount.- // Require the user to explicitly confirm by clicking the submit button.- if (confirmedQuestions && !confirmedQuestions.has(q.id)) {- return false- }- return q.fields.every((field) => isFieldValid(field, answers[field.id]))- }- if (q.type === 'multi_select') {- // Multi_select questions accumulate selections before submission.- // Require explicit confirmation like multi_field questions.- if (!confirmedQuestions?.has(q.id)) {- return false- }- const val = answers[q.id]- return Array.isArray(val) && val.length > 0- }- return answers[q.id] !== undefined-}--function getClearedAnswersForQuestion(- question: MultiQuestionFormQuestion,- answers: Record<string, string | string[]>-): Record<string, string | string[]> {- const nextAnswers = { ...answers }-- if (question.fields?.length) {- for (const field of question.fields) {- delete nextAnswers[field.id]- }- } else {- delete nextAnswers[question.id]- }-- return nextAnswers-}--function removeQuestionFromSet(questionId: string, values: Set<string>): Set<string> {- if (!values.has(questionId)) {- return values- }-- const nextValues = new Set(values)- nextValues.delete(questionId)- return nextValues-}--interface MultiQuestionFormInputProps {- form: MultiQuestionForm- /** Initial answers for stories/testing */- initialAnswers?: Record<string, string | string[]>-}--export function MultiQuestionFormInput({ form, initialAnswers = {} }: MultiQuestionFormInputProps): JSX.Element | null {- const { continueAfterForm, continueAfterFormDismissal } = useActions(maxThreadLogic)- const questions = form.questions-- const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)- // Track which multi_field questions the user has explicitly confirmed- const [confirmedQuestions, setConfirmedQuestions] = useState<Set<string>>(() => new Set())- const [skippedQuestions, setSkippedQuestions] = useState<Set<string>>(() => new Set())- const [answers, setAnswers] = useState<Record<string, string | string[]>>(() => {- const initial = { ...initialAnswers }- for (const q of questions) {- if (!q.fields) {- continue- }- for (const field of q.fields) {- if (initial[field.id] !== undefined) {- continue- }- if (field.type === 'toggle') {- initial[field.id] = 'false'- } else if (field.type === 'slider') {- initial[field.id] = String(field.min ?? 0)- }- }- }- return initial- })- const [submissionState, setSubmissionState] = useState<'idle' | 'submitting' | 'dismissing'>('idle')-- const answersRef = useRef(answers)- answersRef.current = answers- const confirmedQuestionsRef = useRef(confirmedQuestions)- confirmedQuestionsRef.current = confirmedQuestions- const skippedQuestionsRef = useRef(skippedQuestions)- skippedQuestionsRef.current = skippedQuestions-- const currentQuestion = questions[currentQuestionIndex]-- const contentRef = useRef<HTMLDivElement>(null)- const { height: contentHeight } = useResizeObserver({ ref: contentRef })-- const allQuestionsCompleted = questions.every((q) =>- isQuestionComplete(q, answers, confirmedQuestions, skippedQuestions)- )-- const advanceToNextQuestion = useCallback(- (- updatedAnswers: Record<string, string | string[]>,- nextConfirmedQuestions: Set<string> = confirmedQuestionsRef.current,- nextSkippedQuestions: Set<string> = skippedQuestionsRef.current- ) => {- const allCompleted = questions.every((q) =>- isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)- )- if (allCompleted) {- setSubmissionState('submitting')- continueAfterForm(updatedAnswers)- } else {- const nextIncompleteQuestionIndex = questions.findIndex(- (q, index) =>- index > currentQuestionIndex &&- !isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)- )-- if (nextIncompleteQuestionIndex !== -1) {- setCurrentQuestionIndex(nextIncompleteQuestionIndex)- return- }-- const firstIncompleteQuestionIndex = questions.findIndex(- (q) => !isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)- )- if (firstIncompleteQuestionIndex !== -1) {- setCurrentQuestionIndex(firstIncompleteQuestionIndex)- }- }- },- [continueAfterForm, currentQuestionIndex, questions]- )-- const handleSingleFieldAnswer = useCallback(- (value: string | string[] | null) => {- const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)- if (nextSkippedQuestions !== skippedQuestionsRef.current) {- setSkippedQuestions(nextSkippedQuestions)- skippedQuestionsRef.current = nextSkippedQuestions- }-- if (value === null) {- const updatedAnswers = { ...answersRef.current }- delete updatedAnswers[currentQuestion.id]- setAnswers(updatedAnswers)- answersRef.current = updatedAnswers- return- }-- const updatedAnswers = { ...answersRef.current, [currentQuestion.id]: value }- setAnswers(updatedAnswers)- advanceToNextQuestion(updatedAnswers, confirmedQuestionsRef.current, nextSkippedQuestions)- },- [currentQuestion, advanceToNextQuestion]- )-- const handleFieldChange = useCallback(- (fieldId: string, value: string | string[]) => {- const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)- if (nextSkippedQuestions !== skippedQuestionsRef.current) {- setSkippedQuestions(nextSkippedQuestions)- skippedQuestionsRef.current = nextSkippedQuestions- }- setAnswers((prev) => ({ ...prev, [fieldId]: value }))- },- [currentQuestion.id]- )-- const handleMultiSelectChange = useCallback(- (value: string[]) => {- const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)- if (nextSkippedQuestions !== skippedQuestionsRef.current) {- setSkippedQuestions(nextSkippedQuestions)- skippedQuestionsRef.current = nextSkippedQuestions- }- const nextConfirmedQuestions = removeQuestionFromSet(currentQuestion.id, confirmedQuestionsRef.current)- if (nextConfirmedQuestions !== confirmedQuestionsRef.current) {- setConfirmedQuestions(nextConfirmedQuestions)- confirmedQuestionsRef.current = nextConfirmedQuestions- }- const updatedAnswers = { ...answersRef.current, [currentQuestion.id]: value }- setAnswers(updatedAnswers)- answersRef.current = updatedAnswers- },- [currentQuestion.id]- )-- const handleMultiFieldSubmit = useCallback(() => {- const nextConfirmedQuestions = new Set(confirmedQuestionsRef.current)- nextConfirmedQuestions.add(currentQuestion.id)- setConfirmedQuestions(nextConfirmedQuestions)- confirmedQuestionsRef.current = nextConfirmedQuestions-- const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)- if (nextSkippedQuestions !== skippedQuestionsRef.current) {- setSkippedQuestions(nextSkippedQuestions)- skippedQuestionsRef.current = nextSkippedQuestions- }-- advanceToNextQuestion(answersRef.current, nextConfirmedQuestions, nextSkippedQuestions)- }, [advanceToNextQuestion, currentQuestion])-- const handleSkipQuestion = useCallback(() => {- const updatedAnswers = getClearedAnswersForQuestion(currentQuestion, answersRef.current)- setAnswers(updatedAnswers)-- const nextSkippedQuestions = new Set(skippedQuestionsRef.current)- nextSkippedQuestions.add(currentQuestion.id)- setSkippedQuestions(nextSkippedQuestions)- skippedQuestionsRef.current = nextSkippedQuestions-- const nextConfirmedQuestions = removeQuestionFromSet(currentQuestion.id, confirmedQuestionsRef.current)- if (nextConfirmedQuestions !== confirmedQuestionsRef.current) {- setConfirmedQuestions(nextConfirmedQuestions)- confirmedQuestionsRef.current = nextConfirmedQuestions- }-- advanceToNextQuestion(updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)- }, [advanceToNextQuestion, currentQuestion])-- const handleDismissForm = useCallback(() => {- setSubmissionState('dismissing')- continueAfterFormDismissal()- }, [continueAfterFormDismissal])-- const handleTabClick = useCallback((index: number) => {- setCurrentQuestionIndex(index)- }, [])-- if (!currentQuestion || submissionState !== 'idle') {- return (- <div className="flex items-center gap-2 text-muted p-3">- <Spinner className="size-4" />- <span>{submissionState === 'dismissing' ? 'Dismissing form...' : 'Submitting answers...'}</span>- </div>- )- }-- return (- <div className="flex flex-col gap-2 p-3">- {questions.length > 1 && (- <LemonTabs- size="xsmall"- activeKey={currentQuestionIndex}- onChange={handleTabClick}- tabs={questions.map((question, index) => {- return {- key: index,- label: question.title,- completed: isQuestionComplete(question, answers, confirmedQuestions, skippedQuestions),- }- })}- className="w-[calc(100%+var(--spacing-3))] -mx-3 [&>ul]:pl-3 -mt-2.5"- rightSlot={- <LemonButton- size="xsmall"- type="tertiary"- icon={<IconX />}- onClick={handleDismissForm}- aria-label="Dismiss form"- />- }- rightSlotClassName="pr-1 bg-unset"- />- )}- <div- className="transition-[height] duration-150 motion-reduce:transition-none"- // eslint-disable-next-line react/forbid-dom-props- style={{ height: contentHeight }}- >- <div ref={contentRef}>- {questions.map((q, index) => {- const active = index === currentQuestionIndex- const qIsMultiField = q.type === 'multi_field' || !!(q.fields && q.fields.length > 0)-- return (- <div- key={q.id}- className={- active- ? 'flex flex-col gap-3 starting:opacity-0 opacity-100 transition-[opacity] duration-150 motion-reduce:transition-none'- : 'hidden'- }- >- <div className="font-medium text-sm">{q.question}</div>- {qIsMultiField ? (- <MultiFieldQuestion- question={q}- answers={answers}- onFieldChange={handleFieldChange}- onSubmit={handleMultiFieldSubmit}- onSkip={handleSkipQuestion}- submitLabel={allQuestionsCompleted ? 'Submit' : 'Next'}- />- ) : (- <QuestionField- question={q}- value={answers[q.id]}- onAnswer={handleSingleFieldAnswer}- onChange={handleMultiSelectChange}- onSubmit={handleMultiFieldSubmit}- onSkip={handleSkipQuestion}- submitLabel={allQuestionsCompleted ? 'Submit' : 'Next'}- />- )}- </div>- )- })}- </div>- </div>- </div>- )-}--interface DangerousOperationInputProps {- operation: DangerousOperationResponse-}--function DangerousOperationInput({ operation }: DangerousOperationInputProps): JSX.Element {- const { continueAfterApproval, continueAfterRejection } = useActions(maxThreadLogic)- const { streamingActive } = useValues(maxThreadLogic)- const [status, setStatus] = useState<'pending' | 'approving' | 'rejecting' | 'custom'>('pending')-- const options: Option[] = [- { label: 'Approve and execute', value: 'approve', icon: <IconCheck /> },- { label: 'Reject this operation', value: 'reject', icon: <IconX /> },- ]-- const handleSelect = (value: string | null): void => {- if (value === 'approve') {- setStatus('approving')- continueAfterApproval(operation.proposalId)- } else if (value === 'reject') {- setStatus('rejecting')- continueAfterRejection(operation.proposalId)- }- }-- const handleCustomSubmit = (customResponse: string): void => {- setStatus('custom')- continueAfterRejection(operation.proposalId, customResponse)- }-- const isLoading = status !== 'pending'-- return (- <div className="flex flex-col gap-2 p-3">- <div className="flex items-center gap-2 text-sm">- <IconWarning className="text-warning size-4" />- <span className="font-medium">Approval required</span>- </div>- {operation.toolName !== 'finalize_plan' && (- <p className="text-xs text-secondary m-0">Review the changes below before approving:</p>- )}- <LemonDivider className="my-0 -mx-3 w-[calc(100%+var(--spacing)*6)]" />- <div className="max-h-60 overflow-y-auto">- <MarkdownMessage content={operation.preview} id={`approval-${operation.proposalId}`} />- </div>- <LemonDivider className="my-0 -mx-3 w-[calc(100%+var(--spacing)*6)]" />- <OptionSelector- options={options}- onSelect={handleSelect}- allowCustom- customPlaceholder="Explain what you'd like instead..."- onCustomSubmit={handleCustomSubmit}- disabled={streamingActive}- loading={isLoading}- loadingMessage={- status === 'approving'- ? 'Approving...'- : status === 'custom'- ? 'Sending response...'- : 'Rejecting...'- }- />- </div>- )-}+// These forms render only while the agent waits for an answer. Loading them lazily keeps the+// posthog_ai primitives barrel off the eager path of every page that shows the input box.+const MultiQuestionFormInput = lazyWithRetry(() =>+ import('./MultiQuestionFormInput').then((m) => ({ default: m.MultiQuestionFormInput }))+)+const DangerousOperationInput = lazyWithRetry(() =>+ import('./DangerousOperationInput').then((m) => ({ default: m.DangerousOperationInput }))+)+const QuestionInput = lazyWithRetry(() =>+ import('products/posthog_ai/frontend/api/primitives').then((m) => ({ default: m.QuestionInput }))+)+const PermissionInput = lazyWithRetry(() =>+ import('products/posthog_ai/frontend/api/primitives').then((m) => ({ default: m.PermissionInput }))+)/*** Compact badge showing the active ACP permission mode (e.g. plan vs default) for sandbox@@ -433,7 +43,15 @@ export function SandboxModeBadge(): JSX.Element | null {)}-export function InputFormArea(): JSX.Element | null {+export function InputFormArea(): JSX.Element {+ return (+ <Suspense fallback={null}>+ <ActiveInputForm />+ </Suspense>+ )+}++function ActiveInputForm(): JSX.Element | null {// Use raw state values instead of selector to ensure re-renders on state changesconst {activeMultiQuestionForm,diff --git a/frontend/src/scenes/max/components/InputFormArea.test.tsx b/frontend/src/scenes/max/components/MultiQuestionFormInput.test.tsxsimilarity index 98%rename from frontend/src/scenes/max/components/InputFormArea.test.tsxrename to frontend/src/scenes/max/components/MultiQuestionFormInput.test.tsxindex 30421eeb4cfd..f9e67bbef415 100644--- a/frontend/src/scenes/max/components/InputFormArea.test.tsx+++ b/frontend/src/scenes/max/components/MultiQuestionFormInput.test.tsx@@ -5,7 +5,7 @@ import { useActions } from 'kea'import type { MultiQuestionForm } from '~/queries/schema/schema-assistant-messages'-import { MultiQuestionFormInput } from './InputFormArea'+import { MultiQuestionFormInput } from './MultiQuestionFormInput'jest.mock('kea', () => ({...jest.requireActual('kea'),diff --git a/frontend/src/scenes/max/components/MultiQuestionFormInput.tsx b/frontend/src/scenes/max/components/MultiQuestionFormInput.tsxnew file mode 100644index 000000000000..5fbd879a9344--- /dev/null+++ b/frontend/src/scenes/max/components/MultiQuestionFormInput.tsx@@ -0,0 +1,335 @@+import { useActions } from 'kea'+import { useCallback, useRef, useState } from 'react'+import useResizeObserver from 'use-resize-observer'++import { IconX } from '@posthog/icons'+import { LemonButton, LemonTabs, Spinner } from '@posthog/lemon-ui'++import { MultiQuestionForm, MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'++import { isFieldValid, MultiFieldQuestion, QuestionField } from 'products/posthog_ai/frontend/api/primitives'++import { maxThreadLogic } from '../maxThreadLogic'++function isQuestionComplete(+ q: MultiQuestionFormQuestion,+ answers: Record<string, string | string[]>,+ confirmedQuestions?: Set<string>,+ skippedQuestions?: Set<string>+): boolean {+ if (skippedQuestions?.has(q.id)) {+ return true+ }+ if (q.fields?.length) {+ // Multi_field questions with defaults (toggles, sliders) can appear "valid" on mount.+ // Require the user to explicitly confirm by clicking the submit button.+ if (confirmedQuestions && !confirmedQuestions.has(q.id)) {+ return false+ }+ return q.fields.every((field) => isFieldValid(field, answers[field.id]))+ }+ if (q.type === 'multi_select') {+ // Multi_select questions accumulate selections before submission.+ // Require explicit confirmation like multi_field questions.+ if (!confirmedQuestions?.has(q.id)) {+ return false+ }+ const val = answers[q.id]+ return Array.isArray(val) && val.length > 0+ }+ return answers[q.id] !== undefined+}++function getClearedAnswersForQuestion(+ question: MultiQuestionFormQuestion,+ answers: Record<string, string | string[]>+): Record<string, string | string[]> {+ const nextAnswers = { ...answers }++ if (question.fields?.length) {+ for (const field of question.fields) {+ delete nextAnswers[field.id]+ }+ } else {+ delete nextAnswers[question.id]+ }++ return nextAnswers+}++function removeQuestionFromSet(questionId: string, values: Set<string>): Set<string> {+ if (!values.has(questionId)) {+ return values+ }++ const nextValues = new Set(values)+ nextValues.delete(questionId)+ return nextValues+}++interface MultiQuestionFormInputProps {+ form: MultiQuestionForm+ /** Initial answers for stories/testing */+ initialAnswers?: Record<string, string | string[]>+}++export function MultiQuestionFormInput({ form, initialAnswers = {} }: MultiQuestionFormInputProps): JSX.Element | null {+ const { continueAfterForm, continueAfterFormDismissal } = useActions(maxThreadLogic)+ const questions = form.questions++ const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)+ // Track which multi_field questions the user has explicitly confirmed+ const [confirmedQuestions, setConfirmedQuestions] = useState<Set<string>>(() => new Set())+ const [skippedQuestions, setSkippedQuestions] = useState<Set<string>>(() => new Set())+ const [answers, setAnswers] = useState<Record<string, string | string[]>>(() => {+ const initial = { ...initialAnswers }+ for (const q of questions) {+ if (!q.fields) {+ continue+ }+ for (const field of q.fields) {+ if (initial[field.id] !== undefined) {+ continue+ }+ if (field.type === 'toggle') {+ initial[field.id] = 'false'+ } else if (field.type === 'slider') {+ initial[field.id] = String(field.min ?? 0)+ }+ }+ }+ return initial+ })+ const [submissionState, setSubmissionState] = useState<'idle' | 'submitting' | 'dismissing'>('idle')++ const answersRef = useRef(answers)+ answersRef.current = answers+ const confirmedQuestionsRef = useRef(confirmedQuestions)+ confirmedQuestionsRef.current = confirmedQuestions+ const skippedQuestionsRef = useRef(skippedQuestions)+ skippedQuestionsRef.current = skippedQuestions++ const currentQuestion = questions[currentQuestionIndex]++ const contentRef = useRef<HTMLDivElement>(null)+ const { height: contentHeight } = useResizeObserver({ ref: contentRef })++ const allQuestionsCompleted = questions.every((q) =>+ isQuestionComplete(q, answers, confirmedQuestions, skippedQuestions)+ )++ const advanceToNextQuestion = useCallback(+ (+ updatedAnswers: Record<string, string | string[]>,+ nextConfirmedQuestions: Set<string> = confirmedQuestionsRef.current,+ nextSkippedQuestions: Set<string> = skippedQuestionsRef.current+ ) => {+ const allCompleted = questions.every((q) =>+ isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)+ )+ if (allCompleted) {+ setSubmissionState('submitting')+ continueAfterForm(updatedAnswers)+ } else {+ const nextIncompleteQuestionIndex = questions.findIndex(+ (q, index) =>+ index > currentQuestionIndex &&+ !isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)+ )++ if (nextIncompleteQuestionIndex !== -1) {+ setCurrentQuestionIndex(nextIncompleteQuestionIndex)+ return+ }++ const firstIncompleteQuestionIndex = questions.findIndex(+ (q) => !isQuestionComplete(q, updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)+ )+ if (firstIncompleteQuestionIndex !== -1) {+ setCurrentQuestionIndex(firstIncompleteQuestionIndex)+ }+ }+ },+ [continueAfterForm, currentQuestionIndex, questions]+ )++ const handleSingleFieldAnswer = useCallback(+ (value: string | string[] | null) => {+ const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)+ if (nextSkippedQuestions !== skippedQuestionsRef.current) {+ setSkippedQuestions(nextSkippedQuestions)+ skippedQuestionsRef.current = nextSkippedQuestions+ }++ if (value === null) {+ const updatedAnswers = { ...answersRef.current }+ delete updatedAnswers[currentQuestion.id]+ setAnswers(updatedAnswers)+ answersRef.current = updatedAnswers+ return+ }++ const updatedAnswers = { ...answersRef.current, [currentQuestion.id]: value }+ setAnswers(updatedAnswers)+ advanceToNextQuestion(updatedAnswers, confirmedQuestionsRef.current, nextSkippedQuestions)+ },+ [currentQuestion, advanceToNextQuestion]+ )++ const handleFieldChange = useCallback(+ (fieldId: string, value: string | string[]) => {+ const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)+ if (nextSkippedQuestions !== skippedQuestionsRef.current) {+ setSkippedQuestions(nextSkippedQuestions)+ skippedQuestionsRef.current = nextSkippedQuestions+ }+ setAnswers((prev) => ({ ...prev, [fieldId]: value }))+ },+ [currentQuestion.id]+ )++ const handleMultiSelectChange = useCallback(+ (value: string[]) => {+ const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)+ if (nextSkippedQuestions !== skippedQuestionsRef.current) {+ setSkippedQuestions(nextSkippedQuestions)+ skippedQuestionsRef.current = nextSkippedQuestions+ }+ const nextConfirmedQuestions = removeQuestionFromSet(currentQuestion.id, confirmedQuestionsRef.current)+ if (nextConfirmedQuestions !== confirmedQuestionsRef.current) {+ setConfirmedQuestions(nextConfirmedQuestions)+ confirmedQuestionsRef.current = nextConfirmedQuestions+ }+ const updatedAnswers = { ...answersRef.current, [currentQuestion.id]: value }+ setAnswers(updatedAnswers)+ answersRef.current = updatedAnswers+ },+ [currentQuestion.id]+ )++ const handleMultiFieldSubmit = useCallback(() => {+ const nextConfirmedQuestions = new Set(confirmedQuestionsRef.current)+ nextConfirmedQuestions.add(currentQuestion.id)+ setConfirmedQuestions(nextConfirmedQuestions)+ confirmedQuestionsRef.current = nextConfirmedQuestions++ const nextSkippedQuestions = removeQuestionFromSet(currentQuestion.id, skippedQuestionsRef.current)+ if (nextSkippedQuestions !== skippedQuestionsRef.current) {+ setSkippedQuestions(nextSkippedQuestions)+ skippedQuestionsRef.current = nextSkippedQuestions+ }++ advanceToNextQuestion(answersRef.current, nextConfirmedQuestions, nextSkippedQuestions)+ }, [advanceToNextQuestion, currentQuestion])++ const handleSkipQuestion = useCallback(() => {+ const updatedAnswers = getClearedAnswersForQuestion(currentQuestion, answersRef.current)+ setAnswers(updatedAnswers)++ const nextSkippedQuestions = new Set(skippedQuestionsRef.current)+ nextSkippedQuestions.add(currentQuestion.id)+ setSkippedQuestions(nextSkippedQuestions)+ skippedQuestionsRef.current = nextSkippedQuestions++ const nextConfirmedQuestions = removeQuestionFromSet(currentQuestion.id, confirmedQuestionsRef.current)+ if (nextConfirmedQuestions !== confirmedQuestionsRef.current) {+ setConfirmedQuestions(nextConfirmedQuestions)+ confirmedQuestionsRef.current = nextConfirmedQuestions+ }++ advanceToNextQuestion(updatedAnswers, nextConfirmedQuestions, nextSkippedQuestions)+ }, [advanceToNextQuestion, currentQuestion])++ const handleDismissForm = useCallback(() => {+ setSubmissionState('dismissing')+ continueAfterFormDismissal()+ }, [continueAfterFormDismissal])++ const handleTabClick = useCallback((index: number) => {+ setCurrentQuestionIndex(index)+ }, [])++ if (!currentQuestion || submissionState !== 'idle') {+ return (+ <div className="flex items-center gap-2 text-muted p-3">+ <Spinner className="size-4" />+ <span>{submissionState === 'dismissing' ? 'Dismissing form...' : 'Submitting answers...'}</span>+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-2 p-3" data-attr="max-multi-question-form">+ {questions.length > 1 && (+ <LemonTabs+ size="xsmall"+ activeKey={currentQuestionIndex}+ onChange={handleTabClick}+ tabs={questions.map((question, index) => {+ return {+ key: index,+ label: question.title,+ completed: isQuestionComplete(question, answers, confirmedQuestions, skippedQuestions),+ }+ })}+ className="w-[calc(100%+var(--spacing-3))] -mx-3 [&>ul]:pl-3 -mt-2.5"+ rightSlot={+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconX />}+ onClick={handleDismissForm}+ aria-label="Dismiss form"+ />+ }+ rightSlotClassName="pr-1 bg-unset"+ />+ )}+ <div+ className="transition-[height] duration-150 motion-reduce:transition-none"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ height: contentHeight }}+ >+ <div ref={contentRef}>+ {questions.map((q, index) => {+ const active = index === currentQuestionIndex+ const qIsMultiField = q.type === 'multi_field' || !!(q.fields && q.fields.length > 0)++ return (+ <div+ key={q.id}+ className={+ active+ ? 'flex flex-col gap-3 starting:opacity-0 opacity-100 transition-[opacity] duration-150 motion-reduce:transition-none'+ : 'hidden'+ }+ >+ <div className="font-medium text-sm">{q.question}</div>+ {qIsMultiField ? (+ <MultiFieldQuestion+ question={q}+ answers={answers}+ onFieldChange={handleFieldChange}+ onSubmit={handleMultiFieldSubmit}+ onSkip={handleSkipQuestion}+ submitLabel={allQuestionsCompleted ? 'Submit' : 'Next'}+ />+ ) : (+ <QuestionField+ question={q}+ value={answers[q.id]}+ onAnswer={handleSingleFieldAnswer}+ onChange={handleMultiSelectChange}+ onSubmit={handleMultiFieldSubmit}+ onSkip={handleSkipQuestion}+ submitLabel={allQuestionsCompleted ? 'Submit' : 'Next'}+ />+ )}+ </div>+ )+ })}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 869cadce4cdd..566c849af172 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -1471,7 +1471,7 @@ describe('maxThreadLogic', () => {await expectLogic(logic, () => {logic.actions.processNotebookUpdate('test-notebook-id', { type: 'doc', content: [] } as any)- }).toDispatchActions(['processNotebookUpdate'])+ }).toFinishAllListeners()expect(openNotebookSpy).toHaveBeenCalledWith('test-notebook-id', NotebookTarget.Scene, expect.any(Function))expect(router.values.location.pathname).toContain(urls.notebook('test-notebook-id'))@@ -1492,7 +1492,7 @@ describe('maxThreadLogic', () => {await expectLogic(logic, () => {logic.actions.processNotebookUpdate(notebookId, { type: 'doc', content: [] } as any)- }).toDispatchActions(['processNotebookUpdate'])+ }).toFinishAllListeners()expect(findMountedSpy).toHaveBeenCalledWith({ shortId: notebookId })expect(routerActionsSpy).not.toHaveBeenCalled()@@ -1510,7 +1510,7 @@ describe('maxThreadLogic', () => {await expectLogic(logic, () => {logic.actions.processNotebookUpdate(notebookId, { type: 'doc', content: [] } as any)- }).toDispatchActions(['processNotebookUpdate'])+ }).toFinishAllListeners()expect(notebookLogicFindMountedSpy).toHaveBeenCalledWith({ shortId: notebookId })expect(routerActionsSpy).not.toHaveBeenCalled()diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 49e802de6b01..f5aadea6f966 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -29,7 +29,6 @@ import { uuid } from 'lib/utils/dom'import { objectsEqual } from 'lib/utils/objects'import { billingLogic } from 'scenes/billing/billingLogic'import { maxContextLogic } from 'scenes/max/maxContextLogic'-import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'import { NotebookTarget } from 'scenes/notebooks/types'import { organizationLogic } from 'scenes/organizationLogic'import { sceneLogic } from 'scenes/sceneLogic'@@ -38,7 +37,6 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'-import { openNotebook } from '~/models/notebooksModel'import {AgentMode,ApprovalDecisionStatus,@@ -2332,6 +2330,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([},processNotebookUpdate: async ({ notebookId, notebookContent }) => {try {+ const [{ notebookLogic }, { openNotebook }] = await Promise.all([+ import('scenes/notebooks/Notebook/notebookLogic'),+ import('~/models/notebooksModel'),+ ])const currentPath = router.values.location.pathnameconst notebookPath = urls.notebook(notebookId)diff --git a/frontend/src/scenes/max/messages/MultiQuestionForm.tsx b/frontend/src/scenes/max/messages/MultiQuestionForm.tsxindex 5f5de4a84b3b..ad15649ccea2 100644--- a/frontend/src/scenes/max/messages/MultiQuestionForm.tsx+++ b/frontend/src/scenes/max/messages/MultiQuestionForm.tsx@@ -13,7 +13,7 @@ interface MultiQuestionFormRecapProps {/*** Displays a completed multi-question form recap in the chat thread.- * The interactive form is handled by MultiQuestionFormInput in InputFormArea.tsx.+ * The interactive form is handled by MultiQuestionFormInput in MultiQuestionFormInput.tsx.*/export function MultiQuestionFormRecap({form,