Skip to content

: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.

fix(max): stop logging the 40k length validation error as an exception (#95516)

posthog[bot]8044a5704995
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 312246723180..1a4d53ba8011 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -81,6 +81,10 @@ RESEARCH_RATE_LIMIT_MESSAGE = (
"conversation for continued access."
)
+# Roughly 10k tokens. Every path that accepts a user message shares this, so the limit can't drift
+# between them. The frontend mirrors it in `MAX_MESSAGE_LENGTH` (frontend/src/scenes/max/max-constants.tsx).
+MAX_MESSAGE_CONTENT_LENGTH = 40000
+
STREAM_ITERATION_LATENCY_HISTOGRAM = Histogram(
"posthog_ai_stream_iteration_latency_seconds",
"Time between iterations in the async stream loop",
@@ -105,7 +109,7 @@ class MessageSerializer(MessageMinimalSerializer):
content = serializers.CharField(
required=True,
allow_null=True, # Null content means we're resuming streaming or continuing previous generation
- max_length=40000, # Roughly 10k tokens
+ max_length=MAX_MESSAGE_CONTENT_LENGTH,
)
conversation = serializers.UUIDField(
required=True
@@ -157,7 +161,7 @@ class MessageSerializer(MessageMinimalSerializer):
class QueueMessageSerializer(serializers.Serializer):
- content = serializers.CharField(required=True, allow_blank=False, max_length=40000)
+ content = serializers.CharField(required=True, allow_blank=False, max_length=MAX_MESSAGE_CONTENT_LENGTH)
contextual_tools = serializers.DictField(required=False, child=serializers.JSONField())
ui_context = serializers.JSONField(required=False)
billing_context = serializers.JSONField(required=False)
@@ -194,7 +198,7 @@ class QueueMessageSerializer(serializers.Serializer):
class QueueMessageUpdateSerializer(serializers.Serializer):
- content = serializers.CharField(required=True, allow_blank=False, max_length=40000)
+ content = serializers.CharField(required=True, allow_blank=False, max_length=MAX_MESSAGE_CONTENT_LENGTH)
class SandboxAttachedContextItemSerializer(serializers.Serializer):
@@ -235,7 +239,7 @@ class SandboxOpenSerializer(serializers.Serializer):
required=False,
allow_null=True,
allow_blank=True,
- max_length=40000,
+ max_length=MAX_MESSAGE_CONTENT_LENGTH,
help_text="The user's message text. Omit or null to warm a sandbox (boot + idle) ahead of the first message.",
)
trace_id = serializers.UUIDField(
diff --git a/frontend/src/scenes/max/components/QuestionInput.test.tsx b/frontend/src/scenes/max/components/QuestionInput.test.tsx
index 5503e6f6d63a..1d8a9884a283 100644
--- a/frontend/src/scenes/max/components/QuestionInput.test.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.test.tsx
@@ -6,6 +6,7 @@ import { BindLogic, Provider } from 'kea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { MAX_MESSAGE_LENGTH } from '../max-constants'
import { maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
@@ -109,6 +110,44 @@ describe('QuestionInput', () => {
await waitFor(() => expect(slashCommandItem()).toBeInTheDocument())
})
+ describe('message length limit', () => {
+ const sendButton = (): HTMLElement | null => document.querySelector('[data-attr="max-send-message"]')
+
+ it('blocks a message the server would reject, and counts it in code points', async () => {
+ const input = screen.getByRole('textbox') as HTMLTextAreaElement
+
+ // Emoji are one code point each but two UTF-16 units, so a naive `String.length` check
+ // would block this message even though the server accepts it.
+ fireEvent.change(input, { target: { value: '😀'.repeat(MAX_MESSAGE_LENGTH) } })
+ await waitFor(() => expect(sendButton()).not.toHaveAttribute('aria-disabled', 'true'))
+
+ fireEvent.change(input, { target: { value: 'x'.repeat(MAX_MESSAGE_LENGTH + 1) } })
+ await waitFor(() => expect(sendButton()).toHaveAttribute('aria-disabled', 'true'))
+ expect(screen.getByText('40,001 / 40,000')).toBeInTheDocument()
+ })
+
+ it('leaves the counter out of the way until the message approaches the limit', async () => {
+ const input = screen.getByRole('textbox') as HTMLTextAreaElement
+
+ fireEvent.change(input, { target: { value: 'a short question' } })
+ await waitFor(() => expect(input.value).toBe('a short question'))
+ expect(screen.queryByText(/\/ 40,000$/)).not.toBeInTheDocument()
+ })
+
+ it('sends the whole suggestion when the send lands mid-animation', async () => {
+ const askMaxSpy = jest.spyOn(threadLogicInstance.actions, 'askMax')
+ const suggestion = 'What is the retention in the last two weeks?'
+
+ maxLogicInstance.actions.runSuggestion({ content: suggestion })
+ // The typewriter has only written the first character, so the composer shows a prefix.
+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('W'))
+
+ fireEvent.click(sendButton() as HTMLElement)
+
+ expect(askMaxSpy).toHaveBeenCalledWith(suggestion)
+ })
+ })
+
describe('stop button cancel state', () => {
const sendButton = (): HTMLElement | null => document.querySelector('[data-attr="max-send-message"]')
const stopButton = (): HTMLElement | null => document.querySelector('[data-attr="max-stop-generation"]')
diff --git a/frontend/src/scenes/max/components/QuestionInput.tsx b/frontend/src/scenes/max/components/QuestionInput.tsx
index 97c41d3cf2e9..6857b2615f61 100644
--- a/frontend/src/scenes/max/components/QuestionInput.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.tsx
@@ -20,6 +20,7 @@ import { ConversationQueueMessage } from '~/types'
import { ContextDisplay } from '../Context'
import { handsFreeLogic } from '../handsFreeLogic'
+import { MAX_MESSAGE_LENGTH, MESSAGE_TOO_LONG, messageLength } from '../max-constants'
import { maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
@@ -29,6 +30,12 @@ import { HandsFreeButton } from './HandsFreeButton'
import { HandsFreeSurface } from './HandsFreeSurface'
import { SlashCommandAutocomplete } from './SlashCommandAutocomplete'
+/**
+ * Show the character counter only once the message gets close to the limit. A permanent counter
+ * under every composer would be noise: almost every message is a couple of hundred characters.
+ */
+const LENGTH_COUNTER_THRESHOLD = MAX_MESSAGE_LENGTH * 0.9
+
interface QuestionInputProps {
isSticky?: boolean
placeholder?: string
@@ -146,8 +153,8 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
ref
) {
const { dataProcessingAccepted } = useValues(maxGlobalLogic)
- const { question, panelId: maxPanelId, fillInHint } = useValues(maxLogic)
- const { setQuestion, setFillInHint } = useActions(maxLogic)
+ const { question, panelId: maxPanelId, fillInHint, typingSuggestion } = useValues(maxLogic)
+ const { setQuestion, setFillInHint, cancelSuggestionTyping } = useActions(maxLogic)
const { user } = useValues(userLogic)
const {
conversation,
@@ -232,12 +239,27 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
// askMax reads the prompt arg directly and clears `question` afterwards, so drop any
// pending debounce to stop it from re-populating the just-sent text.
debouncedSetQuestion.cancel()
+ // A suggestion is still typing itself in. The user picked that suggestion, so send all of
+ // it rather than the prefix that happens to be on screen, and stop the animation writing
+ // the rest into the composer after the message has gone.
+ const content = typingSuggestion ?? prompt
+ if (typingSuggestion) {
+ cancelSuggestionTyping()
+ }
if (fillInHint) {
setFillInHint(null)
}
- askMax(prompt)
+ askMax(content)
}
+ // Counting code points is O(n), so only pay for it near the limit. A string's UTF-16 length is
+ // never below its code point count, so a shorter one can't be over the limit.
+ const promptLength = useMemo(
+ () => (inputValue.length >= LENGTH_COUNTER_THRESHOLD ? messageLength(inputValue) : null),
+ [inputValue]
+ )
+ const isOverLengthLimit = promptLength !== null && promptLength > MAX_MESSAGE_LENGTH
+
const hasQuestion = inputValue.trim().length > 0
// A fill-in suggestion typed its prefix in and is waiting for the user to complete it.
const showFillInHint = !!fillInHint
@@ -250,7 +272,9 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
? contextDisabledReason
: !inputValue
? 'I need some input first'
- : queueDisabledReason
+ : isOverLengthLimit
+ ? MESSAGE_TOO_LONG
+ : queueDisabledReason
// Update autocomplete visibility when the input changes
useEffect(() => {
@@ -488,6 +512,16 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
) : (
<ContextDisplay size={contextDisplaySize} />
)}
+ {promptLength !== null && (
+ <div
+ className={cn(
+ 'text-xs text-right pr-1 pt-1',
+ isOverLengthLimit ? 'text-error' : 'text-secondary'
+ )}
+ >
+ {promptLength.toLocaleString()} / {MAX_MESSAGE_LENGTH.toLocaleString()}
+ </div>
+ )}
</div>
)}
</label>
diff --git a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
index 336f4bcb8fd4..00debf8f8fce 100644
--- a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
+++ b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
@@ -24,9 +24,8 @@ export function SidebarQuestionInputWithSuggestions({
hideSuggestions?: boolean
}): JSX.Element {
const { dataProcessingAccepted, dataProcessingApprovalDisabledReason, activeSuggestionGroup } = useValues(maxLogic)
- const { setActiveGroup, setQuestion, focusInput, setFillInHint } = useActions(maxLogic)
+ const { setActiveGroup, setFillInHint, runSuggestion } = useActions(maxLogic)
const { agentMode } = useValues(maxThreadLogic)
- const { askMax } = useActions(maxThreadLogic)
const { coreMemory, coreMemoryLoading } = useValues(maxSettingsLogic)
const [settingsModalOpen, setSettingsModalOpen] = useState(false)
@@ -78,15 +77,7 @@ export function SidebarQuestionInputWithSuggestions({
/>
{selectedTopicData && (
<div className="w-full overflow-hidden" style={{ height: SUGGESTION_CARDS_HEIGHT_PX }}>
- <TopicSuggestions
- topic={selectedTopicData}
- onType={setQuestion}
- onSubmit={(text) => askMax(text)}
- onFillIn={(hint) => {
- setFillInHint(hint)
- focusInput()
- }}
- />
+ <TopicSuggestions topic={selectedTopicData} onRun={runSuggestion} />
</div>
)}
</div>
diff --git a/frontend/src/scenes/max/components/TopicBadges.tsx b/frontend/src/scenes/max/components/TopicBadges.tsx
index 42a50632759d..edbd6500415d 100644
--- a/frontend/src/scenes/max/components/TopicBadges.tsx
+++ b/frontend/src/scenes/max/components/TopicBadges.tsx
@@ -1,5 +1,5 @@
import { useValues } from 'kea'
-import { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import { IconCode } from '@posthog/icons'
import { LemonButton, LemonTag } from '@posthog/lemon-ui'
@@ -15,7 +15,6 @@ import { FileSystemIconType } from '~/queries/schema/schema-general'
import { SelfDrivingIntroModal } from 'products/signals/frontend/inbox/components/onboarding/SelfDrivingIntroModal'
import { CODE_BADGE, SuggestionTopic, TopicSuggestion } from '../suggestionTopics'
-import { nextTypingDelayMs } from '../utils/typing'
import { SuggestionCard } from './SuggestionCard'
// Colors the product icons (via iconForType's ProductIconWrapper). Applied inside the components so
@@ -109,61 +108,18 @@ export function TopicBadges({ topics, selectedKey, onSelect, className }: TopicB
export interface TopicSuggestionsProps {
topic: SuggestionTopic
- /** Called per keystroke of the typewriter animation, and once more with the full prompt. */
- onType: (text: string) => void
- /** Send the fully typed prompt to PostHog AI. */
- onSubmit: (text: string) => void
- /** Fired after a fill-in prompt is typed in — the parent shows `hint` as a postfix cue + focuses. */
- onFillIn: (hint: string) => void
+ /**
+ * Run the suggestion. `maxLogic` owns the typewriter that writes it into the composer, so a send
+ * that lands mid-animation still carries the whole suggestion.
+ */
+ onRun: (suggestion: TopicSuggestion) => void
className?: string
}
/**
* The suggestion cards for a selected topic. Fills its parent's baseline height (`h-full`).
*/
-export function TopicSuggestions({ topic, onType, onSubmit, onFillIn, className }: TopicSuggestionsProps): JSX.Element {
- // Cancels an in-flight typewriter animation (new click, or unmount).
- const cancelTypingRef = useRef<(() => void) | null>(null)
- useEffect(() => () => cancelTypingRef.current?.(), [])
-
- // Type the prompt at a human pace, then either send it, or — for a fill-in prompt — add a
- // trailing space and hand the hint to the parent so it can show the postfix cue.
- const runSuggestion = (suggestion: TopicSuggestion): void => {
- cancelTypingRef.current?.()
- const { content, requiresUserInput, hint } = suggestion
- let cancelled = false
- let timer: ReturnType<typeof setTimeout> | undefined
- cancelTypingRef.current = () => {
- cancelled = true
- if (timer) {
- clearTimeout(timer)
- }
- }
- const finish = (): void => {
- if (cancelled) {
- return
- }
- if (requiresUserInput) {
- onType(`${content} `)
- onFillIn(hint ?? 'the details')
- } else {
- onSubmit(content)
- }
- }
- const typeTo = (i: number): void => {
- if (cancelled) {
- return
- }
- onType(content.slice(0, i))
- if (i >= content.length) {
- timer = setTimeout(finish, 250)
- return
- }
- timer = setTimeout(() => typeTo(i + 1), nextTypingDelayMs(content[i - 1] ?? '', content[i]))
- }
- typeTo(1)
- }
-
+export function TopicSuggestions({ topic, onRun, className }: TopicSuggestionsProps): JSX.Element {
// Docs-style: a plain question list (like production's Docs suggestions), reading as an
// explanation rather than an action. Card-style: icon + bold title + description.
const isDocs = topic.variant === 'docs'
@@ -181,7 +137,7 @@ export function TopicSuggestions({ topic, onType, onSubmit, onFillIn, className
className="flex-1 min-h-0"
fullWidth
type="tertiary"
- onClick={() => runSuggestion(suggestion)}
+ onClick={() => onRun(suggestion)}
data-attr={`capability-suggestion-${topic.key}`}
>
<span className="text-sm font-normal text-left truncate w-full">{suggestion.content}</span>
@@ -195,7 +151,7 @@ export function TopicSuggestions({ topic, onType, onSubmit, onFillIn, className
title={suggestion.title ?? suggestion.content}
description={suggestion.description}
icon={iconForType(iconType)}
- onClick={() => runSuggestion(suggestion)}
+ onClick={() => onRun(suggestion)}
data-attr={`capability-suggestion-${topic.key}`}
/>
)
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index b3d9ec96a75b..e9484f82ee58 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -43,6 +43,24 @@ export interface DisplayFormatterContext {
registeredToolMap: Record<string, ToolRegistration>
}
+/**
+ * Longest message the server accepts. Mirrors `MAX_MESSAGE_CONTENT_LENGTH` in ee/api/conversation.py;
+ * keep the two in sync. Anything longer comes back as a 400 on the `content` field.
+ */
+export const MAX_MESSAGE_LENGTH = 40000
+
+/** Shown when a message is over `MAX_MESSAGE_LENGTH`, both before sending and if the server rejects it. */
+export const MESSAGE_TOO_LONG = `Your message is too long. Shorten it to ${MAX_MESSAGE_LENGTH.toLocaleString()} characters or fewer.`
+
+/**
+ * Counts the way the server's `CharField` does: it trims whitespace, then measures Unicode code
+ * points (Python `len`), not UTF-16 units. Emoji are one code point each but two UTF-16 units, so
+ * `String.length` would reject messages the server accepts.
+ */
+export function messageLength(content: string): number {
+ return Array.from(content.trim()).length
+}
+
/** Static tool definition for display purposes. */
export interface ToolDefinition<N extends string = string> {
/** A user-friendly display name for the tool. Must be a verb phrase, like "Create surveys" or "Search docs" */
diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.ts
index 0f1db983c7bc..8deac1a6e41c 100644
--- a/frontend/src/scenes/max/maxLogic.test.ts
+++ b/frontend/src/scenes/max/maxLogic.test.ts
@@ -743,4 +743,64 @@ describe('maxLogic', () => {
})
})
})
+
+ describe('suggestion typewriter', () => {
+ const SUGGESTION = { content: 'What is the retention in the last two weeks?' }
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ logic = maxLogic({ panelId: 'test' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('holds the whole suggestion while the composer still shows a prefix', () => {
+ logic.actions.runSuggestion(SUGGESTION)
+
+ // The composer is mid-animation, so a send right now would carry this prefix. Keeping the
+ // whole suggestion is what lets the send substitute it.
+ expect(logic.values.question).toBe('W')
+ expect(logic.values.typingSuggestion).toBe(SUGGESTION.content)
+ })
+
+ it('sends the whole suggestion once the animation finishes', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.runSuggestion(SUGGESTION)
+ jest.advanceTimersByTime(60000)
+ }).toDispatchActions([
+ (action: any) =>
+ action.type === logic.actionTypes.askMax && action.payload.prompt === SUGGESTION.content,
+ ])
+
+ expect(logic.values.typingSuggestion).toBeNull()
+ })
+
+ it('stops the animation when the user types over it', () => {
+ logic.actions.runSuggestion(SUGGESTION)
+ logic.actions.setQuestion('my own question')
+
+ // The user's input wins: no pending send, and the animation stops writing over them.
+ expect(logic.values.typingSuggestion).toBeNull()
+ jest.advanceTimersByTime(60000)
+ expect(logic.values.question).toBe('my own question')
+ })
+
+ it('leaves a fill-in suggestion for the user to complete instead of sending it', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.runSuggestion({
+ content: 'Tell me about feature flag',
+ requiresUserInput: true,
+ hint: 'insert feature flag name',
+ })
+ jest.advanceTimersByTime(60000)
+ }).toNotHaveDispatchedActions(['askMax'])
+
+ expect(logic.values.question).toBe('Tell me about feature flag ')
+ expect(logic.values.fillInHint).toBe('insert feature flag name')
+ expect(logic.values.typingSuggestion).toBeNull()
+ })
+ })
})
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index 33413a5884f3..d14f8053201e 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -31,6 +31,8 @@ import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'
import { maxContextLogic } from './maxContextLogic'
import { maxGlobalLogic, type PhaiViewMode } from './maxGlobalLogic'
import { MaxUIContext } from './maxTypes'
+import type { TopicSuggestion } from './suggestionTopics'
+import { nextTypingDelayMs } from './utils/typing'
/** Maximum age for restored prompts (5 minutes) */
const PENDING_PROMPT_MAX_AGE_MS = 5 * 60 * 1000
@@ -195,6 +197,7 @@ export interface maxLogicValues {
threadVisible: boolean
toolDescriptions: (string | undefined)[]
toolHeadlines: (string | undefined)[]
+ typingSuggestion: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -246,6 +249,9 @@ export interface maxLogicActions {
prompt: string | null
uiContext: Partial<MaxUIContext> | undefined
}
+ cancelSuggestionTyping: () => {
+ value: true
+ }
decrActiveStreamingThreads: () => {
value: true
}
@@ -273,6 +279,9 @@ export interface maxLogicActions {
currentRecursionDepth: number
leadingTimeout: number
}
+ runSuggestion: (suggestion: TopicSuggestion) => {
+ suggestion: TopicSuggestion
+ }
scrollThreadToBottom: (behavior?: 'instant' | 'smooth') => {
behavior: 'instant' | 'smooth' | undefined
}
@@ -297,6 +306,9 @@ export interface maxLogicActions {
setQuestion: (question: string) => {
question: string
}
+ setTypingSuggestion: (content: string | null) => {
+ content: string | null
+ }
startNewConversation: () => {
value: true
}
@@ -399,6 +411,9 @@ export const maxLogic = kea<maxLogicType>([
actions({
setQuestion: (question: string) => ({ question }), // update the form input
+ runSuggestion: (suggestion: TopicSuggestion) => ({ suggestion }),
+ cancelSuggestionTyping: true,
+ setTypingSuggestion: (content: string | null) => ({ content }),
askMax: (prompt: string | null, addToThread: boolean = true, uiContext?: Partial<MaxUIContext>) => ({
prompt,
addToThread,
@@ -514,6 +529,19 @@ export const maxLogic = kea<maxLogicType>([
},
],
+ /**
+ * Whole text of the suggestion the typewriter is writing in, so a send that lands mid-animation
+ * carries all of it instead of the prefix on screen. Null for a fill-in suggestion, which is a
+ * prefix the user is meant to complete themselves.
+ */
+ typingSuggestion: [
+ null as string | null,
+ {
+ setTypingSuggestion: (_, { content }) => content,
+ startNewConversation: () => null,
+ },
+ ],
+
autoRun: [false as boolean, { setAutoRun: (_, { autoRun }) => autoRun, startNewConversation: () => false }],
})),
@@ -686,8 +714,13 @@ export const maxLogic = kea<maxLogicType>([
],
}),
- listeners(({ actions, values, props }) => ({
+ listeners(({ actions, values, props, cache }) => ({
setQuestion: ({ question }) => {
+ // A question that isn't what the typewriter just wrote means the user typed over the
+ // suggestion or sent it: their input wins, so stop the animation and its pending send.
+ if (cache.suggestionTypingText != null && question !== cache.suggestionTypingText) {
+ actions.cancelSuggestionTyping()
+ }
// Side panel Max stays mounted across the whole app, so its question reducer
// already survives navigation — and there's no removeTab cleanup for it,
// which would turn the persisted draft into a memory leak.
@@ -696,6 +729,54 @@ export const maxLogic = kea<maxLogicType>([
actions.setChatDraftForTab(tabId, question)
}
},
+ runSuggestion: ({ suggestion }) => {
+ const { content, requiresUserInput, hint } = suggestion
+ // A fill-in suggestion types in a prefix for the user to complete, so it never becomes a
+ // pending send. Anything else does, and holding the whole text here is what lets a send
+ // mid-animation carry the full suggestion rather than the prefix on screen.
+ actions.setTypingSuggestion(requiresUserInput ? null : content)
+ // Re-adding under the same key cancels a still-running animation when the user clicks
+ // another suggestion.
+ cache.disposables.add(() => {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const type = (text: string): void => {
+ // Record what the animation wrote before dispatching, so the setQuestion
+ // listener can tell an animation tick from the user typing over it
+ cache.suggestionTypingText = text
+ actions.setQuestion(text)
+ }
+ const finish = (): void => {
+ if (requiresUserInput) {
+ type(`${content} `)
+ actions.setFillInHint(hint ?? 'the details')
+ actions.focusInput()
+ } else {
+ actions.askMax(content)
+ }
+ actions.cancelSuggestionTyping()
+ }
+ const typeTo = (i: number): void => {
+ type(content.slice(0, i))
+ timer =
+ i >= content.length
+ ? setTimeout(finish, 250)
+ : setTimeout(() => typeTo(i + 1), nextTypingDelayMs(content[i - 1] ?? '', content[i]))
+ }
+ typeTo(1)
+ return () => {
+ cache.suggestionTypingText = null
+ if (timer) {
+ clearTimeout(timer)
+ }
+ }
+ }, 'suggestionTyping')
+ },
+ cancelSuggestionTyping: () => {
+ cache.disposables.dispose('suggestionTyping')
+ if (values.typingSuggestion !== null) {
+ actions.setTypingSuggestion(null)
+ }
+ },
// Listen for when the side panel state changes and check for initial prompt
[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {
if (tab === SidePanelTab.Max && options && typeof options === 'string') {
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index 60c18c40ba0c..8b5376f00cd0 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -35,7 +35,7 @@ import { Conversation, ConversationDetail, ConversationStatus, ConversationType,
import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
-import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'
+import { EnhancedToolCall, MESSAGE_TOO_LONG, TOOL_DEFINITIONS } from './max-constants'
import { maxContextLogic } from './maxContextLogic'
import { maxGlobalLogic } from './maxGlobalLogic'
import { maxLogic } from './maxLogic'
@@ -1381,25 +1381,50 @@ describe('maxThreadLogic', () => {
threadGrouped: expect.arrayContaining([
expect.objectContaining({
type: AssistantMessageType.Failure,
- content: 'Oops! Your message is too long. Ensure it has no more than 40000 characters.',
+ content: MESSAGE_TOO_LONG,
}),
]),
})
})
+
+ it('still counts an over-length message as a failed turn', async () => {
+ // The length error is silenced in error tracking but must stay a failure in telemetry:
+ // silencing it by clearing `releaseException` instead would hide the turn entirely.
+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
+ jest.spyOn(api.conversations, 'stream').mockRejectedValue(
+ new ApiError('Bad Request', 400, undefined, { attr: 'content', detail: 'Content too long' })
+ )
+
+ logic.unmount()
+ maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)
+ logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.askMax('hello')
+ }).toDispatchActions(['askMax', 'addMessage', 'completeThreadGeneration'])
+
+ expect(captureSpy).toHaveBeenCalledWith(
+ 'max conversation turn completed',
+ expect.objectContaining({ status: 'failure', error_status_code: 400, prompt_length: 5 })
+ )
+ })
})
describe('error tracking capture gating', () => {
- // 402 (out of AI credits) and 429 (rate limited) are expected business conditions shown
- // to the user, so they must not be reported to error tracking; genuine failures (500) must.
+ // 402 (out of AI credits), 429 (rate limited), and a message over the length limit are
+ // expected business conditions shown to the user, so they must not be reported to error
+ // tracking; genuine failures (500) must.
it.each([
- [402, false],
- [429, false],
- [500, true],
- ])('status %s reports exception: %s', async (status, shouldCapture) => {
+ ['does not report being out of AI credits', 402, {}, false],
+ ['does not report being rate limited', 429, {}, false],
+ ['does not report a message over the length limit', 400, { attr: 'content' }, false],
+ ['reports a server failure', 500, {}, true],
+ ])('%s', async (_label, status, data, shouldCapture) => {
const captureExceptionSpy = jest
.spyOn(posthog, 'captureException')
.mockImplementation(() => undefined as any)
- jest.spyOn(api.conversations, 'stream').mockRejectedValue(new ApiError('error', status, undefined, {}))
+ jest.spyOn(api.conversations, 'stream').mockRejectedValue(new ApiError('error', status, undefined, data))
logic.unmount()
maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index 89deed838637..8861b3cb161b 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -84,10 +84,12 @@ import { handsFreeLogic } from './handsFreeLogic'
import { summariseAssistantThread } from './handsFreeUtils'
import {
EnhancedToolCall,
+ MESSAGE_TOO_LONG,
MODE_DEFINITIONS,
TOOL_DEFINITIONS,
ToolRegistration,
getModeDisplayName,
+ messageLength,
} from './max-constants'
import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'
import { MaxBillingContext, maxBillingContextLogic } from './maxBillingContextLogic'
@@ -1265,6 +1267,11 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
const traceId = uuid()
actions.setTraceId(traceId)
+ // How long the message was, never the message itself. A prompt that arrives truncated is
+ // otherwise invisible outside session recordings, because no send event records a length.
+ // Null content means resume/continue rather than a new message.
+ const promptLength = typeof streamData.content === 'string' ? messageLength(streamData.content) : undefined
+
// Sandbox runtime: route the message to a non-streaming products/tasks Run, then hand the
// SSE connection off to runStreamLogic. The LangGraph EventSource loop below is never
// entered for sandbox conversations.
@@ -1494,6 +1501,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
trace_id: traceId,
agent_mode: agentMode,
generation_attempt: generationAttempt,
+ prompt_length: promptLength,
})
}
@@ -1534,10 +1542,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
releaseException = false
}
- // Validation exception for the content length
+ // Validation exception for the content length. The user is told what to do
+ // and can retry, so this is an expected condition rather than a crash, and
+ // it stays out of error tracking. `releaseException` is left alone so the
+ // turn is still counted as a failure in telemetry.
if (e.data?.attr === 'content') {
- relevantErrorMessage.content =
- 'Oops! Your message is too long. Ensure it has no more than 40000 characters.'
+ relevantErrorMessage.content = MESSAGE_TOO_LONG
+ reportException = false
} else if (e.detail) {
relevantErrorMessage.content = e.detail
}
@@ -1605,6 +1616,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
: e instanceof ApiError
? 'api_error'
: 'unknown_error',
+ prompt_length: promptLength,
})
// Remove streaming messages and reload from server (source of truth)
actions.finalizeStreamingMessages()
@@ -1629,6 +1641,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
trace_id: traceId,
agent_mode: agentMode,
generation_attempt: generationAttempt,
+ prompt_length: promptLength,
})
}
actions.completeThreadGeneration()
diff --git a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
index b1decb0a7571..add5ace32003 100644
--- a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
+++ b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
@@ -26,6 +26,9 @@ export function HomepageThread(): JSX.Element {
// Send the initial query once on mount
const hasSentInitial = useRef(false)
+ // Depends on `query` so a prompt that lands after mount is still sent. With an empty dependency
+ // list the effect read whatever `query` held on the first render, so a prompt set a tick later
+ // was dropped, and the send went out against a stale snapshot.
useEffect(() => {
if (query && !hasSentInitial.current) {
hasSentInitial.current = true
@@ -34,7 +37,7 @@ export function HomepageThread(): JSX.Element {
askMax(query)
}, 100)
}
- }, []) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [query]) // eslint-disable-line react-hooks/exhaustive-deps
const threadProps: MaxThreadLogicProps = {
panelId: HOMEPAGE_TAB_ID,