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.

22.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'

import { urls } from 'scenes/urls'

import { openDismissReportDialog } from '../components/shell/DismissReportDialog'
import { openRemoveYourselfDialog } from '../components/shell/RemoveYourselfDialog'
import { openResolveReportDialog } from '../components/shell/ResolveReportDialog'
import { captureInboxReportAction } from '../inboxAnalytics'
import { inboxSceneLogic } from '../inboxSceneLogic'
import { inboxTaskKickoffLogic } from '../inboxTaskKickoffLogic'
import { INBOX_PRIMARY_REPORT_SECTION_KEY, InboxReportSectionKey, SignalReport, SignalReportStatus } from '../types'
import { canCreateImplementationPr, canUnassignMe, hasOpenImplementationPr } from '../utils/reportActions'
import { displayConventionalCommitTitle } from '../utils/reportPresentation'
import { reportGithubAccessLogic } from './reportGithubAccessLogic'
import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic } from './reportListLogic'

/**
 * Triage mode triages the Needs-a-PR queue, sharing that section's loaded pages, filters, and
 * scope. It walks every loaded report, not just the rows the section has expanded to show.
 */
export const TRIAGE_SECTION_KEY: InboxReportSectionKey = INBOX_PRIMARY_REPORT_SECTION_KEY

const TRIAGE_LIST_PROPS = {
    sectionKey: TRIAGE_SECTION_KEY,
    listParams: INBOX_REPORT_SECTION_LIST_PARAMS[TRIAGE_SECTION_KEY],
}

// How many reports before the end of the loaded page the next page is fetched, so stepping
// forward never lands on a "loading" gap.
const PREFETCH_THRESHOLD = 3

