: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api-error'
import { isSlackMemberTarget } from 'lib/integrations/slackChannel'
import { usersSignalAutonomyCreate, usersSignalAutonomyRetrieve } from 'products/signals/frontend/generated/api'
import type { SignalUserAutonomyConfigCreateApi } from 'products/signals/frontend/generated/api.schemas'
import type { SignalUserAutonomyConfigApi } from '../../generated/api.schemas'
import { captureInboxSettingsChanged } from '../inboxAnalytics'
import type { SignalReportPriority, SignalUserAutonomyConfigDraft } from '../types'
interface SlackNotificationUpdates {
integrationId?: number | null
channel?: string | null
directMessage?: true
minPriority?: SignalReportPriority | null
}
/** Only the keys the caller passed, so unrelated fields (e.g. autostart_priority) aren't wiped. */
function slackNotificationBody(updates: SlackNotificationUpdates): SignalUserAutonomyConfigCreateApi {
const body: SignalUserAutonomyConfigCreateApi = {}
if ('integrationId' in updates) {
body.slack_notification_integration_id = updates.integrationId ?? null
}
if ('channel' in updates) {
body.slack_notification_channel = updates.channel ?? null
}
if ('minPriority' in updates) {
body.slack_notification_min_priority = updates.minPriority ?? null
}
if (updates.directMessage) {
body.slack_notification_direct_message = true
}
return body
}
function slackTargetKind(setting: string, value: unknown): 'direct_message' | 'channel' | null | undefined {
if (setting === 'slack_notification_direct_message') {
return 'direct_message'
}
if (setting !== 'slack_notification_channel') {
return undefined
}
return typeof value === 'string' && value ? (isSlackMemberTarget(value) ? 'direct_message' : 'channel') : null
}
function captureSlackNotificationSaves(body: SignalUserAutonomyConfigCreateApi, success: boolean): void {
for (const [setting, newValue] of Object.entries(body)) {
// The target names the customer's own channel or account, so only its kind travels.
const targetKind = slackTargetKind(setting, newValue)
captureInboxSettingsChanged({
setting,
newValue: setting === 'slack_notification_channel' ? newValue !== null : newValue,
success,
scope: 'user',
...(targetKind === undefined ? {} : { targetKind }),
})
}
}
function apiErrorMessage(error: any, fallback: string): string {
if (typeof error?.detail === 'string' && error.detail) {
return error.detail
}
if (error?.data && typeof error.data === 'object') {
for (const value of Object.values(error.data)) {
if (Array.isArray(value) && typeof value[0] === 'string') {
return value[0]
}
if (typeof value === 'string') {
return value
}
}
}
if (typeof error?.message === 'string' && error.message) {
return error.message
}
return fallback
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userAutonomyLogicValues {
autonomyConfig: SignalUserAutonomyConfigDraft | null
autonomyConfigLoading: boolean
autostartPriorityUpdating: boolean
githubAssignUpdating: boolean
openPullRequestReadyUpdating: boolean
slackNotificationsSaving: boolean
slackPickersExpanded: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userAutonomyLogicActions {
autostartPrioritySettled: () => {
value: true
}
githubAssignSettled: () => {
value: true
}
loadAutonomyConfig: () => any
loadAutonomyConfigFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAutonomyConfigSuccess: (
autonomyConfig: SignalUserAutonomyConfigApi | null,
payload?: any
) => {
autonomyConfig: SignalUserAutonomyConfigApi | null
payload?: any
}
openPullRequestReadySettled: () => {
value: true
}
setAutostartPriority: (priority: SignalReportPriority | null) => {
priority: SignalReportPriority | null
}
setGithubAssignOnPullRequest: (enabled: boolean) => {
enabled: boolean
}
setOpenPullRequestReady: (ready: boolean | null) => {
ready: boolean | null
}
setSlackPickersExpanded: (expanded: boolean) => {
expanded: boolean
}
slackNotificationsSettled: () => {
value: true
}
updateSlackNotifications: (updates: SlackNotificationUpdates) => {
updates: SlackNotificationUpdates
}
}
export type userAutonomyLogicType = MakeLogicType<userAutonomyLogicValues, userAutonomyLogicActions>
/**
* Per-user Self-driving autonomy override over the `users/@me/signal_autonomy`
* endpoint. Every field here applies to reports that suggest this user as
* reviewer: the PR auto-start priority threshold, which
* overrides the team default when set and inherits it when `null` (see the backend
* `_effective_threshold`); the Slack notification destination; whether to add
* this user as a GitHub assignee on the implementation PR; and whether that PR opens
* ready for review instead of draft, which also inherits the team default when `null`.
*/
export const userAutonomyLogic = kea<userAutonomyLogicType>([
path(['scenes', 'inbox', 'logics', 'userAutonomyLogic']),
actions({
setAutostartPriority: (priority: SignalReportPriority | null) => ({ priority }),
// Fires when the threshold POST settles. Separate from the shared config reload, which a
// Slack preference save also triggers and would otherwise release the save guard early.
autostartPrioritySettled: true,
// Slack notification preferences (suggested-reviewer pings for new inbox items).
// integration + target together enable notifications; either null disables them.
// `directMessage` is the one target the client can't name: the backend resolves it.
updateSlackNotifications: (updates: SlackNotificationUpdates) => ({ updates }),
// Fires when a Slack preference POST settles, releasing the save guard on its trigger.
slackNotificationsSettled: true,
// Opt in to being added as a GitHub assignee on PRs for reports suggesting this user.
setGithubAssignOnPullRequest: (enabled: boolean) => ({ enabled }),
// Fires when the GitHub assignment POST settles, releasing the switch's save guard.
githubAssignSettled: true,
// Whether PRs for reports suggesting this user open ready for review. Null follows the
// project default rather than pinning an answer, so a project that changes its mind moves
// this user with it.
setOpenPullRequestReady: (ready: boolean | null) => ({ ready }),
// Fires when the ready-for-review POST settles, releasing that control's save guard.
openPullRequestReadySettled: true,
// Ephemeral view state: whether the workspace/channel pickers are revealed. Lets a user
// with multiple workspaces (and nothing saved yet) open the pickers to pick one.
setSlackPickersExpanded: (expanded: boolean) => ({ expanded }),
}),
loaders({
autonomyConfig: [
null as SignalUserAutonomyConfigDraft | null,
{
loadAutonomyConfig: async () => {
try {
return await usersSignalAutonomyRetrieve('@me')
} catch (error) {
// 404 = no config yet (user hasn't opted in). Treat as null.
if (error instanceof ApiError && error.status === 404) {
return null
}
throw error
}
},
},
],
}),
reducers({
// Optimistically reflect the chosen priority so the select doesn't flicker
// back to the stale value while the request is in flight.
autonomyConfig: {
setAutostartPriority: (state, { priority }) => ({
...(state ?? { autostart_priority: null }),
autostart_priority: priority,
}),
setGithubAssignOnPullRequest: (state, { enabled }) => ({
...(state ?? { autostart_priority: null }),
github_assign_on_pull_request: enabled,
}),
setOpenPullRequestReady: (state, { ready }) => ({
...(state ?? { autostart_priority: null }),
github_open_pull_request_ready: ready,
}),
updateSlackNotifications: (state, { updates }) => ({
...(state ?? { autostart_priority: null }),
...('integrationId' in updates
? { slack_notification_integration_id: updates.integrationId ?? null }
: {}),
...('channel' in updates ? { slack_notification_channel: updates.channel ?? null } : {}),
...('minPriority' in updates ? { slack_notification_min_priority: updates.minPriority ?? null } : {}),
}),
},
// The threshold update runs in a listener, so `autonomyConfigLoading` (the reload loader) only
// turns true after the POST resolves. This flag covers the POST itself so the control stays
// disabled for the whole save window and can't fire a second, racing update.
autostartPriorityUpdating: [
false,
{
setAutostartPriority: () => true,
autostartPrioritySettled: () => false,
},
],
// Same guard as `autostartPriorityUpdating`: the switch stays disabled for the whole save
// window, so it cannot fire a second, racing update.
githubAssignUpdating: [
false,
{
setGithubAssignOnPullRequest: () => true,
githubAssignSettled: () => false,
},
],
// Same guard again: the control stays disabled for the whole save window.
openPullRequestReadyUpdating: [
false,
{
setOpenPullRequestReady: () => true,
openPullRequestReadySettled: () => false,
},
],
// Covers the POST itself, which `autonomyConfigLoading` only reflects once it resolves.
slackNotificationsSaving: [
false,
{
updateSlackNotifications: () => true,
slackNotificationsSettled: () => false,
},
],
slackPickersExpanded: [
false,
{
setSlackPickersExpanded: (_, { expanded }) => expanded,
},
],
}),
listeners(({ actions }) => ({
setAutostartPriority: async ({ priority }) => {
let success = true
try {
await usersSignalAutonomyCreate('@me', { autostart_priority: priority })
} catch (error: any) {
success = false
lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update auto-start threshold')
} finally {
actions.autostartPrioritySettled()
captureInboxSettingsChanged({
setting: 'autostart_priority',
newValue: priority,
success,
scope: 'user',
})
actions.loadAutonomyConfig()
}
},
setGithubAssignOnPullRequest: async ({ enabled }) => {
let success = true
try {
await usersSignalAutonomyCreate('@me', { github_assign_on_pull_request: enabled })
} catch (error: any) {
success = false
lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update GitHub assignment setting')
} finally {
actions.githubAssignSettled()
captureInboxSettingsChanged({
setting: 'github_assign_on_pull_request',
newValue: enabled,
success,
scope: 'user',
})
actions.loadAutonomyConfig()
}
},
setOpenPullRequestReady: async ({ ready }) => {
let success = true
try {
await usersSignalAutonomyCreate('@me', { github_open_pull_request_ready: ready })
} catch (error: any) {
success = false
lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update pull request state setting')
} finally {
actions.openPullRequestReadySettled()
captureInboxSettingsChanged({
setting: 'github_open_pull_request_ready',
newValue: ready,
success,
scope: 'user',
})
actions.loadAutonomyConfig()
}
},
updateSlackNotifications: async ({ updates }) => {
const body = slackNotificationBody(updates)
let success = true
try {
const config = await usersSignalAutonomyCreate('@me', body)
actions.loadAutonomyConfigSuccess(config)
} catch (error: any) {
success = false
lemonToast.error(apiErrorMessage(error, 'Failed to update Slack notification setting'))
} finally {
actions.slackNotificationsSettled()
captureSlackNotificationSaves(body, success)
actions.loadAutonomyConfig()
}
},
})),
afterMount(({ actions }) => {
actions.loadAutonomyConfig()
}),
])