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.

17.0 KB
Raw Blame
import { BindLogic, useActions, useValues } from 'kea'
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'

import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'

import { cn } from 'lib/utils/css-classes'

import { useThreadSkin } from '../hooks/useThreadSkin'
import { isLogicRetained, RETAINED_RUN_STREAMS, retainMountedLogic } from '../logics/retainedLogics'
import { findLiveRunStreamKey, isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'
import { taskLogic } from '../logics/taskLogic'
import { OriginProduct } from '../types/taskTypes'
import { type TurnTrailer } from '../utils/turnTrailers'
import { ContextUsageChip } from './ContextUsageChip'
import { FeedbackPromptTrailer } from './FeedbackPromptTrailer'
import { PermissionInput } from './PermissionInput'
import { QuestionInput } from './QuestionInput'
import { QuillRunSurfaceInputs } from './quill/QuillRunSurfaceInputs'
import { RUN_LOG_REVEAL_CLASS, RunLogSkeleton } from './RunLogSkeleton'
import { ThreadView } from './ThreadView'
import { TurnTrailerActions } from './TurnTrailerActions'

export interface RunSurfaceProps {
    taskId: string
    /**
     * The run to bootstrap and stream. Pass `null`/`''` to mount in a **pending** state — the thread renders
     * whatever's seeded in the bound `runStreamLogic` (an optimistic first message + provisioning via
     * `startOptimisticRun`) and never bootstraps; supply the real id once created to attach it on the same
     * instance (seed-preserving fast path). Requires an explicit `streamKey` while pending, since there's no
     * run id to key on.
     */
    runId: string | null
    /** Stable logic key; defaults to `runId` (the run is the unit being viewed). Required when `runId` is pending. */
    streamKey?: string
    /** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */
    conversationId?: string
    /**
     * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe
     * choice for a static surface. `'live'` streams an in-progress run over SSE (falling back to replay once
     * terminal) and arms the `RunSurface.Composer` input slot (approvals/questions + the follow-up composer) —
     * but those affordances appear only if the consumer renders that slot. A consumer can stream live yet stay
     * read-only by setting `interaction='live'` and omitting `<RunSurface.Composer>`. The mode is folded into
     * the logic key, so a live and a read-only surface of the same run can never share state.
     */
    interaction?: 'live' | 'read-only'
}

// `RunSurface.Root` binds a `runStreamLogic` instance and bootstraps the run; the slot components
// (`RunSurface.Thread/.Composer/.ContextUsage`) read the bound logic via selectors and the
// run wiring from this context. Consumers compose the slots into a custom layout — there is no default
// layout; the prepackaged read-only embed lives in `ReadonlyRunSurfaceImpl`. State stays in the logic;
// the slots are presentational and the composer UI is supplied by the consumer as children.

interface RunSurfaceContextValue {
    /** Original run id passed to `bootstrapRun`; `null`/`''` while the surface is pending (no run yet). */
    runId: string | null
    /** Logic key the bound `runStreamLogic` and child stream consumers share. */
    streamKey: string
    taskId: string
    conversationId?: string
    interaction: 'live' | 'read-only'
    /** Run created by a Signals scout — the context-usage line is suppressed for these. */
    isScout: boolean
    floatingInputsHeight: number
    setFloatingInputsHeight: (height: number) => void
    taskRuntime?: string | null
}

const FLOATING_INPUTS_GAP = 16
const MAX_RETAINED_RUN_STREAMS = 3

const RunSurfaceContext = createContext<RunSurfaceContextValue | null>(null)

function useRunSurfaceContext(): RunSurfaceContextValue {
    const ctx = useContext(RunSurfaceContext)
    if (!ctx) {
        throw new Error('RunSurface.* slots must be rendered inside <RunSurface.Root>')
    }
    return ctx
}

export interface RunSurfaceRootProps extends RunSurfaceProps {
    /** Custom composition of `RunSurface.*` slots. */
    children: ReactNode
    retainAfterUnmount?: boolean
}

/**
 * Binds a `runStreamLogic` instance (keyed apart from any other stream of the same run), bootstraps
 * the run, and provides the run context the slots read. In `'read-only'` mode it replays the persisted
 * `logs/` snapshot once — no SSE; in `'live'` mode it streams an in-progress run. Renders the given
 * slot children — the consumer owns the layout.
 */
function RunSurfaceRoot({
    taskId,
    runId,
    streamKey,
    conversationId,
    interaction = 'read-only',
    children,
    retainAfterUnmount = false,
}: RunSurfaceRootProps): JSX.Element {
    const replayOnly = interaction !== 'live'
    // A pending surface (no run id) must supply `streamKey` to key on; `runId` is the key otherwise.
    const logicKey = streamKey ?? runId ?? ''
    const hasOptimisticClientStream = !!streamKey && streamKey !== runId
    const [floatingInputsHeight, setFloatingInputsHeight] = useState(0)
    const { hasThreadItems } = useValues(runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }))
    useEffect(() => {
        if (
            retainAfterUnmount &&
            !replayOnly &&
            runId &&
            (logicKey === runId ||
                isLogicRetained(RETAINED_RUN_STREAMS, logicKey) ||
                findLiveRunStreamKey(runId) === logicKey)
        ) {
            retainMountedLogic(
                RETAINED_RUN_STREAMS,
                logicKey,
                runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }),
                MAX_RETAINED_RUN_STREAMS
            )
        }
    }, [retainAfterUnmount, replayOnly, runId, logicKey, conversationId])

    // The runtime and scout flag live on the task (not the run), so the surface owns loading it once and
    // exposing it to the slots. The runner already has the task loaded; an embed fetches it here.
    const { task, taskLoading, taskError, taskNotFound } = useValues(taskLogic({ taskId }))
    const { loadTask } = useActions(taskLogic({ taskId }))
    useEffect(() => {
        // A pending surface (optimistic create) has no task yet, so don't fetch an empty id.
        if (taskId && !task && !taskLoading && !taskError && !taskNotFound) {
            loadTask()
        }
    }, [taskId, task, taskLoading, taskError, taskNotFound, loadTask])

    if (taskId && !task) {
        if (taskNotFound) {
            return <LemonBanner type="error">Task not found.</LemonBanner>
        }
        if (taskError) {
            return (
                <LemonBanner type="error">
                    Couldn't load this task. <LemonButton onClick={loadTask}>Try again</LemonButton>
                </LemonBanner>
            )
        }
        if (!hasThreadItems && !hasOptimisticClientStream) {
            return <RunLogSkeleton listClassName="py-4" rowClassName="px-4" />
        }
    }

    const isScout = task?.origin_product === OriginProduct.SIGNALS_SCOUT

    return (
        <BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>
            <RunSurfaceContext.Provider
                value={{
                    runId,
                    streamKey: logicKey,
                    taskId,
                    conversationId,
                    interaction,
                    isScout,
                    floatingInputsHeight,
                    setFloatingInputsHeight,
                    taskRuntime: task?.runtime,
                }}
            >
                <RunSurfaceBootstrap taskId={taskId} />
                {children}
            </RunSurfaceContext.Provider>
        </BindLogic>
    )
}

