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.

feat(tasks): stop focused chat runs with escape (#96631)

Georgiy Tarasov6efb1555a307
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e9a5abb3ac04..1338871e11e7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5576,6 +5576,10 @@ snapshots:
hash: v1.k794b7964.410f559d98dc233ee8047dd8cfd5ce5f16bf47298ac0f3ea7c38e21913f3e79e._jbCcWpMORUlIHh_Te_m_hWib0TJ1zlg4bw-cm35FTI
products-posthog-ai-runalertactivity--connection-lost--light:
hash: v1.k794b7964.6a54547f7784b2a6ddcdde131600ed37ee2abdb56180e9cff603e8a7a3e395bf.cUg8KJHc-L7D6KFrCng16YTN5A0-WRMfw75cElwkroI
+ products-posthog-ai-startup-chat--sidebar--dark:
+ hash: v1.k794b7964.97e75539fb76cb77f57dce890bba8174746a999ac0f00fa4b6c0b27b197892f6.HxsSbUTC0_6SGTHo867GUBAgfdVQGH1_mKgZxVl-k1c
+ products-posthog-ai-startup-chat--sidebar--light:
+ hash: v1.k794b7964.1447c8f9e17c9d9fc09f81ec8469ec0629bafef796c45c3c66894961ad4d978f.H-qJsZXlEGLNeIzG2_tb_L5OarwFKvYVoktKd2p6w-w
products-posthog-ai-virtualizedthread--anchored-open--dark:
hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
products-posthog-ai-virtualizedthread--anchored-open--light:
diff --git a/frontend/src/scenes/max/components/QuestionInput.test.tsx b/frontend/src/scenes/max/components/QuestionInput.test.tsx
index 1d8a9884a283..058a8d9f8065 100644
--- a/frontend/src/scenes/max/components/QuestionInput.test.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { BindLogic, Provider } from 'kea'
import { useMocks } from '~/mocks/jest'
@@ -95,18 +96,19 @@ describe('QuestionInput', () => {
})
it('reopens the popover after Escape dismisses it and a fresh slash is typed', async () => {
+ const user = userEvent.setup()
const input = screen.getByRole('textbox') as HTMLTextAreaElement
- fireEvent.change(input, { target: { value: '/' } })
+ await user.type(input, '/')
await waitFor(() => expect(slashCommandItem()).toBeInTheDocument())
- fireEvent.keyDown(document, { key: 'Escape' })
+ await user.keyboard('{Escape}')
await waitFor(() => expect(slashCommandItem()).not.toBeInTheDocument())
- fireEvent.change(input, { target: { value: '' } })
+ await user.clear(input)
await waitFor(() => expect(input.value).toBe(''))
- fireEvent.change(input, { target: { value: '/' } })
+ await user.type(input, '/')
await waitFor(() => expect(slashCommandItem()).toBeInTheDocument())
})
diff --git a/products/posthog_ai/frontend/components/PermissionInput.test.tsx b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
index 3773b93c27ef..596128d8dea9 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.test.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
@@ -66,6 +66,10 @@ describe('PermissionInput', () => {
fireEvent.keyDown(input, { key: 'Enter' })
expect(respondToPermission).toHaveBeenCalledTimes(2)
expect(respondToPermission.mock.calls[1]).toEqual(respondToPermission.mock.calls[0])
+
+ rerender(<PermissionInput streamKey="run-1" request={request} disabled />)
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(respondToPermission).toHaveBeenCalledTimes(2)
}
)
})
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index 24526d8f8c1d..3969f63f82ec 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -24,6 +24,7 @@ import { lookupToolRenderer } from './tool/toolRegistry'
interface PermissionInputProps {
streamKey: string
request: PermissionRequestRecord
+ disabled?: boolean
}
/** Collapsed height of the payload preview, in lines — enough to scan, never enough to bury the choices. */
@@ -326,10 +327,11 @@ function PermissionOptionRows({ options, responding, onRespond }: PermissionOpti
* `respondingToPermission` drives the loading/double-submit guard and re-enables the controls when the
* POST fails (the pending request only clears on success).
*/
-export function PermissionInput({ streamKey, request }: PermissionInputProps): JSX.Element {
+export function PermissionInput({ streamKey, request, disabled = false }: PermissionInputProps): JSX.Element {
const boundLogic = runStreamLogic({ streamKey })
const { respondToPermission, cancelRun } = useActions(boundLogic)
- const { respondingToPermission } = useValues(boundLogic)
+ const { respondingToPermission: delivering } = useValues(boundLogic)
+ const respondingToPermission = delivering || disabled
// A plan approval keeps the product's Auto and Full auto wire options. If neither is offered,
// fall through to the generic card so the request stays actionable.
diff --git a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
index affe4e182a2b..41135c40e7dc 100644
--- a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
+++ b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
@@ -251,6 +251,9 @@ export function PlanApprovalSelector({
// any element outside the card keeps native Tab/Enter behavior.
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape' && containerRef.current?.closest('[data-run-escape-scope]')) {
+ return
+ }
if (responding || rejectSelected || e.defaultPrevented) {
return
}
@@ -350,7 +353,7 @@ export function PlanApprovalSelector({
const approveActive = selectedIndex === 0 || hoveredIndex === 0
return (
- <div ref={containerRef} className="rounded border bg-surface-primary p-3">
+ <div ref={containerRef} tabIndex={-1} className="rounded border bg-surface-primary p-3">
<div className="flex flex-col gap-2">
<span className="font-medium text-[13px] text-accent">Implementation Plan</span>
@@ -417,6 +420,7 @@ export function PlanApprovalSelector({
onEscape={() => {
setFeedback('')
selectRow(0)
+ containerRef.current?.focus()
}}
onSubmit={submitReject}
/>
diff --git a/products/posthog_ai/frontend/components/QuestionInput.tsx b/products/posthog_ai/frontend/components/QuestionInput.tsx
index c69ef48d05cb..0fb7f33440e4 100644
--- a/products/posthog_ai/frontend/components/QuestionInput.tsx
+++ b/products/posthog_ai/frontend/components/QuestionInput.tsx
@@ -14,6 +14,7 @@ import { QuestionField } from './QuestionField'
interface QuestionInputProps {
streamKey: string
request: PermissionRequestRecord
+ disabled?: boolean
}
/** Adapt a sandbox question onto the `MultiQuestionFormQuestion` shape `QuestionField` renders. */
@@ -47,10 +48,11 @@ function selectedLabels(answer: string | string[] | undefined): string[] {
* text — the agent reads `_meta.answers`; `optionId` only has to be a valid offered option (derived
* from the first question's selection). `respondingToPermission` drives the loading / double-submit guard.
*/
-export function QuestionInput({ streamKey, request }: QuestionInputProps): JSX.Element | null {
+export function QuestionInput({ streamKey, request, disabled = false }: QuestionInputProps): JSX.Element | null {
const boundLogic = runStreamLogic({ streamKey })
const { respondToPermission } = useActions(boundLogic)
- const { respondingToPermission } = useValues(boundLogic)
+ const { respondingToPermission: delivering } = useValues(boundLogic)
+ const respondingToPermission = delivering || disabled
// Stable reference so the memoized callbacks below don't re-evaluate every render.
const questions = useMemo(() => request.questions ?? [], [request.questions])
diff --git a/products/posthog_ai/frontend/components/RunEscapeBoundary.test.tsx b/products/posthog_ai/frontend/components/RunEscapeBoundary.test.tsx
new file mode 100644
index 000000000000..31a814de5369
--- /dev/null
+++ b/products/posthog_ai/frontend/components/RunEscapeBoundary.test.tsx
@@ -0,0 +1,203 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { createRef } from 'react'
+
+import posthog from 'lib/posthog-typed'
+
+import { mapPermissionOptions } from '../policy/permissionUtils'
+import { PlanApprovalSelector } from './PlanApprovalActions'
+import { RunEscapeBoundary } from './RunEscapeBoundary'
+
+jest.mock('lib/posthog-typed', () => ({
+ __esModule: true,
+ default: { __loaded: true, capture: jest.fn() },
+}))
+
+describe('RunEscapeBoundary', () => {
+ beforeEach(() => {
+ jest.mocked(posthog.capture).mockClear()
+ jest.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue({ length: 1 } as DOMRectList)
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['chat', 'composer', true],
+ ['chat', 'composer button', true],
+ ['chat', 'message', true],
+ ['chat', 'approval', true],
+ ['chat', 'outside', false],
+ ['composer', 'composer', true],
+ ['composer', 'composer button', true],
+ ['composer', 'message', false],
+ ['composer', 'approval', true],
+ ['composer', 'outside', false],
+ ] as const)('%s handles Escape from %s: %s', (scope, target, expected) => {
+ const onEscape = jest.fn()
+ const textAreaRef = createRef<HTMLTextAreaElement>()
+ render(
+ <>
+ <RunEscapeBoundary scope={scope} textAreaRef={textAreaRef} onEscape={onEscape}>
+ <form>
+ <textarea ref={textAreaRef} data-attr="composer" />
+ <button data-attr="composer button">Send</button>
+ </form>
+ <button data-attr="message">Message action</button>
+ <div data-attr="run-approval">
+ <button data-attr="approval">Approve</button>
+ </div>
+ </RunEscapeBoundary>
+ <button data-attr="outside">Another panel</button>
+ </>
+ )
+ const element = screen.getByTestId(target)
+ element.focus()
+ fireEvent.keyDown(element, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(expected ? 1 : 0)
+ expect(jest.mocked(posthog.capture).mock.calls).toEqual(
+ expected ? [['keybind triggered', { keybind: 'escape', mechanism: 'hotkey' }]] : []
+ )
+ })
+
+ it('handles Escape after the focused new-task composer is replaced by startup', () => {
+ const onEscape = jest.fn()
+ const { rerender } = render(<textarea data-attr="new-task-composer" />)
+ screen.getByTestId('new-task-composer').focus()
+
+ rerender(
+ <RunEscapeBoundary scope="chat" focusKey="startup" onEscape={onEscape}>
+ <p>Starting task</p>
+ </RunEscapeBoundary>
+ )
+ expect(document.activeElement).toBe(document.body)
+ fireEvent.keyDown(document.body, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(['body', 'main'])(
+ 'retains main chat ownership while reading with %s focus, and relinquishes it on another panel interaction',
+ (focusTarget) => {
+ const main = jest.fn()
+ const sidebar = jest.fn()
+ render(
+ <main tabIndex={-1} data-attr="page">
+ <RunEscapeBoundary scope="chat" onEscape={main}>
+ <p>Main message</p>
+ </RunEscapeBoundary>
+ <RunEscapeBoundary scope="composer" onEscape={sidebar}>
+ <p>Sidebar message</p>
+ </RunEscapeBoundary>
+ </main>
+ )
+ const target = focusTarget === 'main' ? screen.getByTestId('page') : document.body
+ fireEvent.pointerDown(screen.getByText('Main message'))
+ target.focus()
+ fireEvent.keyDown(target, { key: 'Escape' })
+ expect(main).toHaveBeenCalledTimes(1)
+ fireEvent.pointerDown(screen.getByText('Sidebar message'))
+ target.focus()
+ fireEvent.keyDown(target, { key: 'Escape' })
+ expect(main).toHaveBeenCalledTimes(1)
+ expect(sidebar).not.toHaveBeenCalled()
+ expect(posthog.capture).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it.each([false, true])(
+ 'preserves focus ownership through attachment after another panel interaction=%s',
+ (outside) => {
+ const onEscape = jest.fn()
+ const { unmount } = render(
+ <div>
+ <RunEscapeBoundary scope="chat" focusKey="handoff" onEscape={onEscape}>
+ <p>Message</p>
+ </RunEscapeBoundary>
+ <p>Another panel</p>
+ </div>
+ )
+ fireEvent.pointerDown(screen.getByText(outside ? 'Another panel' : 'Message'))
+ unmount()
+ render(
+ <RunEscapeBoundary scope="chat" focusKey="handoff" onEscape={onEscape}>
+ <p>Attached message</p>
+ </RunEscapeBoundary>
+ )
+ fireEvent.keyDown(document.body, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(outside ? 0 : 1)
+ }
+ )
+
+ it.each(['chat', 'composer'] as const)(
+ 'scopes plan Escape and lets feedback editing finish first in %s',
+ (scope) => {
+ const onEscape = jest.fn()
+ const legacyCancel = jest.fn()
+ const options = mapPermissionOptions(
+ [
+ { optionId: 'auto', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'reject', name: 'Do it differently', kind: 'reject_with_feedback' },
+ ],
+ true
+ )
+ render(
+ <RunEscapeBoundary scope={scope} onEscape={onEscape}>
+ <div data-attr="run-approval">
+ <PlanApprovalSelector
+ approveOptions={[options[0]]}
+ rejectOption={options[1]}
+ responding={false}
+ onApprove={jest.fn()}
+ onReject={jest.fn()}
+ onCancel={legacyCancel}
+ />
+ </div>
+ </RunEscapeBoundary>
+ )
+ fireEvent.keyDown(document.body, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(scope === 'chat' ? 1 : 0)
+ fireEvent.keyDown(document.body, { key: '2' })
+ const input = screen.getByPlaceholderText(/tell the agent what to do differently/i)
+ fireEvent.keyDown(input, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(scope === 'chat' ? 1 : 0)
+ expect(legacyCancel).not.toHaveBeenCalled()
+ expect(screen.getByTestId('run-approval')).toContainElement(document.activeElement as HTMLElement)
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' })
+ expect(onEscape).toHaveBeenCalledTimes(scope === 'chat' ? 2 : 1)
+ expect(legacyCancel).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ 'editor',
+ 'hotkey-block',
+ 'disabled',
+ 'repeat',
+ 'isComposing',
+ 'metaKey',
+ 'ctrlKey',
+ 'altKey',
+ 'shiftKey',
+ 'unmounted',
+ ])('leaves Escape alone for %s', (reason) => {
+ const onEscape = jest.fn()
+ const { unmount } = render(
+ <RunEscapeBoundary scope="chat" onEscape={onEscape} disabled={reason === 'disabled'}>
+ <div contentEditable data-attr="editor" />
+ <button className="hotkey-block" data-attr="hotkey-block">
+ Blocked shortcut
+ </button>
+ </RunEscapeBoundary>
+ )
+ const target = ['editor', 'hotkey-block'].includes(reason) ? screen.getByTestId(reason) : document.body
+ if (reason === 'unmounted') {
+ unmount()
+ }
+ fireEvent.keyDown(target, { key: 'Escape', [reason]: true })
+ expect(onEscape).not.toHaveBeenCalled()
+ expect(posthog.capture).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx b/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx
new file mode 100644
index 000000000000..2a1387c4e898
--- /dev/null
+++ b/products/posthog_ai/frontend/components/RunEscapeBoundary.tsx
@@ -0,0 +1,113 @@
+import { type ReactNode, type RefObject, useLayoutEffect, useRef } from 'react'
+
+import { useEventListener } from 'lib/hooks/useEventListener'
+import posthog from 'lib/posthog-typed'
+
+// The optimistic and attached views remount; keep ancestor-focus ownership through that swap.
+const lastChatFocus = new WeakMap<Document, { key: string; ownsFocus: boolean }>()
+
+function isVisible(element: Element | null): boolean {
+ return (
+ !!element &&
+ !element.closest('[hidden], [inert], [aria-hidden="true"]') &&
+ element.getClientRects().length > 0 &&
+ getComputedStyle(element).visibility !== 'hidden'
+ )
+}
+
+export interface RunEscapeBoundaryProps {
+ scope: 'chat' | 'composer'
+ focusKey?: string
+ textAreaRef?: RefObject<HTMLTextAreaElement>
+ onEscape: () => void
+ disabled?: boolean
+ className?: string
+ children: ReactNode
+}
+
+export function RunEscapeBoundary({
+ scope,
+ focusKey,
+ textAreaRef,
+ onEscape,
+ disabled = false,
+ className,
+ children,
+}: RunEscapeBoundaryProps): JSX.Element {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const ownsAncestorFocus = useRef(false)
+
+ useLayoutEffect(() => {
+ // The submitted composer must unmount before we inspect where its focus landed.
+ const previousFocus = lastChatFocus.get(document)
+ ownsAncestorFocus.current =
+ scope === 'chat' &&
+ document.activeElement === document.body &&
+ (!focusKey || previousFocus?.key !== focusKey || previousFocus.ownsFocus)
+ }, [focusKey, scope])
+
+ const recordFocus = (target: EventTarget | null): void => {
+ ownsAncestorFocus.current = target instanceof Node && !!containerRef.current?.contains(target)
+ if (focusKey && scope === 'chat') {
+ lastChatFocus.set(document, { key: focusKey, ownsFocus: ownsAncestorFocus.current })
+ }
+ }
+
+ useEventListener('pointerdown', (event) => {
+ recordFocus(event.target)
+ })
+ useEventListener('focusin', (event) => {
+ // Clicking noninteractive transcript text can focus a tabindex ancestor outside this boundary.
+ if (event.target instanceof Node && !event.target.contains(containerRef.current)) {
+ recordFocus(event.target)
+ }
+ })
+ useEventListener('keydown', (event) => {
+ const container = containerRef.current
+ const target = event.target
+ if (
+ event.key !== 'Escape' ||
+ disabled ||
+ !container ||
+ !(target instanceof HTMLElement) ||
+ target.closest('.hotkey-block') ||
+ event.defaultPrevented ||
+ event.repeat ||
+ event.isComposing ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.altKey ||
+ event.shiftKey ||
+ !isVisible(container) ||
+ isVisible(container.querySelector('[data-attr="run-queue-editor"]')) ||
+ [...document.querySelectorAll('[role="menu"], [role="dialog"], [role="listbox"]')].some(isVisible)
+ ) {
+ return
+ }
+ const composerFocused =
+ !!textAreaRef?.current?.closest('form')?.contains(target) && !target.closest('[hidden], [inert]')
+ const approvalFocused = container.contains(target) && !!target.closest('[data-attr="run-approval"]')
+ if (
+ (target !== textAreaRef?.current &&
+ target.closest(
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), .monaco-editor'
+ )) ||
+ (scope === 'composer'
+ ? !composerFocused && !approvalFocused
+ : !container.contains(target) && !(target.contains(container) && ownsAncestorFocus.current))
+ ) {
+ return
+ }
+ event.preventDefault()
+ if (posthog.__loaded) {
+ posthog.capture('keybind triggered', { keybind: 'escape', mechanism: 'hotkey' })
+ }
+ onEscape()
+ })
+
+ return (
+ <div ref={containerRef} data-run-escape-scope={scope} className={className}>
+ {children}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
index a10841fd59ab..1aed474d4e74 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
@@ -167,45 +167,48 @@ describe('RunSurface', () => {
expect(screen.getByTestId('composer')).not.toBeVisible()
})
- it('hides the approval during delivery and preserves a draft across restoration before its debounce commits', () => {
- jest.useFakeTimers()
- try {
- const request = { requestId: 'r1', sourceRunId: 'run-1' } as PermissionRequestRecord
- const surface = (): JSX.Element => (
- <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">
- <RunSurface.Composer>
- <DraftComposer />
- </RunSurface.Composer>
- </RunSurface.Root>
- )
- setValues({ pendingPermissionRequest: request })
- const { rerender } = render(surface())
- const card = screen.getByTestId('permission')
- const draft = screen.getByTestId('draft')
- expect(card).toBeVisible()
- setValues({ pendingPermissionRequest: request, respondingToPermission: true })
- rerender(surface())
- expect(card).not.toBeVisible()
- expect(draft).toBeVisible()
- fireEvent.change(draft, { target: { value: 'a newer draft' } })
- setValues({ pendingPermissionRequest: request, respondingToPermission: false })
- rerender(surface())
- expect(screen.getByTestId('permission')).toBe(card)
- expect(card).toBeVisible()
- expect(draft).toHaveValue('a newer draft')
- act(() => {
- jest.advanceTimersByTime(150)
- })
- setValues({ pendingPermissionRequest: null })
- rerender(surface())
- expect(screen.getByTestId('draft')).toBe(draft)
- expect(draft).toBeVisible()
- expect(draft).toHaveValue('a newer draft')
- } finally {
- cleanup()
- jest.useRealTimers()
+ it.each(['delivery', 'cancellation'])(
+ 'hides the approval during %s and preserves a draft across restoration before its debounce commits',
+ (transition) => {
+ jest.useFakeTimers()
+ try {
+ const request = { requestId: 'r1', sourceRunId: 'run-1' } as PermissionRequestRecord
+ const surface = (isStopping = false): JSX.Element => (
+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">
+ <RunSurface.Composer isStopping={isStopping}>
+ <DraftComposer />
+ </RunSurface.Composer>
+ </RunSurface.Root>
+ )
+ setValues({ pendingPermissionRequest: request })
+ const { rerender } = render(surface())
+ const card = screen.getByTestId('permission')
+ const draft = screen.getByTestId('draft')
+ expect(card).toBeVisible()
+ setValues({ pendingPermissionRequest: request, respondingToPermission: transition === 'delivery' })
+ rerender(surface(transition === 'cancellation'))
+ expect(card).not.toBeVisible()
+ expect(draft).toBeVisible()
+ fireEvent.change(draft, { target: { value: 'a newer draft' } })
+ setValues({ pendingPermissionRequest: request, respondingToPermission: false })
+ rerender(surface())
+ expect(screen.getByTestId('permission')).toBe(card)
+ expect(card).toBeVisible()
+ expect(draft).toHaveValue('a newer draft')
+ act(() => {
+ jest.advanceTimersByTime(150)
+ })
+ setValues({ pendingPermissionRequest: null })
+ rerender(surface())
+ expect(screen.getByTestId('draft')).toBe(draft)
+ expect(draft).toBeVisible()
+ expect(draft).toHaveValue('a newer draft')
+ } finally {
+ cleanup()
+ jest.useRealTimers()
+ }
}
- })
+ )
it('renders nothing in read-only mode', () => {
setValues({ currentRunStatus: 'in_progress' })
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 2b671d752a5e..33f136b358e2 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -244,14 +244,20 @@ function RunSurfaceThread({
* any settled run status (active runs take a follow-up, terminal runs start a fresh run from the typed
* message), is hidden during bootstrap, and is replaced by the prompt while a request is pending.
*/
-function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element | null {
+function RunSurfaceComposer({
+ children,
+ isStopping = false,
+}: {
+ children?: ReactNode
+ isStopping?: boolean
+}): JSX.Element | null {
const { interaction, streamKey } = useRunSurfaceContext()
const { pendingPermissionRequest, respondingToPermission, currentRunStatus } = useValues(runStreamLogic)
if (interaction !== 'live') {
return null
}
const request = !isTerminalRunStatus(currentRunStatus) ? pendingPermissionRequest : null
- const showApproval = !!request && !respondingToPermission
+ const showApproval = !!request && !respondingToPermission && !isStopping
// Both inputs keep their local state through delivery and restoration, including uncommitted draft keystrokes.
return (
@@ -260,9 +266,9 @@ function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element
<div hidden={!showApproval} className="border-t px-4 py-3" data-attr="run-approval">
<div key={`${request.sourceRunId}:${request.requestId}`} className="mx-auto w-full max-w-180">
{request.questions?.length ? (
- <QuestionInput streamKey={streamKey} request={request} />
+ <QuestionInput streamKey={streamKey} request={request} disabled={isStopping} />
) : (
- <PermissionInput streamKey={streamKey} request={request} />
+ <PermissionInput streamKey={streamKey} request={request} disabled={isStopping} />
)}
</div>
</div>
diff --git a/products/posthog_ai/frontend/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
index 5e3da9742d7f..156e6bc27c4d 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.test.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
@@ -4,8 +4,8 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { createRef, useState } from 'react'
import { QueuedMessageList } from '../QueuedMessageList'
+import { RunEscapeBoundary } from '../RunEscapeBoundary'
import { Composer } from './Composer'
-import { ComposerSteerShortcut } from './ComposerSteerShortcut'
describe('Composer', () => {
const onChange = jest.fn()
@@ -14,10 +14,12 @@ describe('Composer', () => {
beforeEach(() => {
jest.clearAllMocks()
+ jest.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue({ length: 1 } as DOMRectList)
})
afterEach(() => {
cleanup()
+ jest.restoreAllMocks()
})
const renderComposer = (props: Partial<Parameters<typeof Composer.Root>[0]> = {}): ReturnType<typeof render> =>
@@ -48,22 +50,23 @@ describe('Composer', () => {
steer()
}
return (
- <Composer.Root
- value="unsent draft"
- onChange={onChange}
- onSubmit={onSubmit}
- textAreaRef={textAreaRef}
- >
- <ComposerSteerShortcut textAreaRef={textAreaRef} onSteer={onSteer} disabled={pending} />
- <QueuedMessageList
- messages={[{ id: 'queued', content: 'saved message' }]}
- onUpdate={jest.fn()}
- onRemove={jest.fn()}
- onSteer={onSteer}
- steerPending={pending}
- />
- <Composer.Textarea data-attr="composer-input" />
- </Composer.Root>
+ <RunEscapeBoundary scope="composer" textAreaRef={textAreaRef} onEscape={onSteer} disabled={pending}>
+ <Composer.Root
+ value="unsent draft"
+ onChange={onChange}
+ onSubmit={onSubmit}
+ textAreaRef={textAreaRef}
+ >
+ <QueuedMessageList
+ messages={[{ id: 'queued', content: 'saved message' }]}
+ onUpdate={jest.fn()}
+ onRemove={jest.fn()}
+ onSteer={onSteer}
+ steerPending={pending}
+ />
+ <Composer.Textarea data-attr="composer-input" />
+ </Composer.Root>
+ </RunEscapeBoundary>
)
}
render(<QueuedComposer />)
@@ -108,15 +111,22 @@ describe('Composer', () => {
const steer = jest.fn()
const { container } = render(
<div hidden={reason === 'hidden'}>
- <Composer.Root value="unsent draft" onChange={onChange} onSubmit={onSubmit} textAreaRef={textAreaRef}>
- <ComposerSteerShortcut
+ <RunEscapeBoundary
+ scope="composer"
+ textAreaRef={textAreaRef}
+ onEscape={steer}
+ disabled={reason === 'empty queue'}
+ >
+ <Composer.Root
+ value="unsent draft"
+ onChange={onChange}
+ onSubmit={onSubmit}
textAreaRef={textAreaRef}
- onSteer={steer}
- disabled={reason === 'empty queue'}
- />
- <Composer.Textarea data-attr="composer-input" />
- {reason === 'queue editor' && <textarea data-attr="run-queue-editor" />}
- </Composer.Root>
+ >
+ <Composer.Textarea data-attr="composer-input" />
+ {reason === 'queue editor' && <textarea data-attr="run-queue-editor" />}
+ </Composer.Root>
+ </RunEscapeBoundary>
<input data-attr="other-input" />
{['menu', 'dialog', 'listbox'].includes(reason) && <div role={reason} />}
</div>
@@ -214,6 +224,21 @@ describe('Composer', () => {
expect(onStop).not.toHaveBeenCalled()
})
+ it.each(['', 'follow up'])('keeps a pending stop visible and blocks sending with draft %p', (value) => {
+ const { container } = renderComposer({ value, stopLoading: true, onStop })
+ const button = getSend(container)
+ const input = screen.getByTestId('composer-input')
+ expect(button).toHaveAttribute('aria-label', 'Stopping…')
+ expect(button).toHaveAttribute('type', 'button')
+ expect(button).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(button)
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(onStop).not.toHaveBeenCalled()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(input).toHaveValue(value)
+ expect(input).not.toBeDisabled()
+ })
+
it('throws when a part is rendered outside Composer.Root', () => {
// Silence the expected React error boundary log.
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsx
index 834fcb3fc1ef..fe7bb88fb410 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx
@@ -27,10 +27,10 @@ interface ComposerContextValue {
value: string
onChange: (value: string) => void
loading: boolean
+ stopLoading: boolean
disabled: boolean
/** Empty input / loading / caller's `disabledReason`, collapsed to a single reason (undefined when sendable). */
sendDisabledReason: string | undefined
- /** True when the send button should swap to a Stop button (active turn + empty input + an `onStop` handler). */
showStop: boolean
/** Cancels the active turn; drives the Stop button that replaces send when `showStop`. */
onStop: (() => void) | undefined
@@ -58,6 +58,7 @@ export interface ComposerRootProps {
onSubmit: () => void
/** Marks the send button in-flight and blocks submission. */
loading?: boolean
+ stopLoading?: boolean
/** Disables the textarea. */
disabled?: boolean
/** Extra reason to block sending, beyond the internally-handled empty input. */
@@ -86,6 +87,7 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Com
onChange,
onSubmit,
loading = false,
+ stopLoading = false,
disabled = false,
disabledReason,
isTurnActive = false,
@@ -105,11 +107,17 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Com
const generatedId = useId()
const id = idProp ?? generatedId
- const sendDisabledReason = !value.trim() ? 'Type a message first' : loading ? 'Sending…' : disabledReason
+ const sendDisabledReason = stopLoading
+ ? 'Stopping…'
+ : !value.trim()
+ ? 'Type a message first'
+ : loading
+ ? 'Sending…'
+ : disabledReason
// While a turn is active with no drafted text, the send button becomes a Stop button (cancel the run)
// rather than a disabled "Type a message first" — a follow-up with text still sends/queues as usual.
- const showStop = isTurnActive && !value.trim() && !loading && !!onStop
+ const showStop = !!onStop && (stopLoading || (isTurnActive && !value.trim() && !loading))
// Focuses the textarea when blocked, otherwise submits — shared by the native form submit and the
// textarea keyboard shortcuts.
@@ -126,6 +134,7 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Com
value,
onChange,
loading,
+ stopLoading,
disabled,
sendDisabledReason,
showStop,
@@ -139,6 +148,7 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Com
value,
onChange,
loading,
+ stopLoading,
disabled,
sendDisabledReason,
showStop,
@@ -351,7 +361,7 @@ const ComposerSubmit = forwardRef<HTMLDivElement, ComposerSubmitProps>(function
{ icon, tooltip, className, ...rest },
ref
): JSX.Element {
- const { sendDisabledReason, loading, showStop, onStop, isThreadVisible } = useComposerContext()
+ const { sendDisabledReason, loading, stopLoading, showStop, onStop, isThreadVisible } = useComposerContext()
return (
<div
data-slot="composer-submit"
@@ -371,7 +381,8 @@ const ComposerSubmit = forwardRef<HTMLDivElement, ComposerSubmitProps>(function
htmlType="button"
icon={<IconStopFilled />}
onClick={() => onStop?.()}
- tooltip="Stop"
+ loading={stopLoading}
+ tooltip={stopLoading ? 'Stopping…' : 'Stop'}
{...rest}
/>
) : (
diff --git a/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx b/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx
deleted file mode 100644
index c637f3afe907..000000000000
--- a/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { RefObject } from 'react'
-
-import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
-
-export function ComposerSteerShortcut({
- textAreaRef,
- onSteer,
- disabled,
-}: {
- textAreaRef: RefObject<HTMLTextAreaElement>
- onSteer: () => void
- disabled: boolean
-}): null {
- useKeyboardHotkeys({
- escape: {
- disabled,
- willHandleEvent: true,
- action: (event) => {
- if (
- event.defaultPrevented ||
- event.repeat ||
- event.isComposing ||
- event.metaKey ||
- event.ctrlKey ||
- event.altKey ||
- event.shiftKey ||
- event.target !== textAreaRef.current ||
- textAreaRef.current?.closest('[hidden], [inert]') ||
- textAreaRef.current?.closest('form')?.querySelector('[data-attr="run-queue-editor"]') ||
- [...document.querySelectorAll('[role="menu"], [role="dialog"], [role="listbox"]')].some(
- (overlay) =>
- !overlay.closest('[hidden], [inert], [aria-hidden="true"]') &&
- overlay.getClientRects().length > 0 &&
- getComputedStyle(overlay).visibility !== 'hidden'
- )
- ) {
- return
- }
- event.preventDefault()
- onSteer()
- },
- },
- })
- return null
-}
diff --git a/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts b/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts
new file mode 100644
index 000000000000..d44473d25756
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts
@@ -0,0 +1,166 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { initKeaTests } from '~/test/init'
+
+import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'
+
+import type { StoredLogEntry } from '../types/wireTypes'
+import { runCancellationLogic } from './runCancellationLogic'
+import { runStreamLogic } from './runStreamLogic'
+
+jest.mock('products/tasks/frontend/generated/api', () => ({ tasksRunsCommandCreate: jest.fn() }))
+
+function ready(runId = 'run-1'): StoredLogEntry {
+ return {
+ type: 'notification',
+ source_run_id: runId,
+ notification: {
+ method: '_posthog/progress',
+ params: { group: `setup:${runId}`, step: 'agent', status: 'completed' },
+ },
+ }
+}
+
+function prompt(runId = 'run-1', sessionUpdate = 'user_message_chunk'): StoredLogEntry {
+ return {
+ type: 'notification',
+ source_run_id: runId,
+ notification: {
+ method: 'session/update',
+ params: {
+ update: { sessionUpdate, content: { type: 'text', text: 'A synthetic task' } },
+ },
+ },
+ }
+}
+
+describe('runCancellationLogic', () => {
+ let logic: ReturnType<typeof runCancellationLogic.build>
+ let stream: ReturnType<typeof runStreamLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.mocked(tasksRunsCommandCreate).mockReset().mockResolvedValue({ jsonrpc: '2.0', result: {} })
+ jest.spyOn(api.tasks.runs, 'openStream').mockImplementation(() => new Promise(() => {}))
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+ logic = runCancellationLogic({ streamKey: 'draft-1' })
+ logic.mount()
+ stream = runStreamLogic({ streamKey: 'draft-1' })
+ stream.actions.startOptimisticRun('A synthetic task')
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ const attach = (runId = 'run-1'): void => {
+ stream.actions.bootstrapRun({ taskId: 'task-1', runId, justCreatedRun: true })
+ }
+
+ it.each([
+ ['before attachment', 'user_message_chunk'],
+ ['while starting', 'user_message_chunk'],
+ ['already ready', 'user_message_chunk'],
+ ['while starting', 'user_message'],
+ ['while starting', 'agent_message'],
+ ])('stops the same run once when requested %s with %s', async (phase, sessionUpdate) => {
+ if (phase !== 'before attachment') {
+ attach()
+ }
+ if (phase === 'already ready') {
+ stream.actions.ingestAcpFrame(ready())
+ stream.actions.ingestAcpFrame(prompt('run-1', sessionUpdate))
+ }
+ logic.actions.requestCancellation()
+ logic.actions.requestCancellation()
+ if (phase !== 'already ready') {
+ expect(logic.values.cancellationState).toBe('waiting')
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ }
+ if (phase === 'before attachment') {
+ attach()
+ }
+ await expectLogic(logic, () => {
+ stream.actions.ingestAcpFrame(ready())
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(phase === 'already ready' ? 1 : 0)
+ stream.actions.ingestAcpFrame(prompt('run-1', sessionUpdate))
+ }).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {
+ jsonrpc: '2.0',
+ method: 'cancel',
+ })
+ expect(logic.values.cancellationState).toBe('sending')
+ stream.actions.ingestAcpFrame({
+ type: 'notification',
+ source_run_id: 'run-1',
+ notification: { method: '_posthog/turn_complete' },
+ })
+ expect(logic.values.cancellationState).toBeNull()
+ })
+
+ it('ignores readiness from an earlier resumed run', async () => {
+ attach()
+ logic.actions.requestCancellation()
+ await expectLogic(logic, () =>
+ stream.actions.ingestAcpFrame(ready('previous-run'), 'replay')
+ ).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.cancellationState).toBe('waiting')
+ await expectLogic(logic, () => {
+ stream.actions.ingestAcpFrame(ready())
+ stream.actions.ingestAcpFrame(prompt('previous-run'), 'replay')
+ }).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ await expectLogic(logic, () => stream.actions.ingestAcpFrame(prompt())).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(['leave', 'switch', 'terminal', 'reset', 'unmount'])('clears a waiting stop on %s', async (transition) => {
+ attach()
+ logic.actions.requestCancellation()
+ if (transition === 'leave') {
+ logic.actions.clearCancellation()
+ } else if (transition === 'switch') {
+ attach('run-2')
+ } else if (transition === 'terminal') {
+ stream.actions.handleTerminalStatus({ status: 'failed' })
+ } else if (transition === 'reset') {
+ stream.actions.reset()
+ } else {
+ logic.unmount()
+ logic.mount()
+ attach()
+ }
+ await expectLogic(logic, () => {
+ stream.actions.ingestAcpFrame(ready(transition === 'switch' ? 'run-2' : 'run-1'))
+ stream.actions.ingestAcpFrame(prompt(transition === 'switch' ? 'run-2' : 'run-1'))
+ }).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.cancellationState).toBeNull()
+ })
+
+ it.each(['network', 'agent'])('allows retry after a %s cancellation error', async (failure) => {
+ attach()
+ stream.actions.ingestAcpFrame(ready())
+ stream.actions.ingestAcpFrame(prompt())
+ if (failure === 'network') {
+ jest.mocked(tasksRunsCommandCreate).mockRejectedValueOnce(new Error('Network unavailable'))
+ } else {
+ jest.mocked(tasksRunsCommandCreate).mockResolvedValueOnce({
+ jsonrpc: '2.0',
+ error: { code: -32000, message: 'Agent unavailable' },
+ })
+ }
+ await expectLogic(logic, () => logic.actions.requestCancellation()).toFinishAllListeners()
+ expect(logic.values.cancellationState).toBeNull()
+ expect(lemonToast.error).toHaveBeenCalled()
+ await expectLogic(logic, () => logic.actions.requestCancellation()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(2)
+ expect(logic.values.cancellationState).toBe('sending')
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/runCancellationLogic.ts b/products/posthog_ai/frontend/logics/runCancellationLogic.ts
new file mode 100644
index 000000000000..2635985fafab
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runCancellationLogic.ts
@@ -0,0 +1,195 @@
+import { LogicWrapper, MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import posthog from 'posthog-js'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'
+
+import type { StoredLogEntry } from '../types/wireTypes'
+import { type RunLog, type RunStatus, isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
+
+export interface RunCancellationLogicProps {
+ streamKey: string
+}
+
+export type CancellationState = 'waiting' | 'sending' | null
+
+function confirmsAgentReady(entry: StoredLogEntry, runId: string): boolean {
+ const { method, params } = entry.notification
+ if (entry.source_run_id && entry.source_run_id !== runId) {
+ return false
+ }
+ return (
+ (method === '_posthog/progress' &&
+ params?.group === `setup:${runId}` &&
+ params.step === 'agent' &&
+ params.status === 'completed') ||
+ (method === '_posthog/run_started' && params?.runId === runId)
+ )
+}
+
+function confirmsTurnStarted(entry: StoredLogEntry, runId: string): boolean {
+ if (entry.source_run_id !== runId) {
+ return false
+ }
+ const { method, params } = entry.notification
+ const update = params?.update as { sessionUpdate?: string } | undefined
+ return (
+ method === '_posthog/permission_request' ||
+ (method === 'session/update' &&
+ [
+ 'user_message_chunk',
+ 'user_message',
+ 'agent_message_chunk',
+ 'agent_message',
+ 'agent_thought_chunk',
+ 'tool_call',
+ 'tool_call_update',
+ ].includes(update?.sessionUpdate ?? ''))
+ )
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runCancellationLogicValues {
+ currentProjectId: number | null // projectLogic
+ bootstrappedRunId: string | null // runStreamLogic
+ bootstrappedTaskId: string | null // runStreamLogic
+ currentRunStatus: RunStatus | null // runStreamLogic
+ log: RunLog // runStreamLogic
+ cancellationState: CancellationState
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runCancellationLogicActions {
+ cancelPermissionDelivery: () => {
+ value: true
+ } // runStreamLogic
+ cancelWhenReady: () => {
+ value: true
+ }
+ clearCancellation: () => {
+ value: true
+ }
+ requestCancellation: () => {
+ value: true
+ }
+ setCancellationState: (state: CancellationState) => {
+ state: CancellationState
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runCancellationLogicMeta {
+ key: string
+}
+
+export type runCancellationLogicType = MakeLogicType<
+ runCancellationLogicValues,
+ runCancellationLogicActions,
+ RunCancellationLogicProps,
+ runCancellationLogicMeta
+>
+
+export const runCancellationLogic: LogicWrapper<runCancellationLogicType> = kea<runCancellationLogicType>([
+ props({} as RunCancellationLogicProps),
+ key((props) => props.streamKey),
+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runCancellationLogic', key]),
+ connect((props: RunCancellationLogicProps) => ({
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ runStreamLogic(props),
+ ['bootstrappedRunId', 'bootstrappedTaskId', 'currentRunStatus', 'log'],
+ ],
+ actions: [runStreamLogic(props), ['cancelPermissionDelivery']],
+ })),
+ actions({
+ requestCancellation: true,
+ cancelWhenReady: true,
+ setCancellationState: (state: CancellationState) => ({ state }),
+ clearCancellation: true,
+ }),
+ reducers({
+ cancellationState: [
+ null as CancellationState,
+ {
+ setCancellationState: (_, { state }) => state,
+ clearCancellation: () => null,
+ },
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => ({
+ requestCancellation: () => {
+ if (values.cancellationState || isTerminalRunStatus(values.currentRunStatus)) {
+ return
+ }
+ actions.cancelPermissionDelivery()
+ actions.setCancellationState('waiting')
+ actions.cancelWhenReady()
+ },
+ cancelWhenReady: async () => {
+ const { bootstrappedRunId: runId, bootstrappedTaskId: taskId, currentProjectId } = values
+ if (
+ values.cancellationState !== 'waiting' ||
+ !runId ||
+ !taskId ||
+ currentProjectId === null ||
+ isTerminalRunStatus(values.currentRunStatus) ||
+ !values.log.entries.some(({ entry }) => confirmsAgentReady(entry, runId)) ||
+ // Readiness precedes first-message delivery; canceling an idle agent would miss that message.
+ !values.log.entries.some(({ entry }) => confirmsTurnStarted(entry, runId))
+ ) {
+ return
+ }
+ actions.setCancellationState('sending')
+ const disposables = cache.disposables
+ const request = (cache.cancelRequest = {})
+ try {
+ const response = await tasksRunsCommandCreate(String(currentProjectId), taskId, runId, {
+ jsonrpc: '2.0',
+ method: 'cancel',
+ })
+ if (response.error) {
+ throw new Error('Agent rejected cancellation')
+ }
+ } catch (error) {
+ if (!disposables.isDisposed && cache.cancelRequest === request && values.bootstrappedRunId === runId) {
+ actions.clearCancellation()
+ lemonToast.error("Couldn't stop this run. Please try again.")
+ posthog.captureException(error)
+ }
+ }
+ },
+ clearCancellation: () => {
+ cache.cancelRequest = undefined
+ },
+ [runStreamLogic(props).actionTypes.appendEntries]: () => {
+ if (values.cancellationState === 'waiting') {
+ actions.cancelWhenReady()
+ }
+ },
+ [runStreamLogic(props).actionTypes.ingestAcpFrame]: ({ entry, source }) => {
+ if (
+ source === 'live' &&
+ entry.source_run_id === values.bootstrappedRunId &&
+ entry.notification.method === '_posthog/turn_complete'
+ ) {
+ actions.clearCancellation()
+ }
+ },
+ [runStreamLogic(props).actionTypes.handleTerminalStatus]: ({ status }) => {
+ if (isTerminalRunStatus(status)) {
+ actions.clearCancellation()
+ }
+ },
+ [runStreamLogic(props).actionTypes.reset]: () => actions.clearCancellation(),
+ [runStreamLogic(props).actionTypes.closeSse]: () => actions.clearCancellation(),
+ [runStreamLogic(props).actionTypes.bootstrapRun]: ({ runId }) => {
+ if (cache.cancellationRunId && cache.cancellationRunId !== runId) {
+ actions.clearCancellation()
+ }
+ cache.cancellationRunId = runId
+ },
+ })),
+])
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index f6de4e43243b..71751833ce34 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -18,6 +18,7 @@ import {
import type { PermissionRequestRecord } from '../types/streamTypes'
import { contextItemLine } from '../utils/posthogContextBlock'
import { attachedContextLogic } from './attachedContextLogic'
+import { runCancellationLogic } from './runCancellationLogic'
import { runInteractionLogic } from './runInteractionLogic'
import { runStreamLogic } from './runStreamLogic'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
@@ -50,6 +51,10 @@ jest.mock('./runStreamLogic', () => {
cancelPermissionDelivery: true,
clearPermissionRequest: true,
reset: true,
+ appendEntries: true,
+ ingestAcpFrame: true,
+ closeSse: true,
+ bootstrapRun: true,
}),
reducers({
currentRunStatus: [
@@ -67,6 +72,7 @@ jest.mock('./runStreamLogic', () => {
],
bootstrappedRunId: [null, {}],
bootstrappedTaskId: [null, {}],
+ log: [{ entries: [], toolUpdateIndex: new Map() }, {}],
pendingPermissionRequest: [
null,
{
@@ -210,6 +216,69 @@ describe('runInteractionLogic', () => {
toolEvents?.unmount()
})
+ it('adopts the startup draft once and clears it after sending', async () => {
+ const onDraftAdopted = jest.fn()
+ const attached = runInteractionLogic({
+ taskId: TASK_ID,
+ runId: 'attached-run',
+ initialDraft: 'startup draft',
+ onDraftAdopted,
+ })
+ const unmount = attached.mount()
+ try {
+ expect(attached.values.composerForm.draft).toBe('startup draft')
+ expect(onDraftAdopted).toHaveBeenCalledTimes(1)
+ await expectLogic(attached, () => attached.actions.submitComposerForm()).toFinishAllListeners()
+ expect(attached.values.composerForm.draft).toBe('')
+ } finally {
+ unmount()
+ }
+ })
+
+ it.each(['queue', 'run', 'idle', 'approval'])(
+ 'routes Escape for %s and preserves the unsent draft',
+ async (state) => {
+ setThinking(state !== 'idle')
+ logic.actions.setComposerFormValues({ draft: 'unsent draft' })
+ if (state === 'queue') {
+ logic.actions.enqueueMessage('saved message')
+ }
+ if (state === 'approval') {
+ stream.actions.ingestPermissionRequest({
+ requestId: 'approval',
+ sourceRunId: RUN_ID,
+ } as PermissionRequestRecord)
+ }
+ await expectLogic(logic, () => logic.actions.handleEscape()).toFinishAllListeners()
+ expect(logic.values.composerForm.draft).toBe('unsent draft')
+ expect(logic.values.cancellationState).toBe(['run', 'approval'].includes(state) ? 'waiting' : null)
+ if (state === 'queue') {
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
+ jsonrpc: '2.0',
+ method: 'user_message',
+ params: { content: 'saved message', steer: true },
+ })
+ } else {
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ }
+ }
+ )
+
+ it('blocks sends and steering while stopping without clearing either draft or queue', async () => {
+ logic.actions.setComposerFormValues({ draft: 'unsent draft' })
+ logic.actions.enqueueMessage('saved message')
+ runCancellationLogic({ streamKey: RUN_ID }).actions.requestCancellation()
+ await expectLogic(logic, () => {
+ logic.actions.handleEscape()
+ logic.actions.submitComposerForm()
+ logic.actions.steerQueue()
+ logic.actions.flushQueue()
+ }).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.composerForm.draft).toBe('unsent draft')
+ expect(logic.values.queuedMessages).toEqual([{ id: 'queued', content: 'saved message' }])
+ })
+
it('sends immediately and echoes the message when the agent is idle', async () => {
setThinking(false)
logic.actions.setComposerFormValues({ draft: 'ship it' })
@@ -397,33 +466,42 @@ describe('runInteractionLogic', () => {
expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('follow up'))
})
- it('defers steering through approval confirmation and sends the current saved queue once', async () => {
- const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
- stream.actions.ingestPermissionRequest(record)
- stream.actions.deliverPermission(record, 'allow_once')
- setThinking(true)
- logic.actions.enqueueMessage('first')
- logic.actions.setComposerFormValues({ draft: 'still drafting' })
- logic.actions.steerQueue()
- logic.actions.steerQueue()
- logic.actions.enqueueMessage('second')
- expect(logic.values.steerPending).toBe(true)
- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ it.each(['before approval', 'during confirmation'])(
+ 'defers Escape steering %s and sends the current saved queue once',
+ async (phase) => {
+ const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
+ stream.actions.ingestPermissionRequest(record)
+ if (phase === 'during confirmation') {
+ stream.actions.deliverPermission(record, 'allow_once')
+ }
+ setThinking(true)
+ logic.actions.enqueueMessage('first')
+ logic.actions.setComposerFormValues({ draft: 'still drafting' })
+ logic.actions.handleEscape()
+ logic.actions.handleEscape()
+ logic.actions.enqueueMessage('second')
+ expect(logic.values.steerPending).toBe(true)
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
- await expectLogic(logic, () =>
+ if (phase === 'before approval') {
+ stream.actions.deliverPermission(record, 'allow_once')
+ }
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ await expectLogic(logic, () =>
+ stream.actions.markPermissionRequestResolved(record.requestId)
+ ).toFinishAllListeners()
stream.actions.markPermissionRequestResolved(record.requestId)
- ).toFinishAllListeners()
- stream.actions.markPermissionRequestResolved(record.requestId)
- logic.actions.steerQueue()
- expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
- jsonrpc: '2.0',
- method: 'user_message',
- params: { content: 'first\n\nsecond', steer: true },
- })
- expect(logic.values.composerForm.draft).toBe('still drafting')
- expect(logic.values.queuedMessages).toEqual([])
- })
+ logic.actions.steerQueue()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
+ jsonrpc: '2.0',
+ method: 'user_message',
+ params: { content: 'first\n\nsecond', steer: true },
+ })
+ expect(logic.values.composerForm.draft).toBe('still drafting')
+ expect(logic.values.queuedMessages).toEqual([])
+ }
+ )
it.each(['failure', 'replacement approval', 'replacement run', 'terminal', 'cancel', 'reset', 'empty', 'unmount'])(
'cancels deferred steering on %s',
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 76a68e15a654..a497dd1e690f 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
@@ -36,6 +36,7 @@ import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContext
import { submitWithWarmRunRetry } from '../utils/warmRunSubmission'
import { attachedContextLogic } from './attachedContextLogic'
import { modelCatalogueLogic } from './modelCatalogueLogic'
+import { type CancellationState, runCancellationLogic } from './runCancellationLogic'
import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
import type { RunStatus } from './runStreamLogic'
import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'
@@ -52,6 +53,8 @@ export interface RunInteractionLogicProps {
* `RunSurface` binds, never diverging from it. API calls still use the real `runId`.
*/
streamKey?: string
+ initialDraft?: string
+ onDraftAdopted?: () => void
/** The run's stored model / reasoning effort / launch mode, injected by the consumer. They seed the picker's
* display and the config a terminal-run send launches the next run with (override ?? this ?? default). */
currentModel?: string | null
@@ -94,6 +97,7 @@ export interface runInteractionLogicValues {
sentContextKeysByTask: Record<string, string[]> // attachedContextLogic
catalogue: ModelChoiceApi[] // modelCatalogueLogic
currentProjectId: number | null // projectLogic
+ cancellationState: CancellationState // runCancellationLogic
bootstrappedRunId: string | null // runStreamLogic
bootstrappedTaskId: string | null // runStreamLogic
conversationClearSupported: boolean // runStreamLogic
@@ -165,6 +169,9 @@ export interface runInteractionLogicActions {
keys: string[]
taskId: string
} // attachedContextLogic
+ requestCancellation: () => {
+ value: true
+ } // runCancellationLogic
cancelPermissionDelivery: () => {
value: true
} // runStreamLogic
@@ -281,6 +288,9 @@ export interface runInteractionLogicActions {
flushQueue: (steer?: boolean) => {
steer: boolean
}
+ handleEscape: () => {
+ value: true
+ }
prependQueuedMessage: (content: string) => {
content: string
}
@@ -426,6 +436,7 @@ export interface runInteractionLogicMeta {
isBusy: (isThinking: boolean) => boolean
canSend: (
sending: boolean,
+ cancellationState: CancellationState,
isTerminal: boolean,
currentProjectId: number | null,
currentRunStatus: RunStatus | null,
@@ -493,6 +504,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['catalogue'],
taskRunDefaultsLogic,
['defaultModel', 'defaultEffort'],
+ runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),
+ ['cancellationState'],
],
actions: [
runStreamLogic({ streamKey: props.streamKey ?? props.runId }),
@@ -518,6 +531,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['claimApplyBackTargets', 'transferApplyBackTargets', 'releaseApplyBackTargets'],
taskWarmLogic({ taskId: props.taskId, resumeFromRunId: props.runId }),
['noteDraft', 'consumeWarm', 'releaseWarm'],
+ runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),
+ ['requestCancellation'],
],
})),
@@ -545,6 +560,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Internal: drain the staged "Up next" message when the agent is idle.
flushQueue: (steer: boolean = false) => ({ steer }),
steerQueue: true,
+ handleEscape: true,
setDeferredSteer: (requestId: string | null) => ({ requestId }),
queueDeliveryFailed: true,
// Pick the model / reasoning effort for the next message. Selection is held client-side only and
@@ -689,7 +705,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}),
submit: ({ draft }) => {
const content = draft.trim()
- if (!content) {
+ if (!content || values.cancellationState) {
return
}
if (!values.dataProcessingAccepted) {
@@ -794,6 +810,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
canSend: [
(s, p) => [
s.sending,
+ s.cancellationState,
s.isTerminal,
s.currentProjectId,
s.currentRunStatus,
@@ -804,6 +821,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
],
(
sending: boolean,
+ cancellationState: CancellationState,
isTerminal: boolean,
currentProjectId: number | null,
status: RunStatus | null,
@@ -813,6 +831,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
taskId: string
): boolean =>
!sending &&
+ !cancellationState &&
!isTerminal &&
currentProjectId != null &&
status !== null &&
@@ -888,6 +907,16 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}
return {
+ handleEscape: () => {
+ if (values.cancellationState || values.steerPending) {
+ return
+ }
+ if (values.queuedMessages.length > 0) {
+ actions.steerQueue()
+ } else if (values.isBusy || (!values.composerActive && !values.isTerminal)) {
+ actions.requestCancellation()
+ }
+ },
submitAfterConsent: () => {
actions.clearConsentBlock()
if (values.consentBlockedSource === 'steer') {
@@ -919,7 +948,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
},
steerQueue: () => {
- if (!values.queuedMessages.length || values.steerPending || !values.canSend || !values.composerActive) {
+ if (!values.queuedMessages.length || values.steerPending || !values.canSend) {
return
}
if (!values.dataProcessingAccepted) {
@@ -1213,4 +1242,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
},
}
}),
+ afterMount(({ actions, props }) => {
+ if (props.initialDraft) {
+ actions.setComposerFormValues({ draft: props.initialDraft })
+ props.onDraftAdopted?.()
+ }
+ }),
])
diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
index afbd0421bda9..0c45899adb51 100644
--- a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
+++ b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
@@ -7,6 +7,7 @@ export interface ActiveCreation {
streamKey: string
taskId?: string
runId?: string
+ draft?: string
}
// `panelId` is set only by an embedded instance (e.g. Max's side panel runner), which mounts this logic
@@ -41,6 +42,9 @@ export interface runnerPanelLogicActions {
setHistoryExpanded: (expanded: boolean) => {
expanded: boolean
}
+ setStartupDraft: (draft: string) => {
+ draft: string
+ }
toggleHistory: () => {
value: true
}
@@ -70,6 +74,7 @@ export const runnerPanelLogic = kea<runnerPanelLogicType>([
actions({
setActiveCreation: (creation: ActiveCreation) => ({ creation }),
+ setStartupDraft: (draft: string) => ({ draft }),
clearActiveCreation: true,
toggleHistory: true,
setHistoryExpanded: (expanded: boolean) => ({ expanded }),
@@ -83,7 +88,9 @@ export const runnerPanelLogic = kea<runnerPanelLogicType>([
activeCreation: [
null as ActiveCreation | null,
{
- setActiveCreation: (_, { creation }) => creation,
+ setActiveCreation: (state, { creation }) =>
+ state?.streamKey === creation.streamKey ? { ...state, ...creation } : creation,
+ setStartupDraft: (state, { draft }) => (state ? { ...state, draft } : state),
clearActiveCreation: () => null,
},
],
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
index 2ef6a0725f38..10de090bff30 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
@@ -1,14 +1,14 @@
import { BindLogic, useActions, useValues } from 'kea'
+import { useRef } from 'react'
import { IconArrowLeft } from '@posthog/icons'
import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
-import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
-
import { useAttachedContext } from '../../../hooks/useAttachedContext'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../../../utils/posthogContextBlock'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+import { StartupRunChat } from './StartupRunChat'
import { TaskComposer } from './TaskComposer'
import { TaskHistoryList, TaskHistoryPreview } from './TaskHistory'
import { TaskRunChat } from './TaskRunChat'
@@ -35,7 +35,8 @@ export function SidePanelRunnerImpl({ panelId }: SidePanelRunnerImplProps): JSX.
function SidePanelRunnerContent(): JSX.Element {
const { activeCreation, historyExpanded } = useValues(taskTrackerSceneLogic)
- const { toggleHistory, updateActiveCreationRun } = useActions(taskTrackerSceneLogic)
+ const { toggleHistory, updateActiveCreationRun, setStartupDraft } = useActions(taskTrackerSceneLogic)
+ const startupFocusedRef = useRef(false)
// This compact surface renders only in Max's side panel, so the run it shows is a foreground
// stream. Register its `streamKey` (cleared when the panel drops back to the composer/history, and
@@ -91,14 +92,14 @@ function SidePanelRunnerContent(): JSX.Element {
runId={activeCreation.runId}
streamKey={activeCreation.streamKey}
onRunStarted={updateActiveCreationRun}
+ escapeScope="composer"
+ initialDraft={activeCreation.draft}
+ onDraftAdopted={() => setStartupDraft('')}
+ autoFocus={startupFocusedRef.current}
/>
</div>
) : (
- <div className="@container/thread flex flex-col flex-1 min-h-0">
- <RunSurface.Root taskId="" runId={null} streamKey={activeCreation.streamKey} interaction="live">
- <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
- </RunSurface.Root>
- </div>
+ <StartupRunChat streamKey={activeCreation.streamKey} focusedRef={startupFocusedRef} />
)}
</div>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx
new file mode 100644
index 000000000000..5ce7c73404f6
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx
@@ -0,0 +1,46 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
+import { useEffect } from 'react'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { SidePanelRunner } from '../../../components/SidePanelRunner'
+import { runStreamLogic } from '../../../logics/runStreamLogic'
+import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+
+function StartupSidebar(): JSX.Element {
+ const { setActiveCreation } = useActions(taskTrackerSceneLogic({ panelId: 'startup-story' }))
+ const { startOptimisticRun } = useActions(runStreamLogic({ streamKey: 'startup-story' }))
+ useEffect(() => {
+ setActiveCreation({ streamKey: 'startup-story' })
+ startOptimisticRun('Explain how to measure weekly active users.')
+ }, [setActiveCreation, startOptimisticRun])
+ return (
+ <div className="flex h-160 w-100 flex-col border rounded bg-surface-primary">
+ <div className="px-4 py-3 font-semibold">PostHog AI</div>
+ <div className="flex-1 min-h-0">
+ <SidePanelRunner panelId="startup-story" />
+ </div>
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Products/PostHog AI/Startup chat',
+ render: () => <StartupSidebar />,
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/code/invites/check-access/': { has_access: true },
+ '/api/projects/:team/tasks/': { results: [], count: 0 },
+ '/api/projects/:team/tasks/repositories/': { repositories: [] },
+ '/api/projects/:team/tasks/@me/config/': { ai_run_preferences: {}, resolved_ai_run_defaults: {} },
+ '/api/environments/:team/integrations/': { results: [] },
+ },
+ }),
+ ],
+}
+export default meta
+
+export const Sidebar: StoryObj = {}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
new file mode 100644
index 000000000000..2add57410039
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+import { type MutableRefObject, useRef } from 'react'
+
+import { Composer } from 'products/posthog_ai/frontend/api/primitives'
+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
+
+import { RunEscapeBoundary } from '../../../components/RunEscapeBoundary'
+import { runCancellationLogic } from '../../../logics/runCancellationLogic'
+import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+
+export function StartupRunChat({
+ streamKey,
+ focusedRef,
+}: {
+ streamKey: string
+ focusedRef: MutableRefObject<boolean>
+}): JSX.Element {
+ const textAreaRef = useRef<HTMLTextAreaElement>(null)
+ const { activeCreation } = useValues(taskTrackerSceneLogic)
+ const { setStartupDraft } = useActions(taskTrackerSceneLogic)
+ const { requestCancellation } = useActions(runCancellationLogic({ streamKey }))
+ const { cancellationState } = useValues(runCancellationLogic({ streamKey }))
+
+ return (
+ <RunEscapeBoundary
+ scope="composer"
+ focusKey={streamKey}
+ textAreaRef={textAreaRef}
+ onEscape={requestCancellation}
+ className="@container/thread flex flex-col flex-1 min-h-0"
+ >
+ <RunSurface.Root taskId="" runId={null} streamKey={streamKey} interaction="live">
+ <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
+ </RunSurface.Root>
+ <div
+ className="px-4 pb-4"
+ onFocusCapture={() => {
+ focusedRef.current = true
+ }}
+ onBlurCapture={() => {
+ focusedRef.current = false
+ }}
+ >
+ <Composer.Root
+ textAreaRef={textAreaRef}
+ value={activeCreation?.draft ?? ''}
+ onChange={setStartupDraft}
+ onSubmit={() => {}}
+ disabledReason="Wait for the run to start"
+ stopLoading={!!cancellationState}
+ isTurnActive
+ onStop={requestCancellation}
+ >
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>Send a follow-up message…</Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" autoFocus />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </Composer.Root>
+ </div>
+ </RunEscapeBoundary>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
index cb04c77e3f1a..a14920744a50 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
@@ -1,5 +1,12 @@
+import { useActions, useValues } from 'kea'
+
+import { IconStopFilled } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
+import { RunEscapeBoundary } from '../../../components/RunEscapeBoundary'
+import { runCancellationLogic } from '../../../logics/runCancellationLogic'
import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'
import { TaskRunSceneShell } from './TaskRunSceneShell'
@@ -20,6 +27,8 @@ export interface TaskCreateThreadProps {
* detail page, which adopts the same seeded stream so only the continuous thread underneath persists.
*/
export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps): JSX.Element {
+ const { requestCancellation } = useActions(runCancellationLogic({ streamKey }))
+ const { cancellationState } = useValues(runCancellationLogic({ streamKey }))
return (
<TaskRunSceneShell
task={null}
@@ -32,11 +41,27 @@ export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps)
onRetry={() => {}}
isMobile={isMobile}
>
- <div className="@container/thread flex flex-col h-full -mx-4">
+ <RunEscapeBoundary
+ scope="chat"
+ focusKey={streamKey}
+ onEscape={requestCancellation}
+ className="@container/thread flex flex-col h-full -mx-4"
+ >
<RunSurface.Root taskId="" runId={null} streamKey={streamKey} interaction="live">
<RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
</RunSurface.Root>
- </div>
+ <div className="flex justify-end px-4 pb-4">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconStopFilled />}
+ onClick={requestCancellation}
+ loading={!!cancellationState}
+ tooltip={cancellationState ? 'Stopping…' : 'Stop'}
+ data-attr="run-startup-stop"
+ />
+ </div>
+ </RunEscapeBoundary>
</TaskRunSceneShell>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 649d1e83503b..1fb41274833b 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -1,6 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { useRef } from 'react'
+import { type RefObject, useEffect, useRef } from 'react'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
import { urls } from 'scenes/urls'
@@ -20,9 +20,10 @@ import { AttachedContextBar } from '../../../components/composer/AttachedContext
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
-import { ComposerSteerShortcut } from '../../../components/composer/ComposerSteerShortcut'
import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
+import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
+import { runCancellationLogic } from '../../../logics/runCancellationLogic'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
export interface TaskRunChatProps {
@@ -36,6 +37,10 @@ export interface TaskRunChatProps {
streamKey?: string
/** Called after a fresh run starts, in addition to the `taskDetailSceneLogic` re-pointing below. */
onRunStarted?: (runId: string) => void
+ escapeScope?: RunEscapeBoundaryProps['scope']
+ initialDraft?: string
+ onDraftAdopted?: () => void
+ autoFocus?: boolean
}
/**
@@ -46,7 +51,16 @@ export interface TaskRunChatProps {
* re-points scene selection to it. `RunSurface.Root` owns bootstrap: it reads the run status from the tasks
* API and never opens SSE for an already-terminal run.
*/
-export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunChatProps): JSX.Element {
+export function TaskRunChat({
+ taskId,
+ runId,
+ streamKey,
+ onRunStarted,
+ escapeScope = 'chat',
+ initialDraft,
+ onDraftAdopted,
+ autoFocus,
+}: TaskRunChatProps): JSX.Element {
const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))
const { selectedRun, task } = useValues(taskDetailSceneLogic({ taskId }))
const { user } = useValues(userLogic)
@@ -57,6 +71,8 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunC
taskId,
runId,
streamKey,
+ initialDraft,
+ onDraftAdopted,
currentModel: selectedRun?.state?.model,
currentEffort: selectedRun?.state?.reasoning_effort,
currentMode: selectedRun?.state?.initial_permission_mode,
@@ -72,7 +88,12 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunC
return (
<BindLogic logic={runInteractionLogic} props={logicProps}>
- <TaskRunChatContent logicProps={logicProps} readOnly={readOnly} />
+ <TaskRunChatContent
+ logicProps={logicProps}
+ readOnly={readOnly}
+ escapeScope={escapeScope}
+ autoFocus={autoFocus}
+ />
</BindLogic>
)
}
@@ -80,10 +101,21 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunC
function TaskRunChatContent({
logicProps,
readOnly,
+ escapeScope,
+ autoFocus,
}: {
logicProps: RunInteractionLogicProps
readOnly: boolean
+ escapeScope: RunEscapeBoundaryProps['scope']
+ autoFocus?: boolean
}): JSX.Element {
+ const textAreaRef = useRef<HTMLTextAreaElement>(null)
+ const { handleEscape } = useActions(runInteractionLogic(logicProps))
+ const { cancellationState } = useValues(runInteractionLogic(logicProps))
+ const { clearCancellation } = useActions(
+ runCancellationLogic({ streamKey: logicProps.streamKey ?? logicProps.runId })
+ )
+ useEffect(() => () => clearCancellation(), [clearCancellation])
// This surface renders the approval card, so persist tools must prompt here — register as a
// foreground stream (same key resolution as `RunSurface.Root`). A read-only staff view omits the
// composer and could never answer a forced prompt, so it stays a background consumer.
@@ -98,23 +130,38 @@ function TaskRunChatContent({
streamKey={logicProps.streamKey}
interaction="live"
>
- <div className="@container/thread flex flex-col h-full -mx-4">
+ <RunEscapeBoundary
+ scope={escapeScope}
+ focusKey={logicProps.streamKey ?? logicProps.runId}
+ textAreaRef={textAreaRef}
+ onEscape={handleEscape}
+ disabled={readOnly}
+ className="@container/thread flex flex-col h-full -mx-4"
+ >
<RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
{/* Stay live (stream keeps flowing) but omit the composer entirely for a read-only viewer. */}
{!readOnly && (
- <RunSurface.Composer>
+ <RunSurface.Composer isStopping={!!cancellationState}>
<RunSurface.Resources />
{/* 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} />
+ <LiveComposer logicProps={logicProps} textAreaRef={textAreaRef} autoFocus={autoFocus} />
</RunSurface.Composer>
)}
- </div>
+ </RunEscapeBoundary>
</RunSurface.Root>
)
}
-function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {
+function LiveComposer({
+ logicProps,
+ textAreaRef,
+ autoFocus,
+}: {
+ logicProps: RunInteractionLogicProps
+ textAreaRef: RefObject<HTMLTextAreaElement>
+ autoFocus?: boolean
+}): JSX.Element {
const {
composerForm,
isSubmitting,
@@ -127,6 +174,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
selectedMode,
composerActive,
steerPending,
+ cancellationState,
} = useValues(runInteractionLogic(logicProps))
const { catalogue } = useValues(modelCatalogueLogic)
// A live run's harness is whatever it booted on; once terminal the next run follows the picked model.
@@ -134,7 +182,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
const {
setComposerFormValues,
submitComposerForm,
- cancelRun,
+ requestCancellation,
updateQueuedMessage,
removeQueuedMessage,
setModel,
@@ -146,7 +194,6 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
} = useActions(runInteractionLogic(logicProps))
const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))
- const textAreaRef = useRef<HTMLTextAreaElement>(null)
return (
<>
@@ -154,19 +201,15 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
disabled={!composerActive}
onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))}
/>
- <ComposerSteerShortcut
- textAreaRef={textAreaRef}
- onSteer={steerQueue}
- disabled={!composerActive || steerPending || !queuedMessages.length}
- />
<Composer.Root
textAreaRef={textAreaRef}
value={draft.value}
onChange={draft.onChange}
onSubmit={() => draft.submit(submitComposerForm)}
loading={isSubmitting}
+ stopLoading={!!cancellationState}
isTurnActive={isBusy}
- onStop={() => cancelRun()}
+ onStop={requestCancellation}
>
{queuedMessages.length > 0 && (
<Composer.Banner>
@@ -175,7 +218,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
onUpdate={updateQueuedMessage}
onRemove={removeQueuedMessage}
onSteer={steerQueue}
- steerPending={steerPending}
+ steerPending={steerPending || !!cancellationState}
/>
</Composer.Banner>
)}
@@ -187,7 +230,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
<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.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
</Composer.Field>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
{/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index dc55842c2d21..3d10674511fa 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -1,3 +1,4 @@
+import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
@@ -11,6 +12,7 @@ import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schema
import { attachedContextLogic } from '../../api/logics'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
+import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
@@ -89,6 +91,70 @@ describe('taskTrackerSceneLogic', () => {
toolEvents?.unmount()
})
+ it.each([
+ [false, ''],
+ [true, ''],
+ [true, 'A different task'],
+ ] as const)('handles a startup stop and draft when leaving=%s with a new draft=%s', async (leave, newDraft) => {
+ let finishCreation!: (response: [number, Record<string, unknown>]) => void
+ const creation = new Promise<[number, Record<string, unknown>]>((resolve) => {
+ finishCreation = resolve
+ })
+ let createdTasks: Task[] = []
+ useMocks({
+ get: { '/api/projects/:team/tasks/': () => [200, { results: createdTasks, count: createdTasks.length }] },
+ post: { '/api/projects/:team/tasks/': () => creation },
+ })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ router.actions.push('/tasks/new')
+ logic.actions.setNewTaskData({ description: 'A synthetic task' })
+ logic.actions.submitNewTask()
+ const streamKey = logic.values.activeCreation!.streamKey
+ const cancellation = runCancellationLogic({ streamKey })
+ const unmount = cancellation.mount()
+ try {
+ cancellation.actions.requestCancellation()
+ logic.actions.setStartupDraft('A follow-up draft')
+ if (leave) {
+ router.actions.push('/tasks/another-task')
+ }
+ if (newDraft) {
+ router.actions.push('/tasks/new')
+ logic.actions.setNewTaskData({ description: newDraft })
+ }
+ createdTasks = [buildTask({ id: 'new-task', description: 'A synthetic task' })]
+ await expectLogic(logic, () =>
+ finishCreation([
+ 200,
+ {
+ id: 'new-task',
+ latest_run: { id: 'run-1' },
+ },
+ ])
+ ).toFinishAllListeners()
+ if (leave) {
+ expect(logic.values.activeCreation).toBeNull()
+ expect(cancellation.values.cancellationState).toBeNull()
+ expect(router.values.location.pathname).toContain(newDraft ? '/tasks/new' : '/tasks/another-task')
+ expect(toolEvents.values.applyBackTargetClaims[streamKey]).toBeUndefined()
+ } else {
+ expect(logic.values.activeCreation).toEqual({
+ streamKey,
+ taskId: 'new-task',
+ runId: 'run-1',
+ draft: 'A follow-up draft',
+ })
+ expect(cancellation.values.cancellationState).toBe('waiting')
+ }
+ expect(logic.values.newTaskData.description).toBe(newDraft)
+ expect(logic.values.isSubmittingTask).toBe(false)
+ await waitFor(() => expect(logic.values.tasks).toEqual(createdTasks))
+ } finally {
+ unmount()
+ }
+ })
+
it('loads PostHog Desktop access and exposes it to the task UI', async () => {
logic.mount()
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 905abfb95024..4606d4a3cbf9 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -31,6 +31,7 @@ import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
import type { ComposerSeed } from '../../logics/composerSeedLogic'
import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'
+import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import type { ActiveCreation } from '../../logics/runnerPanelLogic'
import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'
@@ -322,6 +323,9 @@ export interface taskTrackerSceneLogicActions {
setHistoryExpanded: (expanded: boolean) => {
expanded: boolean
} // runnerPanelLogic
+ setStartupDraft: (draft: string) => {
+ draft: string
+ } // runnerPanelLogic
toggleHistory: () => {
value: true
} // runnerPanelLogic
@@ -479,7 +483,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
],
actions: [
runnerPanelLogic(props),
- ['setActiveCreation', 'clearActiveCreation', 'toggleHistory', 'setHistoryExpanded'],
+ ['setActiveCreation', 'clearActiveCreation', 'setStartupDraft', 'toggleHistory', 'setHistoryExpanded'],
tasksLogic,
['loadTasks', 'loadRepositories', 'deleteTask'],
integrationsLogic,
@@ -635,8 +639,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// 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.
clearActiveCreation: () => {
- cache.activeCreationUnmount?.()
- cache.activeCreationUnmount = undefined
+ cache.disposables.dispose('active-creation')
},
// Resetting the form (after a successful submit) wipes the repo selection; immediately re-derive it
// (last persisted pick, else the first connected GitHub org) so the composer comes back with the
@@ -733,13 +736,22 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// composable optimistic-open primitive). Hold a manual mount so the seed is in place when the pending
// pane renders, and survives across the React swap into the detail page (which adopts the same
// instance by binding this `streamKey`). Released by `clearActiveCreation` (failure / leaving the run).
- cache.activeCreationUnmount?.()
- cache.activeCreationUnmount = undefined
const streamKey = `draft-${uuid()}`
const seededContext = values.contextItems
actions.claimApplyBackTargets(streamKey)
const stream = runStreamLogic({ streamKey })
- cache.activeCreationUnmount = stream.mount()
+ cache.disposables.add(
+ () => {
+ const cancellation = runCancellationLogic({ streamKey })
+ const unmount = cancellation.mount()
+ return () => {
+ cancellation.actions.clearCancellation()
+ unmount()
+ }
+ },
+ 'active-creation',
+ { pauseOnPageHidden: false }
+ )
actions.setActiveCreation({ streamKey })
stream.actions.startOptimisticRun(description)
@@ -819,6 +831,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
runId = runResponse.latest_run?.id
}
+ if (disposables.isDisposed) {
+ return
+ }
+
// Mark the seeded non-text refs sent under the created task, so the run's first follow-up
// (sent via `runInteractionLogic`) doesn't re-wrap them. Text items always resend.
const seededKeys = seededContext.filter((item) => item.type !== 'text').map(attachedContextItemKey)
@@ -826,19 +842,26 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
actions.markContextSent(newTask.id, seededKeys)
}
- // Attach the real ids to the optimistic creation so the detail page adopts this seeded stream
- // (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.
- // Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.
- actions.setActiveCreation({ streamKey, taskId: newTask.id, runId })
- // An embedded instance (`panelId` set) keeps the run in place — the host renders it from
- // `activeCreation` — rather than navigating the main app to the `/tasks/:id` detail page.
- if (!props.panelId) {
- router.actions.push(`/tasks/${newTask.id}`)
+ const creationIsActive = values.activeCreation?.streamKey === streamKey
+ if (creationIsActive) {
+ // Attach the real ids to the optimistic creation so the detail page adopts this seeded stream
+ // (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.
+ // Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.
+ actions.setActiveCreation({ streamKey, taskId: newTask.id, runId })
+ // An embedded instance (`panelId` set) keeps the run in place because the host renders
+ // `activeCreation` instead of navigating the main app to the `/tasks/:id` detail page.
+ if (!props.panelId) {
+ router.actions.push(`/tasks/${newTask.id}`)
+ }
+ } else {
+ actions.releaseApplyBackTargets(streamKey)
}
// Reset before signaling success: the success listener applies any seed held during this
// submission, and resetting afterwards would wipe that seed's prefill.
- actions.resetNewTaskData()
+ if (creationIsActive || values.newTaskData.description === description) {
+ actions.resetNewTaskData()
+ }
cache.submittingTask = null
actions.submitNewTaskSuccess()
actions.loadTasks(values.taskListParams)
@@ -914,7 +937,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
},
})),
- events(({ actions, values, cache }) => ({
+ events(({ actions, values }) => ({
afterMount: () => {
actions.loadDesktopAccess()
actions.loadTasks(values.taskListParams)
@@ -930,23 +953,15 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// panel mounts us), so pick up any pending seed now; the `setSeed` listener covers the reverse order.
actions.applyComposerSeed()
},
- beforeUnmount: () => {
- // Release the manually-mounted optimistic stream if the whole scene unmounts mid-create — the
- // `clearActiveCreation` release only fires on navigation between runs, so leaving the tasks
- // scene entirely (before the creation resolves) would otherwise leak the mounted instance.
- cache.activeCreationUnmount?.()
- cache.activeCreationUnmount = undefined
- },
})),
urlToAction(({ actions, values, props }) => {
// The optimistic creation is kept alive across the success navigation so the detail page can adopt
// its seeded stream. Release it once the user lands anywhere other than the created task — another
- // task, the list, or back to `/tasks/new`. Guarded on `taskId` being set so the pre-id provisioning
- // phase (still at `/tasks/new`, no id yet) is never torn down mid-create.
+ // task, the list, or back to `/tasks/new`. Before attachment, only `/tasks/new` owns the creation.
const clearIfLeftCreatedTask = (taskId?: string): void => {
const activeCreation = values.activeCreation
- if (activeCreation?.taskId && activeCreation.taskId !== taskId) {
+ if (activeCreation && (activeCreation.taskId ? activeCreation.taskId !== taskId : taskId !== 'new')) {
actions.clearActiveCreation()
}
}