function clampIndex(index: number, length: number): number {
    return Math.max(0, Math.min(index, length - 1))
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxTriageLogicValues {
    createPrDisabledReason: string | null // inboxTaskKickoffLogic
    isCreatingPr: boolean // inboxTaskKickoffLogic
    hasMore: boolean // reportListLogic
    isLoaded: boolean // reportListLogic
    isScopedToMe: boolean // reportListLogic
    reports: SignalReport[] // reportListLogic
    reportsLoadFailed: boolean // reportListLogic
    reportsResponseLoading: boolean // reportListLogic
    unassigningReportIds: string[] // reportListLogic
    canCreatePr: boolean
    counter: string
    currentIndex: number
    currentReport: SignalReport | null
    currentReportUrl: string | null
    expanded: boolean
    isRestoringPosition: boolean
    isUnassigningCurrent: boolean
    nextReport: SignalReport | null
    previousReport: SignalReport | null
    requestedIndex: number
    requestedReportId: string | null
    requestedReportIndex: number
    restoreFailed: boolean
    returnUrl: string
    unassignDisabledReason: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxTriageLogicActions {
    setSelectedReportId: (
        id: string | null,
        openMethod?: import('../inboxAnalytics').InboxReportOpenMethod | undefined,
        linkSource?: null | import('../inboxAnalytics').InboxReportLinkSource | undefined
    ) => {
        id: string | null
        linkSource: null | import('../inboxAnalytics').InboxReportLinkSource
        openMethod: import('../inboxAnalytics').InboxReportOpenMethod
    } // inboxSceneLogic
    createPrFromReport: (
        report: SignalReport,
        feedback?: string | undefined
    ) => {
        feedback: string | undefined
        report: SignalReport
    } // inboxTaskKickoffLogic
    dismissReport: (
        reportId: string,
        dismissal: import('../utils/dismissalReasons').DismissalFeedback
    ) => {
        dismissal: import('../utils/dismissalReasons').DismissalFeedback
        reportId: string
    } // reportListLogic
    ensureLoaded: () => {
        value: true
    } // reportListLogic
    loadMore: () => {
        value: true
    } // reportListLogic
    loadMoreReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // reportListLogic
    loadMoreReportsSuccess: (
        reportsResponse: import('./reportListLogic').ReportListResponse,
        payload?: any
    ) => {
        payload?: any
        reportsResponse: import('./reportListLogic').ReportListResponse
    } // reportListLogic
    loadReportsSuccess: (
        reportsResponse: import('./reportListLogic').ReportListResponse,
        payload?: void | undefined
    ) => {
        payload?: void | undefined
        reportsResponse: import('./reportListLogic').ReportListResponse
    } // reportListLogic
    removeReport: (reportId: string) => {
        reportId: string
    } // reportListLogic
    resolveReport: (
        reportId: string,
        reason: import('../utils/dismissalReasons').ResolveReasonValue,
        note: string
    ) => {
        note: string
        reason: import('../utils/dismissalReasons').ResolveReasonValue
        reportId: string
    } // reportListLogic
    unassignMe: (
        reportId: string,
        surface: import('../inboxAnalytics').InboxReportActionSurface,
        reason?: import('../../generated/api.schemas').ReviewerRemovalReasonEnumApi | undefined
    ) => {
        reason: import('../../generated/api.schemas').ReviewerRemovalReasonEnumApi | undefined
        reportId: string
        surface: import('../inboxAnalytics').InboxReportActionSurface
    } // reportListLogic
    createPrForCurrent: () => {
        value: true
    }
    dismissCurrent: () => {
        value: true
    }
    focusReport: (
        reportId: string | null,
        index: number
    ) => {
        index: number
        reportId: string | null
    }
    goToReport: (
        reportId: string,
        index: number
    ) => {
        index: number
        reportId: string
    }
    navigate: (delta: number) => {
        delta: number
    }
    openCurrent: () => {
        value: true
    }
    resolveCurrent: () => {
        value: true
    }
    setExpanded: (expanded: boolean) => {
        expanded: boolean
    }
    setIndex: (index: number) => {
        index: number
    }
    toggleExpanded: () => {
        value: true
    }
    unassignCurrent: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxTriageLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        requestedReportIndex: (requestedReportId: string | null, reports: SignalReport[]) => number
        currentIndex: (requestedReportIndex: number, requestedIndex: number, reports: SignalReport[]) => number
        isRestoringPosition: (
            requestedReportIndex: number,
            requestedIndex: number,
            reports: SignalReport[],
            hasMore: boolean,
            restoreFailed: boolean
        ) => boolean
        currentReport: (reports: SignalReport[], currentIndex: number) => SignalReport | null
        previousReport: (reports: SignalReport[], currentIndex: number) => SignalReport | null
        nextReport: (reports: SignalReport[], currentIndex: number) => SignalReport | null
        counter: (reports: SignalReport[], currentIndex: number, hasMore: boolean) => string
        canCreatePr: (currentReport: SignalReport | null) => boolean
        isUnassigningCurrent: (currentReport: SignalReport | null, unassigningReportIds: string[]) => boolean
        unassignDisabledReason: (
            currentReport: SignalReport | null,
            isUnassigningCurrent: boolean,
            isScopedToMe: boolean
        ) => string | null
        returnUrl: (currentReport: SignalReport | null, currentIndex: number) => string
        currentReportUrl: (currentReport: SignalReport | null, returnUrl: string) => string | null
    }
}

export type inboxTriageLogicType = MakeLogicType<
    inboxTriageLogicValues,
    inboxTriageLogicActions,
    Record<string, any>,
    inboxTriageLogicMeta
>

/**
 * Triage mode: one report at a time from the Needs-a-decision queue, driven from the keyboard. The
 * queue is the landing view's own `reportListLogic` (same pages, filters, and reviewer scope), so
 * archiving here drops the row from the list too and the next report slides into place.
 */
export const inboxTriageLogic = kea<inboxTriageLogicType>([
    path(['scenes', 'inbox', 'logics', 'inboxTriageLogic']),

    connect(() => ({
        values: [
            reportListLogic(TRIAGE_LIST_PROPS),
            [
                'reports',
                'hasMore',
                'isLoaded',
                'reportsResponseLoading',
                'reportsLoadFailed',
                'unassigningReportIds',
                'isScopedToMe',
            ],
            inboxTaskKickoffLogic,
            ['isCreatingPr', 'createPrDisabledReason'],
        ],
        actions: [
            reportListLogic(TRIAGE_LIST_PROPS),
            [
                'ensureLoaded',
                'loadMore',
                'dismissReport',
                'resolveReport',
                'unassignMe',
                'removeReport',
                'loadReportsSuccess',
                'loadMoreReportsSuccess',
                'loadMoreReportsFailure',
            ],
            inboxTaskKickoffLogic,
            ['createPrFromReport'],
            inboxSceneLogic,
            ['setSelectedReportId'],
        ],
    })),

    actions({
        navigate: (delta: number) => ({ delta }),
        setIndex: (index: number) => ({ index }),
        // Restore a spot carried in the triage URL: the report the user was on, and where it sat.
        focusReport: (reportId: string | null, index: number) => ({ reportId, index }),
        // Move to a report by id, so the spot holds whether or not the rows above it leave the queue.
        goToReport: (reportId: string, index: number) => ({ reportId, index }),
        toggleExpanded: true,
        setExpanded: (expanded: boolean) => ({ expanded }),
        dismissCurrent: true,
        resolveCurrent: true,
        unassignCurrent: true,
        createPrForCurrent: true,
        openCurrent: true,
    }),

    reducers({
        // The index the user asked for. It can point past the end once a verdict shrinks the list,
        // so `currentIndex` clamps it against what is loaded rather than trusting it directly.
        requestedIndex: [
            0,
            {
                setIndex: (_, { index }) => index,
                focusReport: (_, { index }) => index,
                goToReport: (_, { index }) => index,
            },
        ],
        // The report the URL says the user is on. It wins over the index while it is still in the
        // queue, so rows dismissed above it don't shift the user onto a different report.
        requestedReportId: [
            null as string | null,
            {
                focusReport: (_, { reportId }) => reportId,
                goToReport: (_, { reportId }) => reportId,
                setIndex: () => null,
            },
        ],
        expanded: [
            false,
            {
                toggleExpanded: (state) => !state,
                setExpanded: (_, { expanded }) => expanded,
            },
        ],
        // A page load toward the remembered spot failed. kea loaders leave `reports`/`hasMore`
        // unchanged on failure, so `isRestoringPosition` would otherwise stay true forever and hold the
        // view on a skeleton with nothing left to load. Stop restoring (fall back to the nearest loaded
        // report); reset when a new spot is requested or a page lands so a later retry can resume.
        restoreFailed: [
            false,
            {
                focusReport: () => false,
                loadReportsSuccess: () => false,
                loadMoreReportsSuccess: () => false,
                loadMoreReportsFailure: () => true,
            },
        ],
    }),

    selectors({
        requestedReportIndex: [
            (s) => [s.requestedReportId, s.reports],
            (requestedReportId: string | null, reports: SignalReport[]): number =>
                requestedReportId ? reports.findIndex((report) => report.id === requestedReportId) : -1,
        ],
        currentIndex: [
            (s) => [s.requestedReportIndex, s.requestedIndex, s.reports],
            (requestedReportIndex: number, requestedIndex: number, reports: SignalReport[]): number =>
                requestedReportIndex >= 0 ? requestedReportIndex : clampIndex(requestedIndex, reports.length),
        ],
        // The remembered spot sits past the loaded pages while more exist: the view waits instead of
        // flashing whichever report happens to be last on the loaded page.
        isRestoringPosition: [
            (s) => [s.requestedReportIndex, s.requestedIndex, s.reports, s.hasMore, s.restoreFailed],
            (
                requestedReportIndex: number,
                requestedIndex: number,
                reports: SignalReport[],
                hasMore: boolean,
                restoreFailed: boolean
            ): boolean => requestedReportIndex < 0 && requestedIndex >= reports.length && hasMore && !restoreFailed,
        ],
        currentReport: [
            (s) => [s.reports, s.currentIndex],
            (reports: SignalReport[], currentIndex: number): SignalReport | null => reports[currentIndex] ?? null,
        ],
        previousReport: [
            (s) => [s.reports, s.currentIndex],
            (reports: SignalReport[], currentIndex: number): SignalReport | null =>
                currentIndex > 0 ? (reports[currentIndex - 1] ?? null) : null,
        ],
        nextReport: [
            (s) => [s.reports, s.currentIndex],
            (reports: SignalReport[], currentIndex: number): SignalReport | null => reports[currentIndex + 1] ?? null,
        ],
        // "3 / 12", or "3 / 12+" while more pages are still on the server.
        counter: [
            (s) => [s.reports, s.currentIndex, s.hasMore],
            (reports: SignalReport[], currentIndex: number, hasMore: boolean): string =>
                reports.length === 0 ? '0 / 0' : `${currentIndex + 1} / ${reports.length}${hasMore ? '+' : ''}`,
        ],
        canCreatePr: [
            (s) => [s.currentReport],
            (currentReport: SignalReport | null): boolean =>
                currentReport !== null && canCreateImplementationPr(currentReport),
        ],
        isUnassigningCurrent: [
            (s) => [s.currentReport, s.unassigningReportIds],
            (currentReport: SignalReport | null, unassigningReportIds: string[]): boolean =>
                currentReport !== null && unassigningReportIds.includes(currentReport.id),
        ],
        unassignDisabledReason: [
            (s) => [s.currentReport, s.isUnassigningCurrent, s.isScopedToMe],
            (currentReport: SignalReport | null, isUnassigningCurrent: boolean, isScopedToMe: boolean): string | null =>
                currentReport && !canUnassignMe(currentReport, isScopedToMe)
                    ? "You're not a reviewer on this report"
                    : isUnassigningCurrent
                      ? 'Unassigning you…'
                      : null,
        ],
        // The triage URL for the current spot; what a report opened from here returns to.
        returnUrl: [
            (s) => [s.currentReport, s.currentIndex],
            (currentReport: SignalReport | null, currentIndex: number): string =>
                currentReport
                    ? combineUrl(urls.inboxTriage(), { report: currentReport.id, at: currentIndex }).url
                    : urls.inboxTriage(),
        ],
        currentReportUrl: [
            (s) => [s.currentReport, s.returnUrl],
            (currentReport: SignalReport | null, returnUrl: string): string | null =>
                currentReport
                    ? combineUrl(urls.inboxReport('reports', currentReport.id), { back: returnUrl }).url
                    : null,
        ],
    }),

    listeners(({ actions, values }) => {
        // Keep paging until the remembered spot is loaded (or the queue runs out).
        const loadTowardRequestedSpot = (): void => {
            if (values.isRestoringPosition && !values.reportsResponseLoading) {
                actions.loadMore()
            }
        }
        // Fetch the next page before the user reaches the end of the loaded ones.
        const prefetchNearEnd = (): void => {
            if (
                values.hasMore &&
                !values.reportsResponseLoading &&
                values.currentIndex >= values.reports.length - PREFETCH_THRESHOLD
            ) {
                actions.loadMore()
            }
        }
        return {
            loadReportsSuccess: loadTowardRequestedSpot,
            loadMoreReportsSuccess: loadTowardRequestedSpot,
            navigate: ({ delta }) => {
                actions.setIndex(clampIndex(values.currentIndex + delta, values.reports.length))
                prefetchNearEnd()
            },
            dismissCurrent: () => {
                const report = values.currentReport
                if (!report) {
                    return
                }
                openDismissReportDialog({
                    reportTitle: displayConventionalCommitTitle(report.title, 'Untitled report'),
                    hasOpenPr: hasOpenImplementationPr(report),
                    hotkeys: true,
                    onConfirm: (dismissal) => {
                        // The structured reason plus the user's note, matching the list-card dismiss
                        // path so the dismiss analytics read the same from every surface.
                        captureInboxReportAction({
                            report,
                            actionType: 'dismiss',
                            surface: 'triage_mode',
                            extra: {
                                dismissal_reason: dismissal.reason,
                                ...(dismissal.note ? { dismissal_note: dismissal.note } : {}),
                                ...(dismissal.correctedRepository
                                    ? { dismissal_corrected_repository: dismissal.correctedRepository }
                                    : {}),
                            },
                        })
                        // The list logic drops the row optimistically, so the next report takes this index.
                        actions.dismissReport(report.id, dismissal)
                    },
                })
            },
            resolveCurrent: () => {
                const report = values.currentReport
                if (!report) {
                    return
                }
                openResolveReportDialog({
                    reportTitle: displayConventionalCommitTitle(report.title, 'Untitled report'),
                    isMonitoring: report.status === SignalReportStatus.MONITORING,
                    hasOpenPr: hasOpenImplementationPr(report),
                    hotkeys: true,
                    onConfirm: ({ reason, note }) => {
                        // Only the structured reason — the free-form note can carry proprietary text.
                        // `resolveReport` still persists it through the state API. Matches the bulk resolve path.
                        captureInboxReportAction({
                            report,
                            actionType: 'resolve',
                            surface: 'triage_mode',
                            extra: { dismissal_reason: reason },
                        })
                        actions.resolveReport(report.id, reason, note)
                    },
                })
            },
            unassignCurrent: () => {
                const report = values.currentReport
                if (!report || values.unassignDisabledReason) {
                    return
                }
                openRemoveYourselfDialog({
                    reportTitle: displayConventionalCommitTitle(report.title, 'Untitled report'),
                    onConfirm: (reason) => {
                        // Only a list scoped to you drops the report, and only once the request succeeds. Pin
                        // the next report by id, so triage lands on it whether or not this one leaves the queue.
                        const next = values.nextReport
                        actions.unassignMe(report.id, 'triage_mode', reason)
                        if (next) {
                            actions.goToReport(next.id, values.currentIndex + 1)
                        }
                        prefetchNearEnd()
                    },
                })
            },
            createPrForCurrent: () => {
                const report = values.currentReport
                if (!report || !values.canCreatePr || values.isCreatingPr || values.createPrDisabledReason) {
                    return
                }
                const access = reportGithubAccessLogic.findMounted({ report, surface: 'triage_mode' })
                if (access?.values.repairNeeded) {
                    access.actions.setConnectionOpen(true)
                    return
                }
                // Triage is a fast keyboard flow with no note box, so it never steers the agent.
                captureInboxReportAction({
                    report,
                    actionType: 'create_pr',
                    surface: 'triage_mode',
                    extra: { has_feedback: false },
                })
                actions.createPrFromReport(report)
            },
            openCurrent: () => {
                const report = values.currentReport
                if (report) {
                    actions.setSelectedReportId(report.id, 'triage')
                }
            },
        }
    }),

    // The URL follows the current spot (replaced, not pushed, so the browser's back button leaves
    // triage in one step). Archiving moves the spot too, once the row is gone from the list.
    actionToUrl(({ values }) => {
        const positionUrl = (): [string, Record<string, unknown>, Record<string, unknown>, { replace: boolean }] => {
            // Other params (the list scope, for one) stay; only the spot is rewritten.
            const { report: _report, at: _at, ...rest } = router.values.searchParams
            return [
                urls.inboxTriage(),
                values.currentReport ? { ...rest, report: values.currentReport.id, at: values.currentIndex } : rest,
                router.values.hashParams,
                { replace: true },
            ]
        }
        return {
            setIndex: positionUrl,
            goToReport: positionUrl,
            removeReport: positionUrl,
        }
    }),

    urlToAction(({ actions }) => ({
        [urls.inboxTriage()]: (_, searchParams) => {
            const reportId = typeof searchParams.report === 'string' ? searchParams.report : null
            const at = Number(searchParams.at)
            if (reportId !== null || Number.isFinite(at)) {
                actions.focusReport(reportId, Number.isFinite(at) ? Math.max(0, Math.floor(at)) : 0)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.ensureLoaded()
    }),
])