/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */
function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {
    const { runId, interaction, taskRuntime } = useRunSurfaceContext()
    const { bootstrapRun, reset } = useActions(runStreamLogic)
    // The bootstrap decision reads logic-resident state (not a per-component ref) so it survives the
    // optimistic create-thread → detail-page component swap onto the same `streamKey` instance.
    const { bootstrappedRunId, awaitingOptimisticAttach, currentProjectId } = useValues(runStreamLogic)

    useEffect(() => {
        // Pending: no run to bootstrap yet — leave the seeded optimistic thread (first message +
        // provisioning indicator) untouched until the consumer supplies the real id.
        if (!runId) {
            return
        }
        // Wait for the project to resolve before bootstrapping — firing without it races to an
        // unretryable "No current project" error; the effect re-runs once `currentProjectId` lands.
        if (currentProjectId === null) {
            return
        }
        // Already bootstrapped this run on this instance — idempotent across re-renders and across a
        // consumer swap that adopts the same seeded instance (no reset, so the seed/stream survives).
        if (bootstrappedRunId === runId) {
            return
        }
        if (awaitingOptimisticAttach) {
            // Attaching a freshly-created run to a seeded optimistic instance: skip the reset so the seed
            // survives, and take the fresh-run fast path. The live SSE echo dedups the seeded message.
            bootstrapRun({ taskId, runId, justCreatedRun: true, taskRuntime, pagedHistory: true })
            return
        }
        // Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
        // cleanly; the bound logic keys read-only instances apart from any live stream of the same run.
        // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
        // mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
        reset()
        bootstrapRun({ taskId, runId, taskRuntime, pagedHistory: true })
    }, [
        taskId,
        runId,
        interaction,
        taskRuntime,
        bootstrappedRunId,
        awaitingOptimisticAttach,
        currentProjectId,
        bootstrapRun,
        reset,
    ])

    return null
}

