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.

chore(tasks): remove legacy task session renderer (#65452)

Georgiy Tarasov75e32a239470
diff --git a/products/tasks/frontend/components/TaskSessionView.test.ts b/products/tasks/frontend/components/TaskSessionView.test.ts
deleted file mode 100644
index 81ed9d1796f1..000000000000
--- a/products/tasks/frontend/components/TaskSessionView.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { LogEntry } from '../lib/parse-logs'
-import { filterDuplicateInitialPromptEntry, mergeDuplicateUserPromptEntries } from './TaskSessionView'
-
-const createEntry = (overrides: Partial<LogEntry>): LogEntry => ({
- id: 'entry-1',
- type: 'user',
- message: 'Hello from the initial prompt',
- ...overrides,
-})
-
-describe('filterDuplicateInitialPromptEntry', () => {
- it.each([
- {
- name: 'drops matching plain first entry',
- entries: [
- createEntry({ id: 'entry-1' }),
- createEntry({ id: 'entry-2', type: 'agent', message: 'I read the file' }),
- ],
- prompt: 'Hello from the initial prompt',
- expected: (entries: LogEntry[]) => [entries[1]],
- },
- {
- name: 'keeps first entry when message differs',
- entries: [
- createEntry({ id: 'entry-1', message: 'A different prompt' }),
- createEntry({ id: 'entry-2', type: 'agent', message: 'I read the file' }),
- ],
- prompt: 'Hello from the initial prompt',
- expected: (entries: LogEntry[]) => entries,
- },
- {
- name: 'keeps first entry when non-user leads',
- entries: [
- createEntry({ id: 'entry-1', type: 'system', message: 'Run started' }),
- createEntry({ id: 'entry-2' }),
- ],
- prompt: 'Hello from the initial prompt',
- expected: (entries: LogEntry[]) => entries,
- },
- {
- name: 'keeps matching first entry when it has attachments',
- entries: [
- createEntry({
- id: 'entry-1',
- attachments: [{ id: 'attachment-1', label: 'file.pdf' }],
- }),
- createEntry({ id: 'entry-2', type: 'agent', message: 'ok' }),
- ],
- prompt: 'Hello from the initial prompt',
- expected: (entries: LogEntry[]) => entries,
- },
- ])('$name', ({ entries, prompt, expected }) => {
- expect(filterDuplicateInitialPromptEntry(entries, prompt)).toEqual(expected(entries))
- })
-})
-
-describe('mergeDuplicateUserPromptEntries', () => {
- it.each([
- {
- name: 'keeps the attachment-bearing first entry when followed by plain duplicate text',
- entries: [
- createEntry({
- id: 'entry-1',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-1', label: 'Receipt-2264-0277.pdf' }],
- }),
- createEntry({ id: 'entry-2', message: 'Please inspect the attached file' }),
- ],
- expected: [
- createEntry({
- id: 'entry-1',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-1', label: 'Receipt-2264-0277.pdf' }],
- }),
- ],
- },
- {
- name: 'replaces a plain user entry with a later attachment-bearing duplicate',
- entries: [
- createEntry({ id: 'entry-1', message: 'Please inspect the attached file' }),
- createEntry({
- id: 'entry-2',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-1', label: 'Receipt-2264-0277.pdf' }],
- }),
- ],
- expected: [
- createEntry({
- id: 'entry-2',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-1', label: 'Receipt-2264-0277.pdf' }],
- }),
- ],
- },
- {
- name: 'merges attachments when both duplicate entries have them',
- entries: [
- createEntry({
- id: 'entry-1',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-1', label: 'Receipt-2264-0277.pdf' }],
- }),
- createEntry({
- id: 'entry-2',
- message: 'Please inspect the attached file',
- attachments: [{ id: 'attachment-2', label: 'New Project.png' }],
- }),
- ],
- expected: [
- createEntry({
- id: 'entry-1',
- message: 'Please inspect the attached file',
- attachments: [
- { id: 'attachment-1', label: 'Receipt-2264-0277.pdf' },
- { id: 'attachment-2', label: 'New Project.png' },
- ],
- }),
- ],
- },
- {
- name: 'keeps distinct user entries untouched',
- entries: [
- createEntry({ id: 'entry-1', message: 'First prompt' }),
- createEntry({ id: 'entry-2', message: 'Second prompt' }),
- ],
- expected: [
- createEntry({ id: 'entry-1', message: 'First prompt' }),
- createEntry({ id: 'entry-2', message: 'Second prompt' }),
- ],
- },
- ])('$name', ({ entries, expected }) => {
- expect(mergeDuplicateUserPromptEntries(entries)).toEqual(expected)
- })
-})
diff --git a/products/tasks/frontend/components/TaskSessionView.tsx b/products/tasks/frontend/components/TaskSessionView.tsx
deleted file mode 100644
index 58e4f6d10962..000000000000
--- a/products/tasks/frontend/components/TaskSessionView.tsx
+++ /dev/null
@@ -1,299 +0,0 @@
-import { useEffect, useMemo, useState } from 'react'
-import { TextMorph } from 'torph/react'
-
-import { IconCopy } from '@posthog/icons'
-import { LemonButton, LemonSwitch, LemonTag, Spinner } from '@posthog/lemon-ui'
-
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-
-import { LogEntry, parseLogs } from '../lib/parse-logs'
-import { TaskRun } from '../types'
-import { CollapsibleContent } from './CollapsibleContent'
-import { ConsoleLogEntry } from './session/ConsoleLogEntry'
-import { ToolCallEntry } from './session/ToolCallEntry'
-import { TaskRunStatusBadge } from './TaskRunStatusBadge'
-
-const HEDGEHOG_STATUSES = [
- 'Spiking...',
- 'Hedgehogging...',
- 'Snuffling...',
- 'Curling up...',
- 'Foraging...',
- 'Quilling...',
- 'Hibernating...',
- 'Scurrying...',
- 'Bristling...',
- 'Noodling...',
- 'Hogwatching...',
- 'Prickling...',
- 'Burrowing...',
- 'Snoot booping...',
- 'Uncurling...',
-]
-
-function HedgehogStatus(): JSX.Element {
- const [statusIndex, setStatusIndex] = useState(() => Math.floor(Math.random() * HEDGEHOG_STATUSES.length))
-
- useEffect(() => {
- const interval = setInterval(() => {
- setStatusIndex((prev) => (prev + 1) % HEDGEHOG_STATUSES.length)
- }, 2000)
- return () => clearInterval(interval)
- }, [])
-
- return (
- <div className="flex items-center gap-2 py-2 text-muted">
- <Spinner className="text-xs" />
- <TextMorph as="span" className="text-xs">
- {HEDGEHOG_STATUSES[statusIndex]}
- </TextMorph>
- </div>
- )
-}
-
-interface TaskSessionViewProps {
- logs: string
- logsLoading: boolean
- streamEntries: LogEntry[]
- isPolling: boolean
- isStreaming: boolean
- initialPrompt?: string | null
- run: TaskRun | null
-}
-
-export function filterDuplicateInitialPromptEntry(entries: LogEntry[], initialPrompt?: string | null): LogEntry[] {
- const normalizedPrompt = initialPrompt?.trim()
- if (!normalizedPrompt || entries.length === 0) {
- return entries
- }
-
- const [firstEntry, ...restEntries] = entries
- if (
- firstEntry.type !== 'user' ||
- firstEntry.message?.trim() !== normalizedPrompt ||
- (firstEntry.attachments?.length ?? 0) > 0
- ) {
- return entries
- }
-
- return restEntries
-}
-
-export function mergeDuplicateUserPromptEntries(entries: LogEntry[]): LogEntry[] {
- return entries.reduce<LogEntry[]>((mergedEntries, entry) => {
- const previousEntry = mergedEntries[mergedEntries.length - 1]
-
- if (
- previousEntry?.type === 'user' &&
- entry.type === 'user' &&
- previousEntry.message?.trim() === entry.message?.trim()
- ) {
- const previousHasAttachments = Boolean(previousEntry.attachments?.length)
- const currentHasAttachments = Boolean(entry.attachments?.length)
-
- if (!previousHasAttachments && currentHasAttachments) {
- mergedEntries[mergedEntries.length - 1] = entry
- } else if (previousHasAttachments && currentHasAttachments) {
- mergedEntries[mergedEntries.length - 1] = {
- ...previousEntry,
- attachments: [...(previousEntry.attachments ?? []), ...(entry.attachments ?? [])],
- }
- }
-
- return mergedEntries
- }
-
- mergedEntries.push(entry)
- return mergedEntries
- }, [])
-}
-
-function LogEntryRenderer({ entry, renderMarkdown }: { entry: LogEntry; renderMarkdown: boolean }): JSX.Element | null {
- switch (entry.type) {
- case 'console':
- return (
- <ConsoleLogEntry
- level={entry.level || 'info'}
- message={entry.message || ''}
- timestamp={entry.timestamp}
- />
- )
- case 'tool':
- return (
- <ToolCallEntry
- toolName={entry.toolName || 'unknown'}
- status={entry.toolStatus || 'pending'}
- args={entry.toolArgs}
- result={entry.toolResult}
- timestamp={entry.timestamp}
- />
- )
- case 'user':
- return (
- <div className="py-2 flex flex-col items-end">
- <div className="flex items-center gap-2 mb-1">
- <span className="text-xs font-medium">User</span>
- {entry.timestamp && (
- <span className="text-xs text-muted">{new Date(entry.timestamp).toLocaleTimeString()}</span>
- )}
- </div>
- <div className="border-r-2 border-muted pr-3 max-w-[90%] text-right">
- <CollapsibleContent gradientColor="--bg-3000">
- <div className="text-sm whitespace-pre-wrap">{entry.message}</div>
- </CollapsibleContent>
- {entry.attachments && entry.attachments.length > 0 ? (
- <div className="mt-2 flex flex-wrap justify-end gap-2">
- {entry.attachments.map((attachment) => (
- <LemonTag key={attachment.id} type="completion" size="small">
- {attachment.label}
- </LemonTag>
- ))}
- </div>
- ) : null}
- </div>
- </div>
- )
- case 'agent':
- return (
- <div className="py-2">
- <div className="flex items-center gap-2 mb-1">
- {entry.timestamp && (
- <span className="text-xs text-muted">{new Date(entry.timestamp).toLocaleTimeString()}</span>
- )}
- <span className="text-xs font-medium">Agent</span>
- </div>
- <div className="border-l-2 border-primary pl-3 max-w-[90%]">
- {renderMarkdown && entry.message ? (
- <LemonMarkdown className="text-sm font-sans" lowKeyHeadings disableImages>
- {entry.message}
- </LemonMarkdown>
- ) : (
- <div className="text-sm whitespace-pre-wrap">{entry.message}</div>
- )}
- </div>
- </div>
- )
- case 'thinking':
- return (
- <div className="py-2">
- <div className="flex items-center gap-2 mb-1">
- {entry.timestamp && (
- <span className="text-xs text-muted">{new Date(entry.timestamp).toLocaleTimeString()}</span>
- )}
- <span className="text-xs font-medium text-muted">Thinking</span>
- </div>
- <div className="border-l-2 border-muted pl-3 max-w-[90%]">
- <CollapsibleContent gradientColor="--bg-3000">
- <div className="text-sm whitespace-pre-wrap text-muted">{entry.message}</div>
- </CollapsibleContent>
- </div>
- </div>
- )
- case 'system':
- return (
- <div className="flex items-center gap-2 py-1">
- {entry.timestamp && (
- <span className="text-xs text-muted">{new Date(entry.timestamp).toLocaleTimeString()}</span>
- )}
- <span className="text-xs text-muted italic">{entry.message}</span>
- </div>
- )
- case 'raw':
- return <div className="py-0.5 text-xs font-mono text-muted break-all">{entry.raw}</div>
- default:
- return null
- }
-}
-
-export function TaskSessionView({
- logs,
- logsLoading,
- streamEntries,
- isPolling,
- isStreaming,
- initialPrompt,
- run,
-}: TaskSessionViewProps): JSX.Element {
- // Debug lines are noise by default; opt in to show them.
- const [showDebug, setShowDebug] = useState(false)
- const [renderMarkdown, setRenderMarkdown] = useState(true)
- const parsedLogs = useMemo(() => parseLogs(logs), [logs])
- // Use stream entries when available (real-time), otherwise fall back to parsed S3 logs
- const entries = useMemo(() => {
- const sourceEntries = streamEntries.length > 0 ? streamEntries : parsedLogs
- return filterDuplicateInitialPromptEntry(mergeDuplicateUserPromptEntries(sourceEntries), initialPrompt)
- }, [initialPrompt, parsedLogs, streamEntries])
-
- const debugCount = useMemo(
- () => entries.filter((entry) => entry.type === 'console' && entry.level === 'debug').length,
- [entries]
- )
- const agentCount = useMemo(() => entries.filter((entry) => entry.type === 'agent').length, [entries])
- const visibleEntries = useMemo(
- () => (showDebug ? entries : entries.filter((entry) => !(entry.type === 'console' && entry.level === 'debug'))),
- [entries, showDebug]
- )
-
- const handleCopyLogs = (): void => {
- navigator.clipboard.writeText(logs).then(
- () => lemonToast.success('Logs copied to clipboard'),
- () => lemonToast.error('Failed to copy logs')
- )
- }
-
- if (entries.length === 0) {
- if (logsLoading) {
- return (
- <div className="flex items-center justify-center h-32">
- <Spinner />
- </div>
- )
- }
- return (
- <div className="p-4 text-center text-muted">
- <p>No logs available yet</p>
- </div>
- )
- }
-
- return (
- <div className="flex flex-col h-full">
- <div className="flex justify-between items-center px-4 py-2 border-b">
- <div className="flex items-center gap-2">
- {run && <TaskRunStatusBadge run={run} />}
- <span className="text-sm font-semibold">Logs ({visibleEntries.length})</span>
- </div>
- <div className="flex items-center gap-2">
- {agentCount > 0 && (
- <LemonSwitch
- label="Markdown"
- checked={renderMarkdown}
- onChange={setRenderMarkdown}
- size="xsmall"
- bordered
- />
- )}
- {debugCount > 0 && (
- <LemonSwitch
- label={`Show debug (${debugCount})`}
- checked={showDebug}
- onChange={setShowDebug}
- size="xsmall"
- bordered
- />
- )}
- <LemonButton size="xsmall" icon={<IconCopy />} onClick={handleCopyLogs}>
- Copy
- </LemonButton>
- </div>
- </div>
- <div className="flex-1 overflow-auto p-4 font-mono text-sm bg-bg-3000">
- {visibleEntries.map((entry) => (
- <LogEntryRenderer key={entry.id} entry={entry} renderMarkdown={renderMarkdown} />
- ))}
- {(isPolling || isStreaming) && <HedgehogStatus />}
- </div>
- </div>
- )
-}
diff --git a/products/tasks/frontend/components/session/ConsoleLogEntry.tsx b/products/tasks/frontend/components/session/ConsoleLogEntry.tsx
deleted file mode 100644
index f13c93ce8b6d..000000000000
--- a/products/tasks/frontend/components/session/ConsoleLogEntry.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { LemonTag } from '@posthog/lemon-ui'
-
-import { LogLevel } from '../../lib/parse-logs'
-
-interface ConsoleLogEntryProps {
- level: LogLevel
- message: string
- timestamp?: string
-}
-
-const LEVEL_CONFIG: Record<LogLevel, { type: 'default' | 'warning' | 'danger' | 'highlight' }> = {
- info: { type: 'default' },
- debug: { type: 'highlight' },
- warn: { type: 'warning' },
- error: { type: 'danger' },
-}
-
-export function ConsoleLogEntry({ level, message, timestamp }: ConsoleLogEntryProps): JSX.Element {
- const config = LEVEL_CONFIG[level]
-
- return (
- <div className="flex items-start gap-2 py-2">
- {timestamp && (
- <span className="text-xs text-muted shrink-0">{new Date(timestamp).toLocaleTimeString()}</span>
- )}
- <LemonTag type={config.type} size="small" className="shrink-0 uppercase">
- {level}
- </LemonTag>
- <span className="text-sm flex-1 break-words">{message}</span>
- </div>
- )
-}
diff --git a/products/tasks/frontend/components/session/ToolCallEntry.tsx b/products/tasks/frontend/components/session/ToolCallEntry.tsx
deleted file mode 100644
index 0948d04e6ed1..000000000000
--- a/products/tasks/frontend/components/session/ToolCallEntry.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-import { useState } from 'react'
-
-import { IconChevronRight, IconTerminal } from '@posthog/icons'
-import { LemonSwitch, LemonTag, Spinner } from '@posthog/lemon-ui'
-
-import { ToolStatus } from '../../lib/parse-logs'
-
-interface ToolCallEntryProps {
- toolName: string
- status: ToolStatus
- args?: Record<string, unknown>
- result?: unknown
- timestamp?: string
-}
-
-const STATUS_CONFIG: Record<ToolStatus, { label: string; type: 'default' | 'primary' | 'success' | 'danger' }> = {
- pending: { label: 'Pending', type: 'default' },
- running: { label: 'Running', type: 'primary' },
- completed: { label: 'Done', type: 'success' },
- error: { label: 'Failed', type: 'danger' },
-}
-
-function isTextPart(item: unknown): item is { type: 'text'; text: string } {
- return (
- typeof item === 'object' &&
- item !== null &&
- (item as Record<string, unknown>).type === 'text' &&
- typeof (item as Record<string, unknown>).text === 'string'
- )
-}
-
-// Returns the parsed value only when the string is a JSON object/array, otherwise undefined.
-function tryParseJson(text: string): unknown {
- const trimmed = text.trim()
- const first = trimmed[0]
- if (first !== '{' && first !== '[') {
- return undefined
- }
- try {
- return JSON.parse(trimmed)
- } catch {
- return undefined
- }
-}
-
-// Recursively expand any string that is itself JSON, so double-encoded payloads render as real structure.
-function expandEmbeddedJson(value: unknown): unknown {
- if (typeof value === 'string') {
- const parsed = tryParseJson(value)
- return parsed !== undefined ? expandEmbeddedJson(parsed) : value
- }
- if (Array.isArray(value)) {
- return value.map(expandEmbeddedJson)
- }
- if (value && typeof value === 'object') {
- return Object.fromEntries(
- Object.entries(value as Record<string, unknown>).map(([key, val]) => [key, expandEmbeddedJson(val)])
- )
- }
- return value
-}
-
-// MCP tool results usually arrive as [{ type: 'text', text: '...' }]; pull the text out so newlines render.
-function extractTextParts(value: unknown): string | null {
- const items = Array.isArray(value) ? value : [value]
- const texts: string[] = []
- for (const item of items) {
- if (!isTextPart(item)) {
- return null
- }
- texts.push(item.text)
- }
- return texts.length ? texts.join('\n\n') : null
-}
-
-function formatValue(value: unknown, pretty: boolean): string {
- if (!pretty) {
- return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
- }
- const text = extractTextParts(value)
- const candidate = text ?? (typeof value === 'string' ? value : null)
- if (candidate !== null) {
- const parsed = tryParseJson(candidate)
- return parsed !== undefined ? JSON.stringify(expandEmbeddedJson(parsed), null, 2) : candidate
- }
- return JSON.stringify(expandEmbeddedJson(value), null, 2)
-}
-
-export function ToolCallEntry({ toolName, status, args, result, timestamp }: ToolCallEntryProps): JSX.Element {
- const [isOpen, setIsOpen] = useState(false)
- const [pretty, setPretty] = useState(true)
- const config = STATUS_CONFIG[status]
- const hasContent = args || result !== undefined
- const isLoading = status === 'pending' || status === 'running'
-
- const HeaderContent = (
- <>
- {timestamp && <span className="text-xs text-muted">{new Date(timestamp).toLocaleTimeString()}</span>}
- {hasContent && (
- <IconChevronRight
- className={`text-muted transition-transform ${isOpen ? 'rotate-90' : ''}`}
- fontSize="12"
- />
- )}
- {isLoading ? <Spinner className="text-muted" /> : <IconTerminal className="text-muted" fontSize="14" />}
- <code className="text-xs text-secondary">{toolName}</code>
- <LemonTag type={config.type} size="small">
- {config.label}
- </LemonTag>
- </>
- )
-
- return (
- <div className="py-2">
- {hasContent ? (
- <button
- type="button"
- onClick={() => setIsOpen(!isOpen)}
- className="flex items-center gap-2 w-full text-left rounded hover:bg-bg-light cursor-pointer"
- >
- {HeaderContent}
- </button>
- ) : (
- <div className="flex items-center gap-2 w-full text-left rounded">{HeaderContent}</div>
- )}
-
- {isOpen && hasContent && (
- <div className="ml-5 mt-1 rounded bg-bg-light p-2 overflow-hidden">
- <div className="flex justify-end mb-1">
- <LemonSwitch
- label="Pretty print"
- checked={pretty}
- onChange={setPretty}
- size="xsmall"
- bordered
- />
- </div>
- {args && (
- <div className="mb-2">
- <div className="text-xs font-medium text-muted mb-1">Arguments</div>
- <pre className="text-xs overflow-x-auto whitespace-pre-wrap break-words">
- {formatValue(args, pretty)}
- </pre>
- </div>
- )}
- {result !== undefined && (
- <div>
- <div className="text-xs font-medium text-muted mb-1">Result</div>
- <pre className="text-xs overflow-x-auto whitespace-pre-wrap break-words">
- {formatValue(result, pretty)}
- </pre>
- </div>
- )}
- </div>
- )}
- </div>
- )
-}
diff --git a/products/tasks/frontend/lib/ph-debug.ts b/products/tasks/frontend/lib/ph-debug.ts
index 6f70b0764108..3f427807918c 100644
--- a/products/tasks/frontend/lib/ph-debug.ts
+++ b/products/tasks/frontend/lib/ph-debug.ts
@@ -7,8 +7,7 @@ import { router } from 'kea-router'
*
* Use `phDebugQueryParams()` with API helpers that take a params object
* (`api.tasks.get`, `api.tasks.runs.get`, …) — they pipe it through
- * `withQueryString`. Use `phDebugQuerySuffix()` when building a request URL by
- * hand (e.g. the `/logs/` proxy endpoint that `loadLogs` consumes).
+ * `withQueryString`.
*/
function isPhDebugSet(): boolean {
const value = router.values.searchParams?.ph_debug
@@ -18,7 +17,3 @@ function isPhDebugSet(): boolean {
export function phDebugQueryParams(): { ph_debug?: 'true' } {
return isPhDebugSet() ? { ph_debug: 'true' } : {}
}
-
-export function phDebugQuerySuffix(): '' | '?ph_debug=true' {
- return isPhDebugSet() ? '?ph_debug=true' : ''
-}
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
index c32b0d8f1ab3..30b1d2165016 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
@@ -1,8 +1,4 @@
import { expectLogic } from 'kea-test-utils'
-import { ReadableStream as NodeReadableStream } from 'stream/web'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
@@ -44,105 +40,19 @@ const createMockRun = (id: string, status: TaskRunStatus): TaskRun => ({
completed_at: null,
})
-function buildReadableStream(chunks: string[], keepOpen = false): ReadableStream<Uint8Array> {
- const encoder = new TextEncoder()
- let index = 0
- const StreamConstructor = globalThis.ReadableStream ?? NodeReadableStream
-
- return new StreamConstructor({
- pull(controller) {
- if (index < chunks.length) {
- controller.enqueue(encoder.encode(chunks[index]))
- index += 1
- } else if (!keepOpen) {
- controller.close()
- }
- },
- })
-}
-
-function createSseResponse(chunks: string[], keepOpen = false): Response {
- return {
- ok: true,
- body: buildReadableStream(chunks, keepOpen),
- } as Response
-}
-
-function createConsoleSseEvent(id: string, message: string): string {
- return `id: ${id}\nevent: message\ndata: ${JSON.stringify({
- type: 'notification',
- timestamp: '2024-01-01T00:00:00Z',
- notification: {
- jsonrpc: '2.0',
- method: '_posthog/console',
- params: { level: 'info', message },
- },
- })}\n\n`
-}
-
-function createToolCallSseEvent(id: string, toolCallId: string, status: string, rawOutput?: unknown): string {
- return `id: ${id}\nevent: message\ndata: ${JSON.stringify({
- type: 'notification',
- timestamp: '2024-01-01T00:00:00Z',
- notification: {
- jsonrpc: '2.0',
- method: 'session/update',
- params: {
- update: {
- sessionUpdate: status === 'pending' || status === 'in_progress' ? 'tool_call' : 'tool_call_update',
- toolCallId,
- title: 'Read file',
- status,
- rawInput: { path: 'README.md' },
- ...(rawOutput !== undefined ? { rawOutput } : {}),
- },
- },
- },
- })}\n\n`
-}
-
function createJsonResponse(payload: unknown): Response {
return new Response(JSON.stringify(payload), {
headers: { 'Content-Type': 'application/json' },
})
}
-function createFetchMock({
- runs = {},
- streamResponses = [],
- streamBaseUrl = null,
-}: {
- runs?: Record<string, TaskRun>
- streamResponses?: Response[]
- streamBaseUrl?: string | null
-} = {}): typeof fetch {
+function createFetchMock({ runs = {} }: { runs?: Record<string, TaskRun> } = {}): typeof fetch {
return jest.fn((input: RequestInfo | URL) => {
const url = String(input)
- const streamTokenMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/stream_token\/$/)
const taskRunMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/$/)
- // Matches both the Django read path (.../runs/:run/stream/) and the proxy path (/v1/runs/:run/stream).
- const streamMatch = url.match(/\/runs\/([^/]+)\/stream\/?(\?|$)/)
- const logsMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/logs\/$/)
const runsListMatch = url.match(/\/tasks\/([^/]+)\/runs\/$/)
const taskMatch = url.match(/\/tasks\/([^/]+)\/$/)
- if (url.includes('/_preflight')) {
- // Keep is_debug unset so streamViaProxyEnabled is driven purely by the feature flag.
- return Promise.resolve(createJsonResponse({}))
- }
- if (streamTokenMatch) {
- return Promise.resolve(createJsonResponse({ token: 'proxy-test-token', stream_base_url: streamBaseUrl }))
- }
- if (streamMatch) {
- const nextResponse = streamResponses.shift()
- if (!nextResponse) {
- throw new Error(`Missing stream response for ${url}`)
- }
- return Promise.resolve(nextResponse)
- }
- if (logsMatch) {
- return Promise.resolve(new Response(''))
- }
if (taskRunMatch) {
return Promise.resolve(
createJsonResponse(runs[taskRunMatch[2]] ?? createMockRun(taskRunMatch[2], TaskRunStatus.COMPLETED))
@@ -158,15 +68,6 @@ function createFetchMock({
}) as typeof fetch
}
-async function flushStreaming(): Promise<void> {
- // fetch-event-source has a deeper internal async chain (fetch -> onopen -> getBytes
- // -> getLines -> getMessages -> onmessage), so flush several macro+micro cycles.
- for (let i = 0; i < 6; i++) {
- await Promise.resolve()
- await new Promise((resolve) => setTimeout(resolve, 0))
- }
-}
-
describe('taskDetailSceneLogic', () => {
const originalFetch = global.fetch
@@ -289,464 +190,4 @@ describe('taskDetailSceneLogic', () => {
tasksLogicInstance.unmount()
})
})
-
- describe('streaming', () => {
- const getHeader = (init: RequestInit | undefined, name: string): string | undefined => {
- const headers = (init?.headers ?? {}) as Record<string, string>
- const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name.toLowerCase())
- return key !== undefined ? headers[key] : undefined
- }
-
- const streamFetchCalls = (): [RequestInfo | URL, RequestInit | undefined][] =>
- (global.fetch as jest.Mock).mock.calls.filter(([url]) => /\/runs\/[^/]+\/stream\/?(\?|$)/.test(String(url)))
-
- const streamTokenFetchCalls = (): [RequestInfo | URL, RequestInit | undefined][] =>
- (global.fetch as jest.Mock).mock.calls.filter(([url]) => String(url).includes('/stream_token/'))
-
- // The durable-streaming rollout flag gates stream_token resolution and status-unaware
- // streams; tests covering the new behavior opt in explicitly, the rest run with it off.
- const enableProxyStreaming = (): void =>
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY], {
- [FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY]: true,
- })
-
- beforeEach(() => {
- window.sessionStorage.clear()
- })
-
- afterEach(() => {
- jest.useRealTimers()
- })
-
- it('streams events, dedupes by id, and resumes from the last event id on restart', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(
- [
- 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
- 'id: 2-0\nevent: message\ndata: {"type":"assistant","content":"world"}\n\n',
- ],
- true
- ),
- createSseResponse(
- [
- 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
- 'event: keepalive\ndata: {"status":"ok"}\n\n',
- 'id: 3-0\nevent: message\ndata: {"type":"assistant","content":"again"}\n\n',
- ],
- true
- ),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.lastStreamEventId).toBe('2-0')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'world'])
-
- logic.actions.stopStreaming()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.startStreaming()
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- const calls = streamFetchCalls()
- expect(calls).toHaveLength(2)
- expect(getHeader(calls[1][1], 'Last-Event-ID')).toBe('2-0')
- expect(logic.values.lastStreamEventId).toBe('3-0')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'worldagain'])
-
- logic.unmount()
- })
-
- it('resumes from the sessionStorage event id after a page refresh', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- window.sessionStorage.setItem('tasks:stream-resume:run-1', '5-0')
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(
- ['id: 6-0\nevent: message\ndata: {"type":"assistant","content":"resumed"}\n\n'],
- true
- ),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- const calls = streamFetchCalls()
- expect(calls).toHaveLength(1)
- expect(getHeader(calls[0][1], 'Last-Event-ID')).toBe('5-0')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['resumed'])
-
- logic.unmount()
- })
-
- it('stops on a stream-end event for a terminal run without reconnecting or downgrading to polling', async () => {
- const run = createMockRun('run-1', TaskRunStatus.COMPLETED)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse([
- createConsoleSseEvent('1-0', 'hello'),
- 'event: stream-end\ndata: {"status":"complete"}\n\n',
- ]),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- enableProxyStreaming()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.streamComplete).toBe(true)
- expect(logic.values.streamingFailed).toBe(false)
- expect(logic.values.isStreaming).toBe(false)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
- expect(streamFetchCalls()).toHaveLength(1)
- expect(window.sessionStorage.getItem('tasks:stream-resume:run-1')).toBeNull()
-
- logic.unmount()
- })
-
- it('keeps the pre-proxy behavior with the flag off: terminal runs never stream or fetch a stream token', async () => {
- const run = createMockRun('run-1', TaskRunStatus.COMPLETED)
- global.fetch = createFetchMock({ runs: { [run.id]: run } })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.isStreaming).toBe(false)
- expect(streamFetchCalls()).toHaveLength(0)
- expect(streamTokenFetchCalls()).toHaveLength(0)
-
- logic.unmount()
- })
-
- it('streams live runs with the flag off via the Django path without fetching a stream token', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n'], true),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- const calls = streamFetchCalls()
- expect(calls).toHaveLength(1)
- expect(String(calls[0][0])).toContain('/api/projects/@current/tasks/task-123/runs/run-1/stream/')
- expect(streamTokenFetchCalls()).toHaveLength(0)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
-
- logic.unmount()
- })
-
- it('polls after a stream-end event when the refreshed run is still in progress', async () => {
- const setIntervalSpy = jest.spyOn(window, 'setInterval')
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse([
- createConsoleSseEvent('1-0', 'hello'),
- 'event: stream-end\ndata: {"status":"complete"}\n\n',
- ]),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.streamComplete).toBe(true)
- expect(logic.values.streamingFailed).toBe(false)
- expect(logic.values.isStreaming).toBe(false)
- expect(streamFetchCalls()).toHaveLength(1)
- expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 1000)
-
- logic.unmount()
- })
-
- it('routes the stream through the proxy when the server resolves a stream base url', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamBaseUrl: 'https://proxy.example/',
- streamResponses: [
- createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hi"}\n\n'], true),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- enableProxyStreaming()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- const calls = streamFetchCalls()
- expect(calls).toHaveLength(1)
- expect(String(calls[0][0])).toBe('https://proxy.example/v1/runs/run-1/stream')
- expect(getHeader(calls[0][1], 'Authorization')).toBe('Bearer proxy-test-token')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hi'])
-
- logic.unmount()
- })
-
- it('refreshes the stream token and reconnects when the proxy rejects an expired token', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamBaseUrl: 'https://proxy.example/',
- streamResponses: [
- new Response(JSON.stringify({ error: 'Invalid stream read token' }), { status: 401 }),
- createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hi"}\n\n'], true),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- enableProxyStreaming()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
- await flushStreaming()
-
- expect(streamTokenFetchCalls()).toHaveLength(2)
- expect(streamFetchCalls()).toHaveLength(2)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hi'])
- expect(logic.values.streamingFailed).toBe(false)
-
- logic.unmount()
- })
-
- it('reconnects after a dropped connection without latching to polling', async () => {
- jest.useFakeTimers()
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- // First connection emits one event then the body ends (a drop)
- createSseResponse([createConsoleSseEvent('1-0', 'first message')]),
- // Reconnect picks up the next event and stays open
- createSseResponse([createConsoleSseEvent('2-0', 'second message')], true),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await jest.advanceTimersByTimeAsync(0)
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await jest.advanceTimersByTimeAsync(0)
-
- // A drop must not immediately downgrade to polling
- expect(logic.values.streamingFailed).toBe(false)
-
- // Advance past the first reconnect backoff (1000ms base)
- await jest.advanceTimersByTimeAsync(1000)
- await jest.advanceTimersByTimeAsync(0)
-
- const calls = streamFetchCalls()
- expect(calls).toHaveLength(2)
- expect(logic.values.streamingFailed).toBe(false)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([
- 'first message',
- 'second message',
- ])
-
- logic.unmount()
- })
-
- it('exhausts the reconnect budget when connections die immediately instead of looping forever', async () => {
- jest.useFakeTimers()
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- // Initial connection plus MAX_STREAM_RECONNECTS retries, all dying instantly.
- // None lives past STREAM_MIN_HEALTHY_CONNECTION_MS, so the budget never resets.
- streamResponses: Array.from({ length: 7 }, () => createSseResponse([])),
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await jest.advanceTimersByTimeAsync(0)
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await jest.advanceTimersByTimeAsync(0)
-
- // Walk through every reconnect backoff: 1s, 2s, 4s, 8s, then capped at 15s.
- for (const backoffMs of [1000, 2000, 4000, 8000, 15000, 15000]) {
- await jest.advanceTimersByTimeAsync(backoffMs)
- await jest.advanceTimersByTimeAsync(0)
- }
-
- expect(streamFetchCalls()).toHaveLength(7)
- expect(logic.values.streamingFailed).toBe(true)
- expect(logic.values.isStreaming).toBe(false)
-
- logic.unmount()
- })
-
- it('does not restart an active stream when selected run reloads', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(
- ['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hello"}\n\n'],
- true
- ),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(streamFetchCalls()).toHaveLength(1)
-
- logic.actions.loadSelectedRunSuccess(run)
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(streamFetchCalls()).toHaveLength(1)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
-
- logic.unmount()
- })
-
- it('ignores duplicate event ids that arrive in the same chunk', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(
- [
- [
- 'id: 1-0',
- 'event: message',
- 'data: {"type":"assistant","content":"hello"}',
- '',
- 'id: 1-0',
- 'event: message',
- 'data: {"type":"assistant","content":"hello"}',
- '',
- ].join('\n'),
- ],
- true
- ),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.lastStreamEventId).toBe('1-0')
- expect(logic.values.streamEntries.map((entry) => entry.id)).toEqual(['stream-1-0'])
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
-
- logic.unmount()
- })
-
- it('preserves tool state across resumed streams', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
- global.fetch = createFetchMock({
- runs: { [run.id]: run },
- streamResponses: [
- createSseResponse([createToolCallSseEvent('1-0', 'tool-1', 'in_progress')], true),
- createSseResponse(
- [
- createToolCallSseEvent('1-0', 'tool-1', 'in_progress'),
- createToolCallSseEvent('2-0', 'tool-1', 'completed', { content: 'done' }),
- ],
- true
- ),
- ],
- })
-
- const logic = taskDetailSceneLogic({ taskId: 'task-123' })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- const firstToolEntry = logic.values.streamEntries[0]
- expect(logic.values.streamEntries).toHaveLength(1)
- expect(firstToolEntry.type).toBe('tool')
- expect(firstToolEntry.id).toBe('stream-1-0')
- expect(firstToolEntry.toolStatus).toBe('running')
-
- logic.actions.stopStreaming()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.startStreaming()
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
-
- expect(logic.values.lastStreamEventId).toBe('2-0')
- expect(logic.values.streamEntries).toHaveLength(1)
- expect(logic.values.streamEntries[0]).toMatchObject({
- id: 'stream-1-0',
- type: 'tool',
- toolCallId: 'tool-1',
- toolStatus: 'completed',
- toolResult: { content: 'done' },
- })
- expect(logic.values.streamEntries[0]).not.toBe(firstToolEntry)
-
- logic.unmount()
- })
- })
})
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
index 0496be4eb945..d8e0e9d77e80 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
@@ -1,136 +1,26 @@
-import {
- actions,
- afterMount,
- beforeUnmount,
- connect,
- kea,
- key,
- listeners,
- path,
- props,
- propsChanged,
- reducers,
- selectors,
-} from 'kea'
+import { actions, afterMount, connect, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
-import api, { type EventSourceMessage } from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import api from 'lib/api'
import { isUUIDLike } from 'lib/utils/guards'
-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { tasksRunsStreamTokenRetrieve } from '../generated/api'
-import { LogEntry, parseLogEvent } from '../lib/parse-logs'
-import { phDebugQueryParams, phDebugQuerySuffix } from '../lib/ph-debug'
-import { TaskRun, TaskRunStatus } from '../types'
+import { phDebugQueryParams } from '../lib/ph-debug'
+import { TaskRun } from '../types'
import type { taskDetailSceneLogicType } from './taskDetailSceneLogicType'
import { TaskLogicProps, taskLogic } from './taskLogic'
import { tasksLogic } from './tasksLogic'
-const LOG_POLL_INTERVAL_MS = 1000
-// Reconnect the live stream a bounded number of times with exponential backoff
-// before giving up. End-of-run is signalled in-band (the `stream-end` event), so
-// a dropped connection always means "reconnect", never "the run is done".
-const MAX_STREAM_RECONNECTS = 6
-const STREAM_RECONNECT_BASE_MS = 1000
-const STREAM_RECONNECT_MAX_MS = 15000
-// A connection must stay open this long before a later drop earns a fresh reconnect
-// budget. Resetting on every open would let a rapid open-and-die loop reconnect forever.
-const STREAM_MIN_HEALTHY_CONNECTION_MS = 5000
-// "Run is complete" terminal event. Named COMPLETE (not END) because connection-rotation
-// work introduces a separate `end` event that means "reconnect", the opposite semantics.
-const STREAM_COMPLETE_EVENT = 'stream-end'
-
export type TaskDetailSceneLogicProps = TaskLogicProps
-function streamResumeStorageKey(runId: string): string {
- return `tasks:stream-resume:${runId}`
-}
-
-function readStreamResumeId(runId: string): string | null {
- try {
- return window.sessionStorage.getItem(streamResumeStorageKey(runId))
- } catch {
- return null
- }
-}
-
-function writeStreamResumeId(runId: string, eventId: string): void {
- try {
- window.sessionStorage.setItem(streamResumeStorageKey(runId), eventId)
- } catch {
- // sessionStorage may be unavailable (private mode / quota) — resume from in-memory state only
- }
-}
-
-function clearStreamResumeId(runId: string): void {
- try {
- window.sessionStorage.removeItem(streamResumeStorageKey(runId))
- } catch {
- // ignore
- }
-}
-
-function buildToolMap(entries: LogEntry[]): Map<string, LogEntry> {
- const toolMap = new Map<string, LogEntry>()
- for (const entry of entries) {
- if (entry.type === 'tool' && entry.toolCallId) {
- toolMap.set(entry.toolCallId, { ...entry })
- }
- }
- return toolMap
-}
-
-interface StreamTarget {
- url: string
- headers: Record<string, string>
-}
-
-// Route the live stream through the standalone agent-proxy when the rollout flag is on AND the
-// server resolves a base URL for it; otherwise hit the Django endpoint directly. The proxy is
-// purely additive: if the token call fails (or the server returns no base URL), we fall back to
-// the Django path, so streaming never breaks. With the flag off the token call is skipped
-// entirely, keeping the pre-proxy request pattern unchanged.
-async function resolveStreamTarget(taskId: string, runId: string, viaProxy: boolean): Promise<StreamTarget> {
- const djangoPath = `/api/projects/@current/tasks/${taskId}/runs/${runId}/stream/`
- if (!viaProxy) {
- return { url: djangoPath, headers: {} }
- }
- try {
- const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve('@current', taskId, runId)
- if (!stream_base_url) {
- return { url: djangoPath, headers: {} }
- }
- // The proxy exposes a clean run-scoped path; the run-scoped token carries team and task.
- return {
- url: `${stream_base_url.replace(/\/+$/, '')}/v1/runs/${runId}/stream`,
- headers: { Authorization: `Bearer ${token}` },
- }
- } catch {
- return { url: djangoPath, headers: {} }
- }
-}
-
export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
path(['products', 'tasks', 'taskDetailSceneLogic']),
props({} as TaskDetailSceneLogicProps),
key((props) => props.taskId),
connect((props: TaskDetailSceneLogicProps) => ({
- values: [
- taskLogic(props),
- ['task', 'taskLoading'],
- teamLogic,
- ['currentProjectId'],
- featureFlagLogic,
- ['featureFlags'],
- preflightLogic,
- ['preflight'],
- ],
+ values: [taskLogic(props), ['task', 'taskLoading']],
actions: [
taskLogic(props),
['loadTask', 'loadTaskSuccess', 'runTask', 'runTaskSuccess', 'deleteTask', 'updateTask'],
@@ -141,16 +31,6 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
setSelectedRunId: (runId: TaskRun['id'] | null, taskId: string) => ({ runId, taskId }),
selectLatestRun: true,
clearShouldSelectLatestRun: true,
- startPolling: true,
- stopPolling: true,
- startStreaming: true,
- stopStreaming: true,
- markStreamingFailed: true,
- markStreamComplete: true,
- appendStreamEntries: (entries: LogEntry[]) => ({ entries }),
- updateStreamEntries: (entries: LogEntry[]) => ({ entries }),
- recordStreamProgress: (lastEventId: string | null, seenEventIds: string[]) => ({ lastEventId, seenEventIds }),
- setLogs: (logs: string) => ({ logs }),
updateRun: (run: TaskRun) => ({ run }),
}),
@@ -168,21 +48,6 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
clearShouldSelectLatestRun: () => false,
},
],
- logs: [
- '' as string,
- {
- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? '' : state),
- setLogs: (_, { logs }) => logs,
- },
- ],
- isInitialLogsLoad: [
- true as boolean,
- {
- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? true : state),
- setLogs: () => false,
- appendStreamEntries: () => false,
- },
- ],
runs: [
[] as TaskRun[],
{
@@ -190,90 +55,9 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
state.map((r) => (r.id === run.id ? run : r)),
},
],
- streamEntries: [
- [] as LogEntry[],
- {
- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? [] : state),
- appendStreamEntries: (state, { entries }) => {
- if (entries.length === 0) {
- return state
- }
- const last = state[state.length - 1]
- const first = entries[0]
- if (last?.type === first.type && (first.type === 'agent' || first.type === 'thinking')) {
- return [
- ...state.slice(0, -1),
- { ...last, message: (last.message || '') + (first.message || '') },
- ...entries.slice(1),
- ]
- }
- return [...state, ...entries]
- },
- updateStreamEntries: (state, { entries }) => {
- if (entries.length === 0) {
- return state
- }
- const entriesById = new Map(entries.map((entry) => [entry.id, entry]))
- let changed = false
- const nextState = state.map((entry) => {
- const updatedEntry = entriesById.get(entry.id)
- if (!updatedEntry) {
- return entry
- }
- changed = true
- return updatedEntry
- })
- return changed ? nextState : state
- },
- },
- ],
- lastStreamEventId: [
- null as string | null,
- {
- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? null : state),
- recordStreamProgress: (state, { lastEventId }) => lastEventId ?? state,
- },
- ],
- seenStreamEventIds: [
- {} as Record<string, true>,
- {
- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? {} : state),
- recordStreamProgress: (state, { seenEventIds }) => {
- if (seenEventIds.length === 0) {
- return state
- }
- return {
- ...state,
- ...Object.fromEntries(seenEventIds.map((eventId) => [eventId, true])),
- }
- },
- },
- ],
- isStreaming: [
- false,
- {
- startStreaming: () => true,
- stopStreaming: () => false,
- },
- ],
- streamingFailed: [
- false,
- {
- setSelectedRunId: () => false,
- markStreamingFailed: () => true,
- },
- ],
- streamComplete: [
- false,
- {
- setSelectedRunId: () => false,
- startStreaming: () => false,
- markStreamComplete: () => true,
- },
- ],
})),
- loaders(({ props, values, actions }) => ({
+ loaders(({ props, values }) => ({
runs: [
[] as TaskRun[],
{
@@ -291,35 +75,7 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
return null
}
const run = await api.tasks.runs.get(props.taskId, values.selectedRunId, phDebugQueryParams())
- // Use proxy endpoint to avoid CORS issues with direct S3 access
- actions.loadLogs({
- url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,
- })
- return run
- },
- },
- ],
- rawLogs: [
- '' as string,
- {
- loadLogs: async ({ url }: { url: string }) => {
- try {
- const response = await fetch(url, {
- cache: 'no-store',
- headers: { 'Cache-Control': 'no-cache' },
- })
- if (response.status === 404) {
- return ''
- }
- if (!response.ok) {
- console.error('Failed to load logs:', response.status, response.statusText)
- return ''
- }
- return await response.text()
- } catch (error) {
- console.error('Failed to load logs:', error)
- return ''
- }
+ return run ?? null
},
},
],
@@ -345,42 +101,19 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
return runs.length === 0
},
],
- shouldPoll: [
- (s) => [s.selectedRun],
- (selectedRun): boolean => {
- if (!selectedRun) {
- return false
- }
- return selectedRun.status === TaskRunStatus.QUEUED || selectedRun.status === TaskRunStatus.IN_PROGRESS
- },
- ],
- streamViaProxyEnabled: [
- (s) => [s.featureFlags, s.preflight],
- (featureFlags, preflight): boolean =>
- // Gates the durable-streaming rollout (stream_token + status-unaware streams). Local
- // dev disables the analytics SDK, so DEBUG instances opt in unconditionally — the
- // server still owns the final proxy-vs-Django decision via stream_token.
- !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY] || !!preflight?.is_debug,
- ],
title: [
(s) => [s.task],
(task): string => {
return task?.title || task?.slug || 'Task'
},
],
- logsLoading: [
- (s) => [s.rawLogsLoading, s.isInitialLogsLoad],
- (rawLogsLoading, isInitialLogsLoad): boolean => rawLogsLoading && isInitialLogsLoad,
- ],
}),
- listeners(({ actions, values, props, cache }) => ({
+ listeners(({ actions, values, props }) => ({
setSelectedRunId: ({ taskId }) => {
if (taskId !== props.taskId) {
return
}
- actions.stopPolling()
- actions.stopStreaming()
actions.loadSelectedRun()
},
runTaskSuccess: ({ task }) => {
@@ -408,44 +141,6 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
actions.updateRun(selectedRunData)
}
actions.loadTask()
- if (values.streamComplete) {
- // The stream signalled end-of-run in-band; stop reopening it, but keep polling
- // until the refreshed run record catches up to a terminal status.
- actions.stopStreaming()
- const refreshedRun = selectedRunData ?? values.selectedRun
- if (
- refreshedRun?.status === TaskRunStatus.QUEUED ||
- refreshedRun?.status === TaskRunStatus.IN_PROGRESS
- ) {
- actions.startPolling()
- } else {
- actions.stopPolling()
- }
- return
- }
- if (values.streamingFailed) {
- // Reconnects were exhausted earlier; fall back to polling while the run is live,
- // and stop once it reaches a terminal status so the page doesn't poll forever.
- if (values.shouldPoll) {
- actions.startPolling()
- } else {
- actions.stopPolling()
- }
- } else if (!values.isStreaming) {
- if (values.streamViaProxyEnabled) {
- // The durable stream is status-unaware: open it regardless of the run's current
- // status and rely on the in-band stream-end sentinel to finish. Terminal runs
- // replay their buffered events plus the sentinel; live runs stream as they go.
- actions.startStreaming()
- } else if (values.shouldPoll) {
- actions.startStreaming()
- } else {
- // Rollout flag off: keep the pre-proxy behavior — terminal runs never open a
- // stream connection.
- actions.stopPolling()
- actions.stopStreaming()
- }
- }
},
loadTaskSuccess: ({ task }) => {
if (task?.id !== props.taskId) {
@@ -453,180 +148,6 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
}
tasksLogic.findMounted()?.actions.updateTask(task)
},
- loadLogsSuccess: ({ rawLogs }) => {
- if (rawLogs) {
- actions.setLogs(rawLogs)
- }
- },
- startStreaming: () => {
- // Streaming replaces polling
- actions.stopPolling()
-
- const runId = values.selectedRunId
- if (!runId) {
- return
- }
-
- cache.disposables.add(() => {
- const abortController = new AbortController()
- const toolMap = buildToolMap(values.streamEntries)
- let eventIndex = values.streamEntries.length
- let reconnectCount = 0
- let tokenRefreshes = 0
- let openedAt = 0
- let terminated = false
- let disposed = false
-
- const handleDataEvent = (message: EventSourceMessage): void => {
- if (message.id && values.seenStreamEventIds[message.id]) {
- return
- }
- let event: Record<string, unknown>
- try {
- event = JSON.parse(message.data) as Record<string, unknown>
- } catch {
- return
- }
- const entryId = message.id ? `stream-${message.id}` : `stream-${eventIndex++}`
- const entry = parseLogEvent(event, entryId, toolMap, (updatedEntry) => {
- actions.updateStreamEntries([updatedEntry])
- })
- if (entry) {
- // appendStreamEntries merges consecutive agent/thinking messages at the reducer level
- actions.appendStreamEntries([entry])
- }
- if (message.id) {
- actions.recordStreamProgress(message.id, [message.id])
- writeStreamResumeId(runId, message.id)
- }
- }
-
- const consume = async (): Promise<void> => {
- // Resolve the stream target (agent-proxy when enabled, else Django) and seed the
- // first connection from the persisted resume point; fetch-event-source manages
- // Last-Event-ID across its own reconnects after that.
- const target = await resolveStreamTarget(props.taskId, runId, values.streamViaProxyEnabled)
- const resumeId = values.lastStreamEventId ?? readStreamResumeId(runId)
- try {
- await api.stream(target.url, {
- method: 'GET',
- signal: abortController.signal,
- headers: { ...target.headers, ...(resumeId ? { 'Last-Event-ID': resumeId } : {}) },
- onOpen: () => {
- openedAt = Date.now()
- },
- onMessage: (message) => {
- if (terminated) {
- return
- }
- if (message.event === STREAM_COMPLETE_EVENT) {
- terminated = true
- clearStreamResumeId(runId)
- actions.markStreamComplete()
- abortController.abort()
- return
- }
- if (message.event === 'error') {
- terminated = true
- abortController.abort()
- return
- }
- if (message.event === 'keepalive' || !message.data) {
- return
- }
- handleDataEvent(message)
- },
- onError: (error) => {
- // fetch-event-source: returning a number reconnects after that
- // many ms; throwing stops. A 4xx (run gone / forbidden) is fatal.
- if (terminated || disposed) {
- throw error
- }
- // Only a connection that stayed healthy earns fresh budgets; this
- // runs before the 4xx check so a mid-stream token expiry on a
- // long-lived connection refreshes with a clean slate.
- if (openedAt > 0 && Date.now() - openedAt >= STREAM_MIN_HEALTHY_CONNECTION_MS) {
- reconnectCount = 0
- tokenRefreshes = 0
- }
- openedAt = 0
- const status = (error as { status?: number } | undefined)?.status
- if (typeof status === 'number' && status >= 400 && status < 500) {
- throw error
- }
- reconnectCount += 1
- if (reconnectCount > MAX_STREAM_RECONNECTS) {
- throw error
- }
- return Math.min(
- STREAM_RECONNECT_BASE_MS * 2 ** (reconnectCount - 1),
- STREAM_RECONNECT_MAX_MS
- )
- },
- onClose: () => {
- // Server closed the body without an end-of-run sentinel (e.g. a
- // backend restart). Route through onError to reconnect; a genuine
- // completion already set `terminated`.
- if (terminated || disposed) {
- return
- }
- throw new Error('stream closed before completion')
- },
- })
- } catch (error) {
- // Stream read tokens are short-lived (the proxy validates them statelessly),
- // so a reconnect on a long stream can outlive its token. On a 401 from the
- // proxy leg, re-resolve the target — minting a fresh token re-checks access
- // server-side — instead of giving up. Revoked users fail the re-resolve and
- // land on the Django path, whose 4xx stays fatal.
- const status = (error as { status?: number } | undefined)?.status
- if (
- !disposed &&
- !terminated &&
- status === 401 &&
- target.headers.Authorization &&
- tokenRefreshes < MAX_STREAM_RECONNECTS
- ) {
- tokenRefreshes += 1
- return consume()
- }
- // Aborted, fatal, or reconnects exhausted — reconciled below
- }
-
- if (disposed) {
- return
- }
- actions.stopStreaming()
- if (!values.streamComplete) {
- // Gave up only after real reconnect attempts (not the old one-error
- // latch); fall back to polling. Resets when the run changes.
- actions.markStreamingFailed()
- }
- actions.loadSelectedRun()
- }
-
- void consume()
-
- return () => {
- disposed = true
- abortController.abort()
- }
- }, 'sseStream')
- },
- stopStreaming: () => {
- cache.disposables.dispose('sseStream')
- },
- startPolling: () => {
- cache.disposables.add(() => {
- const intervalId = window.setInterval(() => {
- actions.loadSelectedRun()
- }, LOG_POLL_INTERVAL_MS)
- return () => clearInterval(intervalId)
- }, 'logPolling')
- },
- stopPolling: () => {
- cache.disposables.dispose('logPolling')
- },
})),
afterMount(({ actions }) => {
@@ -634,15 +155,8 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
actions.loadRuns()
}),
- beforeUnmount(({ actions }) => {
- actions.stopPolling()
- actions.stopStreaming()
- }),
-
propsChanged(({ actions, props }, oldProps) => {
if (props.taskId !== oldProps.taskId) {
- actions.stopPolling()
- actions.stopStreaming()
actions.loadTask()
actions.loadRuns()
}