Files
zeekay 1b367e2b62 chore: rebase the tree onto upstream master
The tree was a debranded snapshot of upstream taken around 2026-02-20, and
upstream has moved about five months since. This replaces it with upstream
master, mechanically re-derived: bin/debrand does the rename, and the
pipeline and squashed migrations are restored from the shipped tree.

Not a merge. The previous import replaced the tree wholesale in a single
commit, so there is no shared content history to merge against. Reproducing
the rename on the new tree is what actually converges.

What survives: .hanzo/workflows, the Dockerfiles and bin/docker* entrypoints,
compose files, LLM.md, and insights/migrations. The squashed initial
migration is load-bearing — the live database records it by name, so
upstream's ~918 individual migrations cannot come back.

Nine products are dropped as unreferenced. Twenty-one more that we do not run
are kept anyway because the core app still imports them; unpicking those is a
refactor and does not belong in a rebase.

This base does not build yet, and the reasons are not in the rename:
upstream now wants Python 3.13.13 against our 3.12.12 and Django 5.2 against
our 4.2, and the dependency manifests still name upstream packages that we
republish under our own names. Those are decisions, not renames.
2026-08-01 15:44:40 -07:00

314 lines
11 KiB
TypeScript

import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { formatDate } from 'lib/utils/datetime'
import { AlertState } from '~/queries/schema/schema-general'
import type { AlertCheck, AlertType } from '../types'
export const CHART_CHECKS_LIMIT = 50
export const TABLE_CHECKS_PAGE_SIZE = 25
export interface ChecksHistoryParams {
limit: number
offset: number
}
export const DEFAULT_CHECKS_HISTORY_PARAMS: ChecksHistoryParams = {
limit: TABLE_CHECKS_PAGE_SIZE,
offset: 0,
}
export interface AlertHistoryChartPoint {
value: number
label: string
/**
* Whether the check was in a firing state at the time it ran — source of truth for historical firings.
* Use this instead of re-applying the alert's current thresholds, which may have changed since the check.
*/
firedAtTime?: boolean
}
export interface AlertLogicProps {
alertId?: AlertType['id'] | null
}
function initialChecksHistoryParams(): ChecksHistoryParams {
return {
limit: CHART_CHECKS_LIMIT,
offset: 0,
}
}
function getCheckPlotValue(check: AlertCheck, isAnomalyDetection: boolean): number | null {
if (isAnomalyDetection) {
const scores = check.anomaly_scores
const lastScore = scores?.length ? scores[scores.length - 1] : null
if (lastScore != null && !Number.isNaN(lastScore)) {
return lastScore
}
}
const v = check.calculated_value
return v != null && !Number.isNaN(v) ? v : null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicValues {
alert: AlertType | null
alertHistoryChartSeries: AlertHistoryChartPoint[]
alertHistoryChartSeriesName: 'Anomaly score' | 'Value'
alertHistoryChecksSortedDesc: AlertCheck[]
alertHistoryHasHistory: boolean
alertHistoryIsAnomalyDetection: boolean
alertHistoryTableEntryCount: number
alertHistoryTablePageCount: number
alertHistoryUsesAnomalyScores: boolean
alertHistoryView: 'chart' | 'table'
alertLoading: boolean
checksHistoryParams: ChecksHistoryParams
checksHistoryTablePage: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicActions {
alertHistoryTablePageBackward: () => {
value: true
}
alertHistoryTablePageForward: () => {
value: true
}
loadAlert: () => any
loadAlertFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAlertSuccess: (
alert: AlertType | null,
payload?: any
) => {
alert: AlertType | null
payload?: any
}
selectAlertHistoryView: (view: 'chart' | 'table') => {
view: 'chart' | 'table'
}
setAlertHistoryView: (view: 'chart' | 'table') => {
view: 'chart' | 'table'
}
setChecksHistoryParams: (
limit: number,
offset: number
) => {
limit: number
offset: number
}
setChecksHistoryTablePage: (page: number) => {
page: number
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
alertHistoryIsAnomalyDetection: (alert: AlertType | null) => boolean
alertHistoryChecksSortedDesc: (alert: AlertType | null) => AlertCheck[]
alertHistoryChartSeries: (alert: AlertType | null) => AlertHistoryChartPoint[]
alertHistoryUsesAnomalyScores: (alert: AlertType | null) => boolean
alertHistoryChartSeriesName: (alertHistoryUsesAnomalyScores: boolean) => 'Anomaly score' | 'Value'
alertHistoryHasHistory: (alert: AlertType | null) => boolean
alertHistoryTablePageCount: (alert: AlertType | null) => number
alertHistoryTableEntryCount: (alert: AlertType | null) => number
}
}
export type alertLogicType = MakeLogicType<alertLogicValues, alertLogicActions, AlertLogicProps, alertLogicMeta>
export const alertLogic = kea<alertLogicType>([
path(['lib', 'components', 'Alerts', 'alertLogic']),
props({
alertId: null,
} as AlertLogicProps),
key(({ alertId }) => alertId ?? 'new'),
actions({
setChecksHistoryParams: (limit: number, offset: number) => ({ limit, offset }),
// Low-level reducer setter — updates `alertHistoryView` only. Prefer `selectAlertHistoryView`
// from UI code so pagination + checks fetch are reset in the same flow.
setAlertHistoryView: (view: 'chart' | 'table') => ({ view }),
setChecksHistoryTablePage: (page: number) => ({ page }),
// User-facing action: switches view AND re-issues the right checks fetch for the new view.
selectAlertHistoryView: (view: 'chart' | 'table') => ({ view }),
alertHistoryTablePageForward: true,
alertHistoryTablePageBackward: true,
}),
reducers(() => ({
checksHistoryParams: [
initialChecksHistoryParams(),
{
setChecksHistoryParams: (_, { limit, offset }) => ({ limit, offset }),
},
],
alertHistoryView: [
'chart' as 'chart' | 'table',
{
setAlertHistoryView: (_, { view }) => view,
},
],
checksHistoryTablePage: [
1,
{
setChecksHistoryTablePage: (_, { page }) => page,
},
],
})),
// Loaders must run before `selectors` so `selectors.alert` exists when history selectors are built.
loaders(({ props, values }) => ({
alert: [
null as AlertType | null,
{
loadAlert: async () => {
if (!props.alertId) {
return null
}
const { limit, offset } = values.checksHistoryParams
return await api.alerts.get(props.alertId, { checksLimit: limit, checksOffset: offset })
},
},
],
})),
// Selector deps must be functions from `logic.selectors` / propSelectors — not raw state values.
selectors(() => ({
alertHistoryIsAnomalyDetection: [(s) => [s.alert], (alert: AlertType | null) => !!alert?.detector_config],
alertHistoryChecksSortedDesc: [
(s) => [s.alert],
(alert: AlertType | null): AlertCheck[] => {
const checks = alert?.checks ?? []
return [...checks].sort((a, b) => dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf())
},
],
alertHistoryChartSeries: [
(s) => [s.alert],
(alert: AlertType | null): AlertHistoryChartPoint[] => {
if (!alert) {
return []
}
const isAnomaly = !!alert.detector_config
const sortedAsc = [...(alert.checks ?? [])].sort(
(a, b) => dayjs(a.created_at).valueOf() - dayjs(b.created_at).valueOf()
)
const points: AlertHistoryChartPoint[] = []
for (const check of sortedAsc) {
const value = getCheckPlotValue(check, isAnomaly)
if (value === null) {
continue
}
points.push({
value,
label: formatDate(dayjs(check.created_at), 'MMM D, HH:mm'),
firedAtTime: check.state === AlertState.FIRING,
})
}
return points
},
],
alertHistoryUsesAnomalyScores: [
(s) => [s.alert],
(alert: AlertType | null): boolean => {
if (!alert?.detector_config) {
return false
}
const checks = alert.checks ?? []
return checks.some((c: AlertCheck) => {
const scores = c.anomaly_scores
const last = scores?.length ? scores[scores.length - 1] : null
return last != null && !Number.isNaN(last)
})
},
],
alertHistoryChartSeriesName: [
(s) => [s.alertHistoryUsesAnomalyScores],
(usesAnomalyScores: boolean) => (usesAnomalyScores ? 'Anomaly score' : 'Value'),
],
alertHistoryHasHistory: [
(s) => [s.alert],
(alert: AlertType | null): boolean => {
const total = alert?.checks_total
if (total !== undefined && total > 0) {
return true
}
return (alert?.checks?.length ?? 0) > 0
},
],
alertHistoryTablePageCount: [
(s) => [s.alert],
(alert: AlertType | null): number => {
const checksTotal = alert?.checks_total
const resolvedTotal = checksTotal ?? 0
return Math.max(1, Math.ceil(resolvedTotal / TABLE_CHECKS_PAGE_SIZE) || 1)
},
],
alertHistoryTableEntryCount: [
(s) => [s.alert],
(alert: AlertType | null): number => {
const resolvedTotal = alert?.checks_total ?? 0
const checksLen = alert?.checks?.length ?? 0
return resolvedTotal > 0 ? resolvedTotal : checksLen
},
],
})),
listeners(({ actions, values }) => ({
selectAlertHistoryView: ({ view }) => {
actions.setAlertHistoryView(view)
if (view === 'table') {
actions.setChecksHistoryTablePage(1)
actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, 0)
} else {
actions.setChecksHistoryParams(CHART_CHECKS_LIMIT, 0)
}
actions.loadAlert()
},
alertHistoryTablePageForward: () => {
const tablePage = values.checksHistoryTablePage
if (tablePage >= values.alertHistoryTablePageCount) {
return
}
const next = tablePage + 1
actions.setChecksHistoryTablePage(next)
actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, (next - 1) * TABLE_CHECKS_PAGE_SIZE)
actions.loadAlert()
},
alertHistoryTablePageBackward: () => {
const tablePage = values.checksHistoryTablePage
if (tablePage <= 1) {
return
}
const next = tablePage - 1
actions.setChecksHistoryTablePage(next)
actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, (next - 1) * TABLE_CHECKS_PAGE_SIZE)
actions.loadAlert()
},
})),
events(({ actions, props }) => ({
afterMount() {
if (props.alertId) {
actions.selectAlertHistoryView('chart')
} else {
actions.loadAlert()
}
},
})),
])