/** Thread slot: the streamed run thread, with the shared run-log skeleton during the first bootstrap. */
function RunSurfaceThread({
    restoreReadPosition = false,
    className,
    listClassName,
    rowClassName,
    showContextUsage = false,
}: {
    restoreReadPosition?: boolean
    className?: string
    listClassName?: string
    rowClassName?: string
    /** Composer-less live embeds keep the usage line in the thread footer; the runner shows it in its composer. */
    showContextUsage?: boolean
} = {}): JSX.Element {
    const { interaction, isScout, taskId, streamKey, runId, floatingInputsHeight } = useRunSurfaceContext()
    const skin = useThreadSkin()
    const { bootstrapLoading, logBootstrapLoading, runConnectionState, hasThreadItems } = useValues(runStreamLogic)
    // Feedback identity: always the task, matching `$ai_session_id` on other surfaces.
    const feedbackSessionId = taskId
    const collectsFeedback = interaction === 'live' && !isScout && !!feedbackSessionId
    // Memoized so the footer keeps a stable element identity across streamed frames.
    const feedbackPrompt = useMemo(
        () =>
            collectsFeedback ? (
                <FeedbackPromptTrailer sessionId={feedbackSessionId} sessionKind="task" streamKey={streamKey} />
            ) : undefined,
        [collectsFeedback, feedbackSessionId, streamKey]
    )
    // Stable identity so the memoized trailer rows don't re-render on every streamed frame.
    const feedbackRun = useMemo(() => ({ taskId, runId: runId ?? undefined }), [taskId, runId])
    const renderTurnTrailer = useCallback(
        (trailer: TurnTrailer): JSX.Element | null =>
            feedbackSessionId ? (
                <TurnTrailerActions trailer={trailer} sessionId={feedbackSessionId} run={feedbackRun} />
            ) : null,
        [feedbackSessionId, feedbackRun]
    )
    const showedSkeletonRef = useRef(false)
    const showSkeleton =
        (bootstrapLoading || (logBootstrapLoading && !runConnectionState)) && !hasThreadItems && streamKey === runId
    if (showSkeleton) {
        showedSkeletonRef.current = true
        return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />
    }
    // The runner shows context usage in its composer footer (`ContextUsageChip`); a surface with no
    // composer opts back into the thread footer line. Never for a scout run.
    // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
    // Turn feedback: only interactive, non-scout surfaces collect ratings.
    return (
        <ThreadView
            scrollRestorationKey={restoreReadPosition ? taskId : undefined}
            className={cn(className, showedSkeletonRef.current && RUN_LOG_REVEAL_CLASS)}
            listClassName={listClassName}
            endInset={floatingInputsHeight > 0 ? floatingInputsHeight + FLOATING_INPUTS_GAP : undefined}
            rowClassName={rowClassName}
            showContextUsage={showContextUsage && interaction === 'live' && !isScout}
            renderTurnTrailer={collectsFeedback ? renderTurnTrailer : undefined}
            footerExtra={feedbackPrompt}
            skin={skin}
        />
    )
}

