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): debounce sandbox composer draft to stop sidebar typing lag (#69214)

Paul D'Ambra8ee320b3fcc0
diff --git a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts
new file mode 100644
index 000000000000..ade32aa8e2d0
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts
@@ -0,0 +1,53 @@
+import { useEffect, useState } from 'react'
+import { useDebouncedCallback } from 'use-debounce'
+
+export interface DebouncedDraft {
+ /** Local echo to bind to `Composer.Root`'s `value` — updated synchronously on every keystroke. */
+ value: string
+ /** Bind to `Composer.Root`'s `onChange` — updates the local echo now, syncs upstream on a debounce. */
+ onChange: (next: string) => void
+ /** Wrap the caller's submit so the latest keystroke is flushed to the owning logic before it reads the draft. */
+ submit: (send: () => void) => void
+}
+
+/**
+ * Buffers a composer draft in local component state and debounces the write to the owning kea logic, so each
+ * keystroke is an isolated, cheap re-render rather than a store dispatch that notifies every subscriber.
+ * Binding the composer straight to kea made every keystroke re-render every subscriber — next to a mounted
+ * thread/virtualizer that's what makes typing lag, and it grows with conversation length. kea stays the
+ * source of truth: external changes (draft restore, clear-on-submit) are mirrored back, the pending value is
+ * flushed synchronously before submit so the send never races the debounce, and any pending draft is flushed
+ * on unmount. Mirrors the fix in `scenes/max/components/QuestionInput.tsx` for the same problem.
+ */
+export function useDebouncedDraft(externalValue: string, sync: (value: string) => void, delayMs = 150): DebouncedDraft {
+ const [value, setValue] = useState(externalValue)
+ const debouncedSync = useDebouncedCallback(sync, delayMs)
+
+ // Flush a pending draft on unmount so text typed just before teardown still persists to kea.
+ useEffect(() => () => debouncedSync.flush(), [debouncedSync])
+
+ // Mirror external changes (suggestion insertion, draft restore, clear-on-submit) into the local echo.
+ // Cancel any in-flight keystroke sync first: an external write can land while a debounced sync from
+ // prior typing is still pending, and without cancelling that stale sync fires ~150ms later and clobbers
+ // the external value (e.g. type in the task composer, then click a suggestion). The debounce coalesces
+ // to the latest keystroke and only fires once typing pauses, so its own write echoes back an equal value
+ // here (a no-op cancel + no-op setValue) — cancelling never drops an in-progress keystroke.
+ useEffect(() => {
+ debouncedSync.cancel()
+ setValue(externalValue)
+ }, [externalValue, debouncedSync])
+
+ return {
+ value,
+ onChange: (next: string): void => {
+ setValue(next)
+ debouncedSync(next)
+ },
+ submit: (send: () => void): void => {
+ // Flush the pending keystroke synchronously so the send reads the latest draft, not the stale
+ // debounced value; a no-op when nothing is pending (kea already has it).
+ debouncedSync.flush()
+ send()
+ },
+ }
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 7ad8e671ecb2..95cb8b06ad97 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -12,14 +12,19 @@ import {
import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
+import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
import { RepositorySelector } from './RepositorySelector'
export function TaskComposer(): JSX.Element {
const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion } =
useActions(taskTrackerSceneLogic)
- const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline, sendDisabledReason } =
- useValues(taskTrackerSceneLogic)
+ const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline } = useValues(taskTrackerSceneLogic)
+
+ // Buffer the description locally and debounce the write to kea so each keystroke is a cheap, isolated
+ // re-render instead of a store dispatch. `Composer.Root` already blocks send on an empty `draft.value`
+ // internally, so there's no need to pass a `disabledReason` derived from the logic's debounced value.
+ const draft = useDebouncedDraft(newTaskData.description, (value) => setNewTaskData({ description: value }))
const textAreaRef = useRef<HTMLTextAreaElement>(null)
@@ -48,11 +53,10 @@ export function TaskComposer(): JSX.Element {
onChange={(config) => setNewTaskData({ repositoryConfig: config })}
/>
<Composer.Root
- value={newTaskData.description}
- onChange={(value) => setNewTaskData({ description: value })}
- onSubmit={submitNewTask}
+ value={draft.value}
+ onChange={draft.onChange}
+ onSubmit={() => draft.submit(submitNewTask)}
loading={isSubmittingTask}
- disabledReason={sendDisabledReason}
textAreaRef={textAreaRef}
>
<Composer.Frame>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index b6f4a1c55ede..6246a64d0194 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -8,6 +8,7 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
+import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
export interface TaskRunChatProps {
@@ -57,19 +58,6 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunC
}
function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {
- const { composerForm, isSubmitting, isBusy, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(
- runInteractionLogic(logicProps)
- )
- const {
- setComposerFormValues,
- submitComposerForm,
- cancelRun,
- updateQueuedMessage,
- removeQueuedMessage,
- setModel,
- setEffort,
- } = useActions(runInteractionLogic(logicProps))
-
return (
// `RunSurface.Root` and `runInteractionLogic` deliberately share the same stream key (`streamKey ?? runId`,
// resolved inside each): the composer slot's gating must read the exact stream the thread renders. The
@@ -84,46 +72,69 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicPro
<RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
<RunSurface.Composer>
<RunSurface.Resources />
- <Composer.Root
- value={composerForm.draft}
- onChange={(value) => setComposerFormValues({ draft: value })}
- onSubmit={submitComposerForm}
- loading={isSubmitting}
- isTurnActive={isBusy}
- onStop={() => cancelRun()}
- >
- {queuedMessages.length > 0 && (
- <Composer.Banner>
- <QueuedMessageList
- messages={queuedMessages}
- onUpdate={updateQueuedMessage}
- onRemove={removeQueuedMessage}
- />
- </Composer.Banner>
- )}
- <Composer.Frame>
- <Composer.Field>
- <Composer.Placeholder>
- {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
- </Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" />
- </Composer.Field>
- <Composer.Footer>
- {/* Model/effort picker: selection lives in the bound runInteractionLogic and is
- applied when the message is sent — synced to the running agent on a follow-up,
- or used to seed the next run once terminal. */}
- <ComposerModelEffortPickers
- selectedModel={selectedModel}
- selectedEffort={selectedEffort}
- onModelChange={setModel}
- onEffortChange={setEffort}
- />
- </Composer.Footer>
- </Composer.Frame>
- <Composer.Submit data-attr="sandbox-composer-send" />
- </Composer.Root>
+ {/* The composer owns the per-keystroke draft in an isolated child so typing never re-renders
+ the thread/virtualizer rendered as its sibling above — that cascade is what made the input lag. */}
+ <LiveComposer logicProps={logicProps} />
</RunSurface.Composer>
</div>
</RunSurface.Root>
)
}
+
+function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {
+ const { composerForm, isSubmitting, isBusy, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(
+ runInteractionLogic(logicProps)
+ )
+ const {
+ setComposerFormValues,
+ submitComposerForm,
+ cancelRun,
+ updateQueuedMessage,
+ removeQueuedMessage,
+ setModel,
+ setEffort,
+ } = useActions(runInteractionLogic(logicProps))
+
+ const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))
+
+ return (
+ <Composer.Root
+ value={draft.value}
+ onChange={draft.onChange}
+ onSubmit={() => draft.submit(submitComposerForm)}
+ loading={isSubmitting}
+ isTurnActive={isBusy}
+ onStop={() => cancelRun()}
+ >
+ {queuedMessages.length > 0 && (
+ <Composer.Banner>
+ <QueuedMessageList
+ messages={queuedMessages}
+ onUpdate={updateQueuedMessage}
+ onRemove={removeQueuedMessage}
+ />
+ </Composer.Banner>
+ )}
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>
+ {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
+ </Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" />
+ </Composer.Field>
+ <Composer.Footer>
+ {/* Model/effort picker: selection lives in the bound runInteractionLogic and is
+ applied when the message is sent — synced to the running agent on a follow-up,
+ or used to seed the next run once terminal. */}
+ <ComposerModelEffortPickers
+ selectedModel={selectedModel}
+ selectedEffort={selectedEffort}
+ onModelChange={setModel}
+ onEffortChange={setEffort}
+ />
+ </Composer.Footer>
+ </Composer.Frame>
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </Composer.Root>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index c8a4944c74f5..0263bb1e4386 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, connect, events, kea, key, listeners, path, props, reducers } from 'kea'
import { router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
@@ -142,14 +142,6 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
],
}),
- selectors({
- sendDisabledReason: [
- (s) => [s.newTaskData],
- (newTaskData): string | undefined =>
- !newTaskData.description.trim() ? 'Describe the task first' : undefined,
- ],
- }),
-
listeners(({ actions, values, cache, props }) => ({
// Release the manually-mounted optimistic stream once the create resolves (navigated to the real run)
// or fails (returned to the composer), so the throwaway draft instance never leaks.