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.

23.3 KB
Raw Blame
import { MakeLogicType, actions, connect, isBreakpoint, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'

import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { getProjectIdentifierInPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'
import { navFilesTabLogic } from '~/layout/panel-layout/navbar/tabs/navFilesTabLogic'
import type { ProjectTreeRef } from '~/types'

import { NinePServer } from './ninepServer'
import { PosthogCommands } from './posthogCommands'
import { PosthogFilesystem } from './posthogFilesystem'
import { TerminalAI } from './terminalAI'
import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
import { TerminalNetplay } from './terminalNetplay'
import { TerminalRuntime } from './terminalRuntime'
import { TerminalSession } from './TerminalSession'

export interface TerminalAgent {
    write: (data: string) => void
    read: () => string
}

declare global {
    interface Window {
        posthogTerminal?: TerminalAgent
    }
}

export type TerminalStatus = 'idle' | 'loading' | 'booting' | 'ready' | 'error'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface terminalLogicValues {
    projectTreeRef: ProjectTreeRef | null // breadcrumbsLogic
    currentTeamId: number | null // teamLogic
    dockOpen: boolean // terminalDockLogic
    requestedFolder: string | null // terminalDockLogic
    terminalEnabled: boolean // terminalDockLogic
    clipboardError: string | null
    confirmation: TerminalConfirmation | null
    displayCaptured: boolean
    displayError: string | null
    displayFullscreen: boolean
    displayOpen: boolean
    error: string | null
    hasSelection: boolean
    hasStarted: boolean
    pasting: boolean
    runRequested: boolean
    saveError: string | null
    status: TerminalStatus
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface terminalLogicActions {
    focusTerminal: () => {
        value: true
    } // terminalDockLogic
    setRequestedFolder: (folder: string | null) => {
        folder: string | null
    } // terminalDockLogic
    answerConfirmation: (
        confirmation: TerminalConfirmation,
        approved: boolean
    ) => {
        approved: boolean
        confirmation: TerminalConfirmation
    }
    attach: (container: HTMLElement) => {
        container: HTMLElement
    }
    attachDisplay: (container: HTMLElement) => {
        container: HTMLElement
    }
    closeDisplay: () => {
        value: true
    }
    copy: () => {
        value: true
    }
    detach: (container: HTMLElement) => {
        container: HTMLElement
    }
    detachDisplay: () => {
        value: true
    }
    displayButtons: (buttons: number) => {
        buttons: number
    }
    displayKey: (
        code: string,
        down: boolean
    ) => {
        code: string
        down: boolean
    }
    displayMouse: (
        x: number,
        y: number
    ) => {
        x: number
        y: number
    }
    focus: () => {
        value: true
    }
    followFolder: () => {
        value: true
    }
    insertCommand: (command: string) => {
        command: string
    }
    openUrl: (url: string) => {
        url: string
    }
    paste: () => {
        value: true
    }
    releaseDisplayInput: () => {
        value: true
    }
    setClipboardError: (error: string | null) => {
        error: string | null
    }
    setConfirmation: (confirmation: TerminalConfirmation | null) => {
        confirmation: TerminalConfirmation | null
    }
    setDisplayCaptured: (captured: boolean) => {
        captured: boolean
    }
    setDisplayError: (error: string | null) => {
        error: string | null
    }
    setDisplayFullscreen: (fullscreen: boolean) => {
        fullscreen: boolean
    }
    setDisplayOpen: (open: boolean) => {
        open: boolean
    }
    setError: (error: string | null) => {
        error: string | null
    }
    setHasSelection: (selected: boolean) => {
        selected: boolean
    }
    setPasting: (pasting: boolean) => {
        pasting: boolean
    }
    setSaveError: (error: string | null) => {
        error: string | null
    }
    setStatus: (status: TerminalStatus) => {
        status: TerminalStatus
    }
    start: () => {
        value: true
    }
    stop: () => {
        value: true
    }
}

export type terminalLogicType = MakeLogicType<terminalLogicValues, terminalLogicActions>

export const terminalLogic = kea<terminalLogicType>([
    path(['scenes', 'terminal', 'terminalLogic']),
    connect({
        values: [
            breadcrumbsLogic,
            ['projectTreeRef'],
            teamLogic,
            ['currentTeamId'],
            terminalDockLogic,
            ['terminalEnabled', 'dockOpen', 'requestedFolder'],
        ],
        actions: [terminalDockLogic, ['focusTerminal', 'setRequestedFolder']],
    }),
    actions({
        openUrl: (url: string) => ({ url }),
        setConfirmation: (confirmation: TerminalConfirmation | null) => ({ confirmation }),
        answerConfirmation: (confirmation: TerminalConfirmation, approved: boolean) => ({ confirmation, approved }),
        setDisplayFullscreen: (fullscreen: boolean) => ({ fullscreen }),
        setDisplayCaptured: (captured: boolean) => ({ captured }),
        setDisplayError: (error: string | null) => ({ error }),
        setDisplayOpen: (open: boolean) => ({ open }),
        closeDisplay: true,
        attachDisplay: (container: HTMLElement) => ({ container }),
        detachDisplay: true,
        displayKey: (code: string, down: boolean) => ({ code, down }),
        displayButtons: (buttons: number) => ({ buttons }),
        displayMouse: (x: number, y: number) => ({ x, y }),
        releaseDisplayInput: true,
        start: true,
        followFolder: true,
        attach: (container: HTMLElement) => ({ container }),
        detach: (container: HTMLElement) => ({ container }),
        focus: true,
        insertCommand: (command: string) => ({ command }),
        copy: true,
        paste: true,
        setHasSelection: (selected: boolean) => ({ selected }),
        setClipboardError: (error: string | null) => ({ error }),
        setPasting: (pasting: boolean) => ({ pasting }),
        stop: true,
        setStatus: (status: TerminalStatus) => ({ status }),
        setError: (error: string | null) => ({ error }),
        setSaveError: (error: string | null) => ({ error }),
    }),
    reducers({
        confirmation: [
            null as TerminalConfirmation | null,
            { setConfirmation: (_, { confirmation }) => confirmation, stop: () => null },
        ],
        displayFullscreen: [
            false,
            {
                setDisplayFullscreen: (_, { fullscreen }) => fullscreen,
                detachDisplay: () => false,
                closeDisplay: () => false,
                stop: () => false,
            },
        ],
        displayCaptured: [
            false,
            {
                setDisplayCaptured: (_, { captured }) => captured,
                detachDisplay: () => false,
                closeDisplay: () => false,
                stop: () => false,
            },
        ],
        displayError: [
            null as string | null,
            {
                setDisplayError: (_, { error }) => error,
                attachDisplay: () => null,
                closeDisplay: () => null,
                stop: () => null,
            },
        ],
        displayOpen: [
            false,
            {
                setDisplayOpen: (_, { open }) => open,
                closeDisplay: () => false,
                stop: () => false,
                setStatus: (state, { status }) => (status === 'error' ? false : state),
            },
        ],
        hasStarted: [false, { start: () => true }],
        runRequested: [false, { start: () => true, stop: () => false }],
        hasSelection: [false, { setHasSelection: (_, { selected }) => selected }],
        pasting: [false, { setPasting: (_, { pasting }) => pasting }],
        clipboardError: [null as string | null, { setClipboardError: (_, { error }) => error }],
        status: ['idle' as TerminalStatus, { setStatus: (_, { status }) => status, stop: () => 'idle' }],
        // Stop destroys the session, including the recovery copies a save error points at.
        error: [null as string | null, { setError: (_, { error }) => error, start: () => null, stop: () => null }],
        saveError: [
            null as string | null,
            { setSaveError: (_, { error }) => error, start: () => null, stop: () => null },
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        openUrl: ({ url }) => {
            const target = new URL(url, window.location.origin)
            const targetProjectId = getProjectIdentifierInPath(target.pathname)
            if (
                target.origin === window.location.origin &&
                (targetProjectId === null || targetProjectId === String(values.currentTeamId)) &&
                removeProjectIdIfPresent(target.pathname) === urls.projectFiles()
            ) {
                cache.disposables.add(() => navFilesTabLogic.mount(), 'files-navigation')
                navFilesTabLogic.actions.openFolder(target.searchParams.get('folder') ?? '')
            } else {
                router.actions.push(url)
            }
        },
        followFolder: async (_, breakpoint) => {
            const runtime: TerminalRuntime | undefined = cache.runtime
            const filesystem: PosthogFilesystem | undefined = cache.filesystem
            if (!values.terminalEnabled || values.status !== 'ready' || !runtime || !filesystem) {
                return
            }
            const requested = values.requestedFolder
            try {
                const folder =
                    requested !== null
                        ? filesystem.folderPath(requested)
                        : await filesystem.folderFor(values.projectTreeRef)
                breakpoint()
                if (folder && cache.runtime === runtime) {
                    if (!runtime.changeDirectory(folder) && requested !== null) {
                        lemonToast.info('The terminal is busy. Finish the command or clear the prompt, then try again.')
                    }
                }
            } catch (error) {
                if (error instanceof Error && isBreakpoint(error)) {
                    throw error
                }
                lemonToast.error('Could not find the terminal folder. Navigate to another resource and try again.')
            } finally {
                if (values.requestedFolder === requested) {
                    actions.setRequestedFolder(null)
                }
            }
        },
        [terminalDockLogic.actionTypes.setDockOpen]: ({ open }) => {
            if (open) {
                actions.followFolder()
            }
        },
        setRequestedFolder: ({ folder }) => {
            if (folder !== null) {
                actions.followFolder()
            }
        },
        answerConfirmation: ({ confirmation, approved }) => {
            if (values.confirmation === confirmation) {
                cache.answerConfirmation?.(approved)
            }
        },
        attachDisplay: ({ container }) => cache.runtime?.attachDisplay(container),
        detachDisplay: () => cache.runtime?.detachDisplay(),
        displayKey: ({ code, down }) => {
            if (values.displayOpen) {
                cache.runtime?.displayInput.key(code, down)
            }
        },
        displayButtons: ({ buttons }) => {
            if (values.displayOpen) {
                cache.runtime?.displayInput.buttons(buttons)
            }
        },
        displayMouse: ({ x, y }) => {
            if (values.displayOpen) {
                cache.runtime?.moveMouse(x, y)
            }
        },
        releaseDisplayInput: () => cache.runtime?.displayInput.release(),
        closeDisplay: () => {
            cache.runtime?.displayInput.release()
            cache.runtime?.write('\x03')
            if (removeProjectIdIfPresent(router.values.location.pathname) !== '/terminal') {
                terminalDockLogic.actions.setDockOpen(true)
            }
            actions.focus()
        },
        setDisplayOpen: ({ open }) => {
            if (!open) {
                actions.releaseDisplayInput()
                actions.focus()
            }
        },
        attach: ({ container }) => {
            if (!cache.session) {
                cache.session = new TerminalSession(
                    (data) => !values.confirmation && cache.runtime?.write(data),
                    (columns, rows) => cache.runtime?.resize(columns, rows),
                    actions.setHasSelection,
                    actions.paste
                )
                cache.disposables.add(
                    () => () => {
                        cache.session.dispose()
                        cache.session = null
                    },
                    'screen',
                    { pauseOnPageHidden: false }
                )
            }
            cache.session.attach(container)
            if (!values.hasStarted) {
                actions.start()
            }
        },
        detach: ({ container }) => cache.session?.detach(container),
        focus: () => !values.confirmation && cache.session?.view.focus(),
        focusTerminal: () => actions.focus(),
        insertCommand: ({ command }) => {
            if (values.confirmation) {
                return
            }
            cache.session?.view.paste(command)
            actions.focus()
        },
        copy: () => void copyToClipboard(cache.session?.view.getSelection() ?? '', 'terminal selection'),
        paste: async () => {
            if (values.pasting || values.confirmation) {
                return
            }
            actions.setPasting(true)
            actions.setClipboardError(null)
            try {
                const text = await navigator.clipboard.readText()
                if (values.confirmation) {
                    return
                }
                cache.session?.view.paste(text)
                actions.focus()
            } catch {
                actions.setClipboardError(
                    'Could not read the clipboard. Focus the terminal and use your browser’s paste shortcut.'
                )
            } finally {
                actions.setPasting(false)
            }
        },
        [teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {
            if (cache.projectId === currentTeam?.id) {
                return
            }
            const restart = values.runRequested
            actions.stop()
            cache.filesystem = null
            cache.session?.view.clear()
            if (restart && cache.session) {
                actions.start()
            }
        },
        [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
            if (!values.terminalEnabled) {
                actions.stop()
            }
        },
        start: async () => {
            const projectId = values.currentTeamId
            if (!values.terminalEnabled || !projectId || ['loading', 'booting', 'ready'].includes(values.status)) {
                return
            }
            if (!cache.session) {
                return
            }
            cache.projectId = projectId
            const runtime = new TerminalRuntime(
                (bytes) => cache.session?.view.write(bytes),
                actions.setDisplayOpen,
                (message) => {
                    if (!controller.signal.aborted) {
                        actions.setError(message)
                        actions.setStatus('error')
                        disposables.dispose('terminal')
                    }
                }
            )
            cache.runtime = runtime
            cache.session.view.clear()
            runtime.resize(cache.session.view.cols, cache.session.view.rows)
            const controller = new AbortController()
            const disposables = cache.disposables
            disposables.add(
                () => () => {
                    controller.abort()
                    disposables.dispose('confirmation')
                    disposables.dispose('clock-sync')
                    runtime.dispose()
                    if (cache.runtime === runtime) {
                        cache.runtime = null
                        cache.filesystem = null
                    }
                    if (window.posthogTerminal?.read === agent.read) {
                        delete window.posthogTerminal
                    }
                },
                'terminal',
                { pauseOnPageHidden: false }
            )
            const agent: TerminalAgent = {
                write: (data) => !values.confirmation && runtime.write(data),
                read: () => runtime.read(),
            }
            actions.setStatus('loading')
            try {
                let confirmationQueue = Promise.resolve(false)
                const filesystem = new PosthogFilesystem(
                    String(projectId),
                    controller.signal,
                    (confirmation) => {
                        const pending = confirmationQueue.then(() => {
                            if (controller.signal.aborted) {
                                return false
                            }
                            return new Promise<boolean>((resolve) => {
                                disposables.add(
                                    () => {
                                        const blockKeyboard = (event: KeyboardEvent): void => {
                                            event.preventDefault()
                                            event.stopImmediatePropagation()
                                        }
                                        for (const type of ['keydown', 'keypress', 'keyup'] as const) {
                                            window.addEventListener(type, blockKeyboard, true)
                                        }
                                        cache.answerConfirmation = (approved: boolean): void => {
                                            resolve(approved)
                                            disposables.dispose('confirmation')
                                        }
                                        actions.setConfirmation(confirmation)
                                        return () => {
                                            resolve(false)
                                            cache.answerConfirmation = null
                                            actions.setConfirmation(null)
                                            for (const type of ['keydown', 'keypress', 'keyup'] as const) {
                                                window.removeEventListener(type, blockKeyboard, true)
                                            }
                                        }
                                    },
                                    'confirmation',
                                    { pauseOnPageHidden: false }
                                )
                            })
                        })
                        confirmationQueue = pending
                        return pending
                    },
                    true
                )
                cache.filesystem = filesystem
                new PosthogCommands(String(projectId), controller.signal, filesystem, actions.openUrl)
                new TerminalAI(filesystem, String(projectId), controller.signal)
                actions.setStatus('booting')
                const server = new NinePServer(filesystem, (error) => {
                    if (!controller.signal.aborted) {
                        actions.setSaveError(error)
                    }
                })
                const requested = values.requestedFolder
                const projectTreeRef = values.projectTreeRef
                const folder =
                    requested !== null
                        ? filesystem.folderPath(requested)
                        : await filesystem.folderFor(projectTreeRef).catch(() => null)
                if (controller.signal.aborted) {
                    return
                }
                if (values.requestedFolder === requested) {
                    actions.setRequestedFolder(null)
                }
                await runtime.start(
                    server,
                    controller.signal,
                    () => {
                        if (!controller.signal.aborted) {
                            window.posthogTerminal = agent
                            actions.setStatus('ready')
                            if (
                                values.requestedFolder !== null ||
                                (values.dockOpen &&
                                    (values.projectTreeRef?.type !== projectTreeRef?.type ||
                                        values.projectTreeRef?.ref !== projectTreeRef?.ref))
                            ) {
                                actions.followFolder()
                            }
                            disposables.add(() => {
                                runtime.syncClock()
                                const interval = setInterval(() => runtime.syncClock(), 30_000)
                                return () => clearInterval(interval)
                            }, 'clock-sync')
                        }
                    },
                    folder ?? undefined,
                    new TerminalNetplay(String(projectId), controller.signal)
                )
                if (controller.signal.aborted) {
                    return
                }
                disposables.add(
                    () => {
                        const timeout = setTimeout(() => {
                            if (!controller.signal.aborted && values.status === 'booting') {
                                actions.setError('Linux did not finish starting. Stop the terminal and try again.')
                                actions.setStatus('error')
                                disposables.dispose('terminal')
                            }
                        }, 90_000)
                        return () => clearTimeout(timeout)
                    },
                    'boot-timeout',
                    { pauseOnPageHidden: false }
                )
            } catch (error) {
                if (!controller.signal.aborted) {
                    actions.setError(
                        error instanceof Error ? error.message : 'Could not start the terminal. Try again.'
                    )
                    actions.setStatus('error')
                    disposables.dispose('terminal')
                }
            }
        },
        stop: () => {
            cache.disposables.dispose('terminal')
            cache.disposables.dispose('boot-timeout')
        },
    })),
    subscriptions(({ actions, values }) => ({
        // Each scene derives this reference from its own state, so no single navigation action covers it.
        projectTreeRef: () => {
            if (values.dockOpen) {
                actions.followFolder()
            }
        },
    })),
])