: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 {
BreakPointFunction,
MakeLogicType,
actions,
afterMount,
kea,
key,
listeners,
path,
props,
reducers,
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import {
signalsScoutNotesCreate,
signalsScoutNotesDestroy,
signalsScoutNotesList,
} from 'products/signals/frontend/generated/api'
import type { ScoutNoteApi, SignalsScoutNotesListParams } from 'products/signals/frontend/generated/api.schemas'
import { captureScoutAction } from '../inboxAnalytics'
import type { InboxPanelLoad } from '../inboxAnalytics'
import { withPanelLoadTimeout } from '../utils/panelLoadTimeout'
export interface ScoutNotesLogicProps {
/** The scout these notes steer, or '' for the fleet-wide view. */
skillName: string
}
/**
* Where a note came from, in the words a reader needs. A note someone typed is a directive; one
* derived from inbox activity is evidence about a particular report, and reads very differently —
* so the origin is shown rather than flattened into "a note".
*/
export const SCOUT_NOTE_ORIGIN_LABEL: Record<string, string> = {
human: 'Left directly',
// No "From a" prefix: these sit in a tag beside the note, where the preposition is the widest
// part of a label that already reads as a source.
report_dismissal: 'Dismissal',
report_discussion: 'Discussion',
report_feedback: 'Rating',
report_reviewer_correction: 'Reviewer change',
}
export function scoutNoteOriginLabel(origin: string): string {
return SCOUT_NOTE_ORIGIN_LABEL[origin] ?? 'From the inbox'
}
/** A note left directly is the team steering the fleet; the rest are derived from inbox activity. */
export function isDirectScoutNote(note: ScoutNoteApi): boolean {
return note.origin === 'human'
}
/** Bounded by the create serializer; mirrored here so a composer can say so before a failed request. */
export const SCOUT_NOTE_MAX_CHARS = 10000
/** Notes are written and retired through the skill, so the same editor access gates both. */
export function scoutNoteWriteDisabledReason(): string | undefined {
return getAccessControlDisabledReason(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor) ?? undefined
}
/**
* One request, newest first. Well above any real history (a scout carries a handful of notes), but
* a scout that somehow hits it shows a caption rather than a silently short list.
*/
export const NOTES_FETCH_LIMIT = 200
/**
* A save reloads the notes, so a second read can start while the first is still in flight. The
* breakpoint on both paths stops the older read answering for the newer one — including when what
* it has to say is its own timeout.
*/
export async function fetchScoutNotes(
load: InboxPanelLoad,
params: SignalsScoutNotesListParams,
breakpoint: BreakPointFunction
): Promise<ScoutNoteApi[]> {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
return []
}
const notes = await withPanelLoadTimeout(load, (options) =>
signalsScoutNotesList(String(teamId), params, options)
).catch((error: unknown) => {
breakpoint()
throw error
})
breakpoint()
return notes
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutNotesLogicValues {
activeNotes: ScoutNoteApi[]
directNotes: ScoutNoteApi[]
fleetWideNotes: ScoutNoteApi[]
lastSaveFailed: boolean
notes: ScoutNoteApi[]
notesCapped: boolean
notesLoadFailed: boolean
notesLoading: boolean
retiredNoteIds: string[]
savingNote: boolean
scoutNotes: ScoutNoteApi[]
toldCount: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutNotesLogicActions {
createNote: (content: string) => {
content: string
}
createNoteFailed: () => {
value: true
}
createNoteFinished: () => {
value: true
}
deleteNote: (noteId: string) => {
noteId: string
}
deleteNoteFailed: (noteId: string) => {
noteId: string
}
loadNotes: (_payload: void) => void
loadNotesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadNotesSuccess: (
notes: ScoutNoteApi[],
payload?: void
) => {
notes: ScoutNoteApi[]
payload?: void
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutNotesLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
activeNotes: (notes: ScoutNoteApi[], retiredNoteIds: string[]) => ScoutNoteApi[]
notesCapped: (notes: ScoutNoteApi[]) => boolean
scoutNotes: (activeNotes: ScoutNoteApi[], arg: any) => ScoutNoteApi[]
fleetWideNotes: (activeNotes: ScoutNoteApi[]) => ScoutNoteApi[]
directNotes: (activeNotes: ScoutNoteApi[]) => ScoutNoteApi[]
toldCount: (scoutNotes: ScoutNoteApi[]) => number
}
}
export type scoutNotesLogicType = MakeLogicType<
scoutNotesLogicValues,
scoutNotesLogicActions,
ScoutNotesLogicProps,
scoutNotesLogicMeta
>
/**
* The steering channel between a team and its scouts (`SignalScoutNote`): notes a person left, plus
* the ones the inbox forwards on their behalf when they dismiss, discuss, or rate a report. Every
* run reads them as prior context, so this is what tuning a scout looks like short of editing its
* skill.
*
* Keyed by skill name; the empty key is the fleet-wide view. The list endpoint returns a scout's
* own notes *plus* the general ones when given a `skill_name`, so the selectors split them back
* apart — a note addressed to every scout shouldn't read as something said about this one.
*/
export const scoutNotesLogic = kea<scoutNotesLogicType>([
path((key) => ['scenes', 'inbox', 'logics', 'scoutNotesLogic', key]),
props({} as ScoutNotesLogicProps),
key((props) => props.skillName || 'fleet'),
actions({
createNote: (content: string) => ({ content }),
createNoteFailed: true,
createNoteFinished: true,
deleteNote: (noteId: string) => ({ noteId }),
deleteNoteFailed: (noteId: string) => ({ noteId }),
}),
loaders(({ props }) => ({
notes: [
[] as ScoutNoteApi[],
{
loadNotes: async (_payload: void, breakpoint) =>
await fetchScoutNotes(
'scout_notes',
{
limit: NOTES_FETCH_LIMIT,
...(props.skillName ? { skill_name: props.skillName } : {}),
},
breakpoint
),
},
],
})),
reducers({
// Retired here, whatever the server has said since. A load that was already in flight when
// the note was retired can resolve after the delete and would otherwise resurrect the row.
retiredNoteIds: [
[] as string[],
{
deleteNote: (state, { noteId }) => [...state, noteId],
deleteNoteFailed: (state, { noteId }) => state.filter((id) => id !== noteId),
},
],
notesLoadFailed: [
false,
{
loadNotes: () => false,
loadNotesSuccess: () => false,
loadNotesFailure: () => true,
},
],
savingNote: [
false,
{
createNote: () => true,
createNoteFinished: () => false,
},
],
// Whether the most recent save failed. The composer awaits `createNote` and reads this to
// decide whether to close, since a listener cannot return a result.
lastSaveFailed: [
false,
{
createNote: () => false,
createNoteFailed: () => true,
},
],
}),
selectors({
activeNotes: [
(s) => [s.notes, s.retiredNoteIds],
(notes: ScoutNoteApi[], retiredNoteIds: string[]): ScoutNoteApi[] =>
retiredNoteIds.length ? notes.filter((note) => !retiredNoteIds.includes(note.id)) : notes,
],
notesCapped: [(s) => [s.notes], (notes: ScoutNoteApi[]): boolean => notes.length >= NOTES_FETCH_LIMIT],
// Notes addressed to this scout specifically. On the fleet view every note qualifies.
scoutNotes: [
(s) => [s.activeNotes, (_, props) => props],
(activeNotes: ScoutNoteApi[], props: ScoutNotesLogicProps): ScoutNoteApi[] =>
props.skillName ? activeNotes.filter((note) => note.skill_name === props.skillName) : activeNotes,
],
fleetWideNotes: [
(s) => [s.activeNotes],
(activeNotes: ScoutNoteApi[]): ScoutNoteApi[] => activeNotes.filter((note) => !note.skill_name),
],
directNotes: [
(s) => [s.activeNotes],
(activeNotes: ScoutNoteApi[]): ScoutNoteApi[] => activeNotes.filter(isDirectScoutNote),
],
// Only the notes addressed to this scout. Inbox activity on a report no scout wrote leaves a
// note for every scout, so counting those would give every scout the same large number.
// The Told tab and the health strip both show this count.
toldCount: [(s) => [s.scoutNotes], (scoutNotes: ScoutNoteApi[]): number => scoutNotes.length],
}),
listeners(({ actions, props }) => ({
createNote: async ({ content }) => {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
actions.createNoteFailed()
actions.createNoteFinished()
return
}
try {
await signalsScoutNotesCreate(String(teamId), {
content,
...(props.skillName ? { skill_name: props.skillName } : {}),
})
captureScoutAction({
actionType: 'leave_note',
surface: props.skillName ? 'scout_detail' : 'fleet_list',
skillName: props.skillName || null,
})
lemonToast.success(
props.skillName
? 'Your scout picks this up on its next run'
: 'Every scout picks this up on its next run'
)
actions.loadNotes()
} catch (error: any) {
lemonToast.error(error?.detail || error?.message || 'Failed to leave the note')
actions.createNoteFailed()
} finally {
actions.createNoteFinished()
}
},
deleteNote: async ({ noteId }) => {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
return
}
// Optimistic: `retiredNoteIds` hides the row at once; a failed delete un-hides it.
try {
await signalsScoutNotesDestroy(String(teamId), noteId)
captureScoutAction({
actionType: 'delete_note',
surface: props.skillName ? 'scout_detail' : 'fleet_list',
skillName: props.skillName || null,
})
} catch (error: any) {
lemonToast.error(error?.detail || error?.message || 'Failed to retire the note')
actions.deleteNoteFailed(noteId)
}
},
})),
afterMount(({ actions }) => {
actions.loadNotes()
}),
])