/**
 * Input-region slot: owns prompt-vs-composer precedence and the bootstrap gate. While a permission /
 * question request is pending (and the run isn't terminal) it renders the approval prompt; otherwise it
 * renders the consumer's composer `children`. Renders nothing outside live mode, during the `null` bootstrap
 * window without an optimistic start, or when no composer children are supplied (e.g. `ReadonlyRunSurface`).
 * The composer also shows during optimistic startup so follow-ups can queue before the agent is ready.
 */
function RunSurfaceComposer({
    children,
    isStopping = false,
    loadingFallback,
}: {
    children?: ReactNode
    isStopping?: boolean
    loadingFallback?: ReactNode
}): JSX.Element | null {
    const { interaction, streamKey, floatingInputsHeight, setFloatingInputsHeight } = useRunSurfaceContext()
    const { pendingPermissionRequest, respondingToPermission, currentRunStatus, runOpening } = useValues(runStreamLogic)
    const skin = useThreadSkin()
    if (interaction !== 'live') {
        return null
    }
    const request = !isTerminalRunStatus(currentRunStatus) ? pendingPermissionRequest : null
    const showApproval = !!request && !respondingToPermission && !isStopping
    const approval =
        request &&
        (request.questions?.length ? (
            <QuestionInput
                key={`${request.sourceRunId}:${request.requestId}`}
                streamKey={streamKey}
                request={request}
                disabled={isStopping}
            />
        ) : (
            <PermissionInput
                key={`${request.sourceRunId}:${request.requestId}`}
                streamKey={streamKey}
                request={request}
                disabled={isStopping}
            />
        ))
    const composer = children && (currentRunStatus !== null || runOpening) ? children : loadingFallback

    // Both inputs keep their local state through delivery and restoration, including uncommitted draft keystrokes.
    if (skin === 'quill') {
        return (
            <QuillRunSurfaceInputs
                approval={approval}
                showApproval={showApproval}
                composer={composer}
                height={floatingInputsHeight}
                onHeightChange={setFloatingInputsHeight}
            />
        )
    }
    return (
        <>
            {approval && (
                <div hidden={!showApproval} className="border-t px-4 py-3" data-attr="run-approval">
                    <div className="mx-auto w-full max-w-180">{approval}</div>
                </div>
            )}
            {composer && (
                <div
                    hidden={showApproval}
                    data-attr="composer"
                    className="px-4 pb-[calc(1rem_+_env(safe-area-inset-bottom))]"
                >
                    <LemonDivider className="mt-0 mb-4" />
                    <div className="mx-auto w-full max-w-180">{composer}</div>
                </div>
            )}
        </>
    )
}

/**
 * Compound run surface. `RunSurface.Root` binds the stream logic, bootstraps the run, and provides context;
 * the slots (`RunSurface.Thread/.Composer/.ContextUsage`) compose into a custom layout — there is
 * no default layout. `RunSurface.Composer` owns the prompt-vs-composer precedence and takes the composer UI
 * as children; the meta slot (`.ContextUsage`) self-binds and self-hides when empty. For the
 * common no-input embed, prefer the prepackaged `ReadonlyRunSurface` (api/readableRun).
 */
export const RunSurface = Object.assign(RunSurfaceRoot, {
    Root: RunSurfaceRoot,
    Thread: RunSurfaceThread,
    Composer: RunSurfaceComposer,
    ContextUsage: ContextUsageChip,
})