: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
feat(platform): add staff ui feedback widget that posts to slack (#111692)
Adam Leith940dff5b55c4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 44e395de6050..0611e4fc9aa5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4008,6 +4008,10 @@ snapshots:hash: v1.k794b7964.9d70ea02558f2ef94600839f5baec7be56ba352ce8f0e026754b79112b488f03.9Lr83f7fP3zgd0Jnmxkcl6WaLVQCV_E1yLtBDbcvfkMlayout-impersonation-reason-modal--upgrade-to-read-write--light:hash: v1.k794b7964.439dc8957d5cd87372de3bb4d9eca7fe709be1f2796cdf9a65cf5cc6ceeb662b.i4Llp0CW2-32owDxA3h2qD_fNnlB0ON6e_z9twN3iuU+ layout-internal-feedback-widget--with-open-menu--dark:+ hash: v1.k794b7964.16ee39068a77c973daf16724ce36c74f1be0bd8e68b61602b22f1874d7827164.JRpzUuVTa5o_ZeK9qmeBWV99VhYjYe79fM4ro-feV18+ layout-internal-feedback-widget--with-open-menu--light:+ hash: v1.k794b7964.2b9a643a79c1fa1bfa3871d5cc5fcd9e57bac37283c82f952c726bac5540c9cd.mMaGVxLUAD9FGQ6M7LxNWTZAqsSst51srsdlK9IZtAQlayout-nav-bar-installation-status--all-states--dark:hash: v1.k794b7964.d4cd8a0e68eb7a8934c190510512afd4f4c30fa99335f40e78f9585fb181a549.sSPU_PnpVJHx1X6u1B05Wv7C7r42QYnZpJ9AeIjY35clayout-nav-bar-installation-status--all-states--light:diff --git a/frontend/src/layout/InternalFeedback/InternalFeedbackBar.tsx b/frontend/src/layout/InternalFeedback/InternalFeedbackBar.tsxnew file mode 100644index 000000000000..692a19bf5cfd--- /dev/null+++ b/frontend/src/layout/InternalFeedback/InternalFeedbackBar.tsx@@ -0,0 +1,127 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import { IconCursorClick, IconDrag, IconMessage, IconX } from '@posthog/icons'+import { Button, Text, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill'++import { INTERNAL_FEEDBACK_IGNORE_ATTR } from './captureFeedbackScreenshot'+import { clampToViewport, internalFeedbackLogic } from './internalFeedbackLogic'++export function InternalFeedbackBar(): JSX.Element {+ const { position, isInspecting, target, justSent } = useValues(internalFeedbackLogic)+ const { setPosition, startInspecting, stopInspecting, startGeneralFeedback, clearSelection, hide } =+ useActions(internalFeedbackLogic)+ const barRef = useRef<HTMLDivElement>(null)+ const dragOffset = useRef<{ x: number; y: number } | null>(null)++ // The tooltips explain the bar while it is idle. Once a flow is open they only get in the way.+ const tooltipsDisabled = isInspecting || !!target+ const isGeneralFeedbackOpen = !!target && !target.element++ const viewport = { width: window.innerWidth, height: window.innerHeight }+ const size = barRef.current+ ? { width: barRef.current.offsetWidth, height: barRef.current.offsetHeight }+ : { width: 0, height: 0 }+ const placed = position ? clampToViewport(position, size, viewport) : null++ return (+ <div+ ref={barRef}+ data-quill+ {...{ [INTERNAL_FEEDBACK_IGNORE_ATTR]: '' }}+ // Above every other layer, including modals and tooltips, so the bar never ends up hidden.+ className={cn(+ 'fixed z-[2147483647] pointer-events-auto flex items-center gap-1 p-1 rounded-lg border border-border bg-card text-card-foreground shadow-md',+ !placed && 'bottom-4 left-1/2 -translate-x-1/2'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={placed ? { left: placed.x, top: placed.y } : undefined}+ >+ <Tooltip disabled={tooltipsDisabled}>+ <TooltipTrigger+ delay={0}+ render={+ <Button+ size="icon"+ aria-label="Drag to move the feedback bar"+ className="cursor-grab touch-none active:cursor-grabbing"+ onPointerDown={(e: React.PointerEvent<HTMLButtonElement>) => {+ if (!barRef.current) {+ return+ }+ const rect = barRef.current.getBoundingClientRect()+ dragOffset.current = { x: e.clientX - rect.left, y: e.clientY - rect.top }+ e.currentTarget.setPointerCapture(e.pointerId)+ }}+ onPointerMove={(e: React.PointerEvent<HTMLButtonElement>) => {+ if (!dragOffset.current || !barRef.current) {+ return+ }+ setPosition(+ clampToViewport(+ { x: e.clientX - dragOffset.current.x, y: e.clientY - dragOffset.current.y },+ { width: barRef.current.offsetWidth, height: barRef.current.offsetHeight },+ { width: window.innerWidth, height: window.innerHeight }+ )+ )+ }}+ onPointerUp={() => {+ dragOffset.current = null+ }}+ onPointerCancel={() => {+ dragOffset.current = null+ }}+ />+ }+ >+ <IconDrag />+ </TooltipTrigger>+ <TooltipContent>Drag to move the feedback bar</TooltipContent>+ </Tooltip>+ <Tooltip disabled={tooltipsDisabled}>+ <TooltipTrigger+ render={+ <Button+ aria-pressed={isInspecting}+ className={cn(isInspecting && 'bg-fill-selected')}+ onClick={() => (isInspecting ? stopInspecting() : startInspecting())}+ data-attr="internal-feedback-inspect"+ />+ }+ >+ <IconCursorClick />+ Inspect+ </TooltipTrigger>+ <TooltipContent>Click to pick a part of the page and send feedback about it to the devs</TooltipContent>+ </Tooltip>+ <Tooltip disabled={tooltipsDisabled}>+ <TooltipTrigger+ render={+ <Button+ aria-pressed={isGeneralFeedbackOpen}+ className={cn(isGeneralFeedbackOpen && 'bg-fill-selected')}+ onClick={() => (isGeneralFeedbackOpen ? clearSelection() : startGeneralFeedback())}+ data-attr="internal-feedback-general"+ />+ }+ >+ <IconMessage />+ General feedback+ </TooltipTrigger>+ <TooltipContent>Click to send feedback about this whole page, with a screenshot of it</TooltipContent>+ </Tooltip>+ <Tooltip disabled={tooltipsDisabled}>+ <TooltipTrigger render={<Button onClick={() => hide()} data-attr="internal-feedback-close" />}>+ <IconX />+ Close+ </TooltipTrigger>+ <TooltipContent>Click to hide this bar. It comes back when you reload the page.</TooltipContent>+ </Tooltip>+ {justSent && (+ <Text size="xs" variant="muted" render={<span />} className="pr-2" role="status">+ Sent, thanks!+ </Text>+ )}+ </div>+ )+}diff --git a/frontend/src/layout/InternalFeedback/InternalFeedbackPopover.tsx b/frontend/src/layout/InternalFeedback/InternalFeedbackPopover.tsxnew file mode 100644index 000000000000..60cf0296e343--- /dev/null+++ b/frontend/src/layout/InternalFeedback/InternalFeedbackPopover.tsx@@ -0,0 +1,113 @@+import { useActions, useValues } from 'kea'++import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Field,+ FieldError,+ FieldLabel,+ Textarea,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ cn,+} from '@posthog/quill'++import { INTERNAL_FEEDBACK_IGNORE_ATTR } from './captureFeedbackScreenshot'+import { internalFeedbackLogic } from './internalFeedbackLogic'++const POPOVER_WIDTH = 320+// Room the card needs below the element before it moves up to stay in view.+const POPOVER_HEIGHT = 300+const COMMENT_INPUT_ID = 'internal-feedback-comment'++export function InternalFeedbackPopover(): JSX.Element | null {+ const { target, selectedElementRect, comment, isSubmitting, submitError } = useValues(internalFeedbackLogic)+ const { setComment, submitFeedback, clearSelection } = useActions(internalFeedbackLogic)++ if (!target) {+ return null+ }++ // Whole-page feedback has no element to sit next to, so the card centers in the viewport.+ let position: React.CSSProperties | undefined+ if (selectedElementRect) {+ position = {+ top: Math.max(+ 8,+ Math.min(selectedElementRect.top + selectedElementRect.height + 8, window.innerHeight - POPOVER_HEIGHT)+ ),+ left: Math.min(Math.max(selectedElementRect.left, 8), window.innerWidth - POPOVER_WIDTH - 8),+ }+ }+ const canSave = !!comment.trim()++ return (+ <Card+ size="sm"+ data-quill+ {...{ [INTERNAL_FEEDBACK_IGNORE_ATTR]: '' }}+ // Same top layer as the bar, so an open modal or menu never covers the card.+ className={cn(+ 'fixed z-[2147483647] pointer-events-auto w-80 shadow-md',+ !position && 'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={position}+ >+ <CardHeader>+ <CardTitle>Send feedback to devs</CardTitle>+ {!target.element && <CardDescription>About this whole page</CardDescription>}+ </CardHeader>+ <CardContent>+ <Field>+ <FieldLabel htmlFor={COMMENT_INPUT_ID}>What should change?</FieldLabel>+ <Textarea+ id={COMMENT_INPUT_ID}+ placeholder="⌘↵ to save"+ value={comment}+ onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setComment(e.target.value)}+ onKeyDown={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && canSave && !isSubmitting) {+ e.preventDefault()+ submitFeedback()+ }+ }}+ rows={3}+ // The textarea grows with its content, so cap it to keep Save inside the viewport.+ className="max-h-48"+ autoFocus+ data-attr="internal-feedback-comment"+ />+ {submitError && <FieldError>{submitError}</FieldError>}+ </Field>+ </CardContent>+ <CardFooter className="justify-end gap-2">+ <Button variant="outline" onClick={() => clearSelection()} data-attr="internal-feedback-cancel">+ Cancel+ </Button>+ <Tooltip disabled={canSave}>+ <TooltipTrigger+ render={+ <Button+ variant="primary"+ loading={isSubmitting}+ disabled={!canSave}+ onClick={() => submitFeedback()}+ data-attr="internal-feedback-save"+ />+ }+ >+ Save+ </TooltipTrigger>+ <TooltipContent>Write some feedback first</TooltipContent>+ </Tooltip>+ </CardFooter>+ </Card>+ )+}diff --git a/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.stories.tsx b/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.stories.tsxnew file mode 100644index 000000000000..3e713252503d--- /dev/null+++ b/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.stories.tsx@@ -0,0 +1,45 @@+import { Meta, StoryObj } from '@storybook/react'++import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'++import { InternalFeedbackWidget } from './InternalFeedbackWidget'++const meta: Meta<typeof InternalFeedbackWidget> = {+ title: 'Layout/Internal Feedback Widget',+ component: InternalFeedbackWidget,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ },+}+export default meta+type Story = StoryObj<typeof InternalFeedbackWidget>++export const WithOpenMenu: Story = {+ render: () => (+ <div className="h-screen flex flex-col gap-4 p-4 bg-primary">+ <div className="h-64 overflow-y-auto border rounded p-2 space-y-2" data-attr="story-scroll-area">+ {Array.from({ length: 30 }, (_, i) => (+ <LemonButton key={i} type="secondary" data-attr={`story-row-${i}`}>+ Row {i + 1}+ </LemonButton>+ ))}+ </div>+ <LemonDropdown+ visible+ overlay={+ <div className="p-2 space-y-1">+ <LemonButton fullWidth data-attr="story-menu-item">+ Menu item in a portal+ </LemonButton>+ </div>+ }+ >+ <LemonButton type="primary" className="self-start">+ Open menu+ </LemonButton>+ </LemonDropdown>+ <InternalFeedbackWidget />+ </div>+ ),+}diff --git a/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.tsx b/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.tsxnew file mode 100644index 000000000000..c9bae0c41683--- /dev/null+++ b/frontend/src/layout/InternalFeedback/InternalFeedbackWidget.tsx@@ -0,0 +1,34 @@+import { useValues } from 'kea'+import { createPortal } from 'react-dom'++import { ElementHighlight } from '~/toolbar/product-tours/ElementHighlight'++import { INTERNAL_FEEDBACK_IGNORE_ATTR } from './captureFeedbackScreenshot'+import { InternalFeedbackBar } from './InternalFeedbackBar'+import { internalFeedbackLogic } from './internalFeedbackLogic'+import { InternalFeedbackPopover } from './InternalFeedbackPopover'++/**+ * Staff-only bar for pointing at an element and sending feedback about it to Slack.+ * It renders in a portal on <body>, next to the portals of menus and modals, so it can stay+ * above them and keep working while one of them is open.+ */+export function InternalFeedbackWidget(): JSX.Element | null {+ const { isHidden, isInspecting, hoverElementRect, selectedElementRect } = useValues(internalFeedbackLogic)++ if (isHidden) {+ return null+ }++ return createPortal(+ <>+ <div {...{ [INTERNAL_FEEDBACK_IGNORE_ATTR]: '' }} className="contents">+ {selectedElementRect && <ElementHighlight rect={selectedElementRect} isSelected />}+ {isInspecting && hoverElementRect && <ElementHighlight rect={hoverElementRect} />}+ </div>+ <InternalFeedbackPopover />+ <InternalFeedbackBar />+ </>,+ document.body+ )+}diff --git a/frontend/src/layout/InternalFeedback/captureFeedbackScreenshot.ts b/frontend/src/layout/InternalFeedback/captureFeedbackScreenshot.tsnew file mode 100644index 000000000000..a799d077371c--- /dev/null+++ b/frontend/src/layout/InternalFeedback/captureFeedbackScreenshot.ts@@ -0,0 +1,129 @@+import { captureElementSvg } from 'lib/utils/captureElementImage'++/** Marks the feedback widget's own nodes, so the screenshot leaves them out. */+export const INTERNAL_FEEDBACK_IGNORE_ATTR = 'data-internal-feedback-ignore'++const SCROLL_ATTR = 'data-internal-feedback-scroll'+const SVG_DATA_URL_PREFIX = 'data:image/svg+xml;charset=utf-8,'+// Same blue and padding as the selected state of the toolbar's ElementHighlight.+const OUTLINE_COLOR = '#1d4aff'+const OUTLINE_PADDING = 4+const OUTLINE_WIDTH = 3++export interface ViewportRect {+ top: number+ left: number+ width: number+ height: number+}++function markScrolledElements(): HTMLElement[] {+ const marked: HTMLElement[] = []+ if (window.scrollX || window.scrollY) {+ document.body.setAttribute(SCROLL_ATTR, `${window.scrollX},${window.scrollY}`)+ marked.push(document.body)+ }+ for (const element of Array.from(document.body.querySelectorAll<HTMLElement>('*'))) {+ if (element.scrollTop || element.scrollLeft) {+ element.setAttribute(SCROLL_ATTR, `${element.scrollLeft},${element.scrollTop}`)+ marked.push(element)+ }+ }+ return marked+}++function readStyle(style: string, property: string): string | null {+ const match = style.match(new RegExp(`(?:^|;)\\s*${property}:\\s*([^;]+)`))+ return match ? match[1].trim() : null+}++/**+ * html-to-image clones every scroll container at scroll position zero, so content scrolled out of+ * view would appear in the screenshot instead of what the person saw. Shift the children of each+ * marked container back by its scroll offset. Fixed and sticky children stay put, because the+ * browser already drew them relative to the viewport or the container edge.+ */+function applyScrollOffsets(svgDataUrl: string): string {+ const svg = decodeURIComponent(svgDataUrl.slice(SVG_DATA_URL_PREFIX.length))+ const doc = new DOMParser().parseFromString(svg, 'image/svg+xml')+ for (const container of Array.from(doc.querySelectorAll(`[${SCROLL_ATTR}]`))) {+ const [left, top] = (container.getAttribute(SCROLL_ATTR) ?? '0,0').split(',').map(Number)+ for (const child of Array.from(container.children)) {+ const style = child.getAttribute('style') ?? ''+ const position = readStyle(style, 'position')+ if (position === 'fixed' || position === 'sticky') {+ continue+ }+ const transform = readStyle(style, 'transform')+ const shift = `translate(${-left}px, ${-top}px)`+ child.setAttribute(+ 'style',+ `${style}; transform: ${transform && transform !== 'none' ? `${shift} ${transform}` : shift};`+ )+ }+ }+ return SVG_DATA_URL_PREFIX + encodeURIComponent(new XMLSerializer().serializeToString(doc))+}++function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const image = new Image()+ image.onload = () => resolve(image)+ image.onerror = () => reject(new Error('Could not render the page screenshot'))+ image.src = src+ })+}++/**+ * Captures what the person sees in the viewport, with the selected element outlined when there is one. The capture+ * starts at <body> rather than the app root, because menus, popovers and modals render in portals+ * outside the root.+ */+export async function captureFeedbackScreenshot(rect: ViewportRect | null): Promise<Blob> {+ const width = window.innerWidth+ const height = window.innerHeight+ const pixelRatio = Math.min(window.devicePixelRatio || 1, 2)++ const marked = markScrolledElements()+ let svgDataUrl: string+ try {+ svgDataUrl = await captureElementSvg(document.body, {+ width,+ height,+ backgroundColor: getComputedStyle(document.body).backgroundColor,+ filter: (node) => !(node instanceof HTMLElement && node.hasAttribute(INTERNAL_FEEDBACK_IGNORE_ATTR)),+ })+ } finally {+ for (const element of marked) {+ element.removeAttribute(SCROLL_ATTR)+ }+ }++ const image = await loadImage(applyScrollOffsets(svgDataUrl))+ const canvas = document.createElement('canvas')+ canvas.width = Math.round(width * pixelRatio)+ canvas.height = Math.round(height * pixelRatio)+ const context = canvas.getContext('2d')+ if (!context) {+ throw new Error('Could not get a 2D canvas context for the screenshot')+ }+ context.drawImage(image, 0, 0, canvas.width, canvas.height)+ if (rect) {+ context.strokeStyle = OUTLINE_COLOR+ context.lineWidth = OUTLINE_WIDTH * pixelRatio+ context.strokeRect(+ (rect.left - OUTLINE_PADDING) * pixelRatio,+ (rect.top - OUTLINE_PADDING) * pixelRatio,+ (rect.width + OUTLINE_PADDING * 2) * pixelRatio,+ (rect.height + OUTLINE_PADDING * 2) * pixelRatio+ )+ }++ return await new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error('Encoding the screenshot produced no data'))),+ 'image/jpeg',+ 0.85+ )+ })+}diff --git a/frontend/src/layout/InternalFeedback/internalFeedbackLogic.ts b/frontend/src/layout/InternalFeedback/internalFeedbackLogic.tsnew file mode 100644index 000000000000..5e6d2d99496b--- /dev/null+++ b/frontend/src/layout/InternalFeedback/internalFeedbackLogic.ts@@ -0,0 +1,390 @@+import { MakeLogicType, actions, events, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api'++import { ElementRect } from '~/toolbar/types'+import { elementToQuery, getRectForElement } from '~/toolbar/utils'++import { internalFeedbackCreate } from 'products/platform_features/frontend/generated/api'++import { INTERNAL_FEEDBACK_IGNORE_ATTR, captureFeedbackScreenshot } from './captureFeedbackScreenshot'++export interface WidgetPosition {+ x: number+ y: number+}++/** What the feedback is about. `element` and `identifier` are null for feedback about the whole page. */+export interface FeedbackTarget {+ element: HTMLElement | null+ identifier: string | null+ pageUrl: string+}++const DATA_ATTRIBUTES = ['data-attr']+const VIEWPORT_MARGIN = 8+// Matches the backend limit on the screenshot upload.+const MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024++/** Keeps the bar fully on screen, also after the window shrinks below a saved position. */+export function clampToViewport(+ position: WidgetPosition,+ size: { width: number; height: number },+ viewport: { width: number; height: number }+): WidgetPosition {+ return {+ x: Math.max(VIEWPORT_MARGIN, Math.min(position.x, viewport.width - size.width - VIEWPORT_MARGIN)),+ y: Math.max(VIEWPORT_MARGIN, Math.min(position.y, viewport.height - size.height - VIEWPORT_MARGIN)),+ }+}++function isWidgetElement(element: Element): boolean {+ return !!element.closest(`[${INTERNAL_FEEDBACK_IGNORE_ATTR}]`)+}++/** Clicks on an icon land on its SVG parts, which are not HTML elements, so select the nearest HTML ancestor. */+function toSelectableElement(target: EventTarget | null): HTMLElement | null {+ let element = target instanceof Element ? target : null+ while (element && !(element instanceof HTMLElement)) {+ element = element.parentElement+ }+ return element && !isWidgetElement(element) ? element : null+}++function describeTarget(element: HTMLElement | null): FeedbackTarget {+ return {+ element,+ identifier: element ? elementToQuery(element, DATA_ATTRIBUTES) || element.tagName.toLowerCase() : null,+ // Read at select time: on an SPA the URL can change before the person saves.+ pageUrl: window.location.href,+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface internalFeedbackLogicValues {+ comment: string+ hoverElement: HTMLElement | null+ hoverElementRect: ElementRect | null+ isHidden: boolean+ isInspecting: boolean+ isSubmitting: boolean+ justSent: boolean+ position: WidgetPosition | null+ rectUpdateCounter: number+ selectedElementRect: ElementRect | null+ submitError: string | null+ target: FeedbackTarget | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface internalFeedbackLogicActions {+ clearJustSent: () => {+ value: true+ }+ clearSelection: () => {+ value: true+ }+ hide: () => {+ value: true+ }+ selectElement: (element: HTMLElement) => {+ target: FeedbackTarget+ }+ setComment: (comment: string) => {+ comment: string+ }+ setHoverElement: (element: HTMLElement | null) => {+ element: HTMLElement | null+ }+ setPosition: (position: WidgetPosition) => {+ position: WidgetPosition+ }+ startGeneralFeedback: () => {+ target: FeedbackTarget+ }+ startInspecting: () => {+ value: true+ }+ stopInspecting: () => {+ value: true+ }+ submitFeedback: () => {+ value: true+ }+ submitFeedbackFailure: (error: string) => {+ error: string+ }+ submitFeedbackSuccess: () => {+ value: true+ }+ updateRects: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface internalFeedbackLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ hoverElementRect: (hoverElement: HTMLElement | null, rectUpdateCounter: number) => ElementRect | null+ selectedElementRect: (target: FeedbackTarget | null, rectUpdateCounter: number) => ElementRect | null+ }+}++export type internalFeedbackLogicType = MakeLogicType<+ internalFeedbackLogicValues,+ internalFeedbackLogicActions,+ Record<string, any>,+ internalFeedbackLogicMeta+>++export const internalFeedbackLogic = kea<internalFeedbackLogicType>([+ path(['layout', 'InternalFeedback', 'internalFeedbackLogic']),++ actions({+ hide: true,+ startInspecting: true,+ stopInspecting: true,+ startGeneralFeedback: () => ({ target: describeTarget(null) }),+ setHoverElement: (element: HTMLElement | null) => ({ element }),+ selectElement: (element: HTMLElement) => ({ target: describeTarget(element) }),+ clearSelection: true,+ setComment: (comment: string) => ({ comment }),+ setPosition: (position: WidgetPosition) => ({ position }),+ updateRects: true,+ submitFeedback: true,+ submitFeedbackSuccess: true,+ submitFeedbackFailure: (error: string) => ({ error }),+ clearJustSent: true,+ }),++ reducers({+ // Not persisted: closing hides the widget until the next page load.+ isHidden: [false, { hide: () => true }],+ // pinned: localStorage key via kea path + reducer name, renaming resets every saved position+ position: [+ null as WidgetPosition | null,+ { persist: true },+ {+ setPosition: (_, { position }) => position,+ },+ ],+ isInspecting: [+ false,+ {+ startInspecting: () => true,+ stopInspecting: () => false,+ selectElement: () => false,+ startGeneralFeedback: () => false,+ hide: () => false,+ },+ ],+ hoverElement: [+ null as HTMLElement | null,+ {+ setHoverElement: (_, { element }) => element,+ stopInspecting: () => null,+ selectElement: () => null,+ startGeneralFeedback: () => null,+ hide: () => null,+ },+ ],+ target: [+ null as FeedbackTarget | null,+ {+ selectElement: (_, { target }) => target,+ startGeneralFeedback: (_, { target }) => target,+ startInspecting: () => null,+ clearSelection: () => null,+ hide: () => null,+ submitFeedbackSuccess: () => null,+ },+ ],+ comment: [+ '',+ {+ setComment: (_, { comment }) => comment,+ startInspecting: () => '',+ startGeneralFeedback: () => '',+ clearSelection: () => '',+ hide: () => '',+ submitFeedbackSuccess: () => '',+ },+ ],+ submitError: [+ null as string | null,+ {+ submitFeedbackFailure: (_, { error }) => error,+ submitFeedback: () => null,+ setComment: () => null,+ selectElement: () => null,+ startGeneralFeedback: () => null,+ clearSelection: () => null,+ hide: () => null,+ },+ ],+ justSent: [+ false,+ {+ submitFeedbackSuccess: () => true,+ clearJustSent: () => false,+ startInspecting: () => false,+ startGeneralFeedback: () => false,+ hide: () => false,+ },+ ],+ isSubmitting: [+ false,+ {+ submitFeedback: () => true,+ submitFeedbackSuccess: () => false,+ submitFeedbackFailure: () => false,+ },+ ],+ rectUpdateCounter: [+ 0,+ {+ updateRects: (state) => state + 1,+ },+ ],+ }),++ selectors({+ hoverElementRect: [+ (s) => [s.hoverElement, s.rectUpdateCounter],+ (hoverElement: HTMLElement | null): ElementRect | null =>+ hoverElement ? getRectForElement(hoverElement) : null,+ ],+ selectedElementRect: [+ (s) => [s.target, s.rectUpdateCounter],+ (target: FeedbackTarget | null): ElementRect | null =>+ target?.element ? getRectForElement(target.element) : null,+ ],+ }),++ listeners(({ actions, values, cache }) => ({+ submitFeedback: async () => {+ const { target, comment } = values+ if (!target || !comment.trim()) {+ actions.submitFeedbackFailure('Write some feedback first.')+ return+ }+ // A failed screenshot must not lose the written feedback, so send without one.+ const captured: Blob | null = await (cache.screenshotPromise ?? Promise.resolve(null)).catch(() => null)+ // The backend refuses the whole request when the screenshot is too large, so drop it instead.+ const screenshot = captured && captured.size <= MAX_SCREENSHOT_BYTES ? captured : null+ try {+ await internalFeedbackCreate({+ comment: comment.trim(),+ page_url: target.pageUrl,+ ...(target.identifier ? { element_identifier: target.identifier } : {}),+ // A bare Blob uploads as "blob", and the backend ImageField rejects a name with no extension.+ ...(screenshot+ ? { screenshot: new File([screenshot], 'screenshot.jpg', { type: 'image/jpeg' }) }+ : {}),+ })+ } catch (e) {+ actions.submitFeedbackFailure(+ (e instanceof ApiError && e.detail) || "Couldn't send your feedback. Try again in a moment."+ )+ return+ }+ posthog.capture('internal feedback submitted', {+ has_screenshot: !!screenshot,+ is_whole_page: !target.element,+ })+ actions.submitFeedbackSuccess()+ },+ submitFeedbackSuccess: () => {+ cache.disposables.add(() => {+ const timeout = setTimeout(() => actions.clearJustSent(), 4000)+ return () => clearTimeout(timeout)+ }, 'justSentTimeout')+ },+ startInspecting: () => {+ posthog.capture('internal feedback inspect started')+ },+ selectElement: ({ target }) => {+ // Start right away, before the comment box takes focus and an open menu has a chance to close.+ cache.screenshotPromise = captureFeedbackScreenshot(target.element?.getBoundingClientRect() ?? null)+ cache.screenshotPromise.catch((e: unknown) => posthog.captureException(e))+ },+ startGeneralFeedback: () => {+ posthog.capture('internal feedback whole page started')+ cache.screenshotPromise = captureFeedbackScreenshot(null)+ cache.screenshotPromise.catch((e: unknown) => posthog.captureException(e))+ },+ clearSelection: () => {+ cache.screenshotPromise = null+ },+ hide: () => {+ cache.screenshotPromise = null+ posthog.capture('internal feedback closed')+ },+ })),++ events(({ actions, values, cache }) => ({+ afterMount: () => {+ // While inspecting, swallow presses on the page so a click selects instead of acting, and+ // so an open menu or popover does not close before it can be selected.+ const blockWhileInspecting = (e: Event): void => {+ const target = toSelectableElement(e.target)+ if (!values.isInspecting || !target) {+ return+ }+ e.preventDefault()+ e.stopPropagation()+ if (e.type === 'click') {+ actions.selectElement(target)+ }+ }+ const onMouseOver = (e: MouseEvent): void => {+ const target = toSelectableElement(e.target)+ if (values.isInspecting && target) {+ actions.setHoverElement(target)+ }+ }+ const onViewportChange = (): void => {+ actions.updateRects()+ }+ // Enter or Space on a focused page control would activate it, so block it the same way as a press.+ const blockKeyActivationWhileInspecting = (e: KeyboardEvent): void => {+ if (values.isInspecting && (e.key === 'Enter' || e.key === ' ') && toSelectableElement(e.target)) {+ e.preventDefault()+ e.stopPropagation()+ }+ }+ const onKeyDown = (e: KeyboardEvent): void => {+ if (e.key !== 'Escape') {+ return+ }+ if (values.isInspecting) {+ actions.stopInspecting()+ } else if (values.target) {+ actions.clearSelection()+ }+ }+ cache.disposables.add(() => {+ const blockedEvents = ['pointerdown', 'mousedown', 'mouseup', 'pointerup', 'click'] as const+ for (const type of blockedEvents) {+ document.addEventListener(type, blockWhileInspecting, true)+ }+ document.addEventListener('keydown', blockKeyActivationWhileInspecting, true)+ document.addEventListener('mouseover', onMouseOver, true)+ document.addEventListener('scroll', onViewportChange, { capture: true, passive: true })+ window.addEventListener('resize', onViewportChange)+ window.addEventListener('keydown', onKeyDown)+ return () => {+ for (const type of blockedEvents) {+ document.removeEventListener(type, blockWhileInspecting, true)+ }+ document.removeEventListener('keydown', blockKeyActivationWhileInspecting, true)+ document.removeEventListener('mouseover', onMouseOver, true)+ document.removeEventListener('scroll', onViewportChange, { capture: true })+ window.removeEventListener('resize', onViewportChange)+ window.removeEventListener('keydown', onKeyDown)+ }+ }, 'documentListeners')+ },+ })),+])diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 0e77ead22fdb..09a57fc8944e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -369,6 +369,7 @@ export const FEATURE_FLAGS = {INSIGHT_DRAG_TO_ZOOM: 'insight-drag-to-zoom', // owner: @sampennington #team-product-analytics, gates x-axis drag-to-zoom on insight charts (trends today, SQL to follow)INSIGHT_EXPORT_NUDGE: 'insight-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported an insight toward a recurring subscriptionINSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,test+ INTERNAL_FEEDBACK_WIDGET: 'internal-feedback-widget', // owner: @adamleithp, gates the staff UI feedback bar that posts to SlackJEV_CHART_AUTODETECTION: 'jev-chart-autodetection', // owner: #team-data-toolsJS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-librariesLEGACY_OAUTH_RECONNECT_WARNING: 'legacy-oauth-reconnect-warning', // owner: @jabahamondes #team-web-analytics — kill-switch for the retiring-OAuth-app reconnect banner@@ -627,7 +628,7 @@ export type FeatureFlagKey = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS]// The Today rail swaps out the whole navigation, so stories that render the app opt in to it explicitly.export const STORYBOOK_FEATURE_FLAGS = Object.values(FEATURE_FLAGS).filter(- (flag) => flag !== FEATURE_FLAGS.TODAY_RAIL_NAV+ (flag) => flag !== FEATURE_FLAGS.TODAY_RAIL_NAV && flag !== FEATURE_FLAGS.INTERNAL_FEEDBACK_WIDGET)export const INSIGHT_VISUAL_ORDER = {diff --git a/frontend/src/lib/utils/captureElementImage.ts b/frontend/src/lib/utils/captureElementImage.tsindex 6bcfbc561609..6971fa2626e2 100644--- a/frontend/src/lib/utils/captureElementImage.ts+++ b/frontend/src/lib/utils/captureElementImage.ts@@ -1,4 +1,4 @@-import { toBlob } from 'html-to-image'+import { toBlob, toSvg } from 'html-to-image'/** html-to-image does not re-export its options type. */export type CaptureImageOptions = NonNullable<Parameters<typeof toBlob>[1]>@@ -40,3 +40,11 @@ export async function captureElementImage(element: HTMLElement, options?: Capturreturn blob}++/** Serializes a live DOM element to an SVG data URL, for callers that edit the clone before they rasterize it. */+export async function captureElementSvg(element: HTMLElement, options?: CaptureImageOptions): Promise<string> {+ return await toSvg(element, {+ includeStyleProperties: getStylePropertyNames(),+ ...options,+ })+}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex e1fe39cea206..66375abcc3cc 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -14,6 +14,7 @@ import { lazyWithRetry } from 'lib/utils/retryImport'import { WizardHandoffDialog } from 'scenes/onboarding/shared/wizard-sync/WizardHandoffDialog'import { WizardSyncDebugPanel } from 'scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel'import { WizardSyncFab } from 'scenes/onboarding/shared/wizard-sync/WizardSyncFab'+import { userLogic } from 'scenes/userLogic'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { GlobalModals } from '~/layout/GlobalModals'@@ -31,6 +32,12 @@ import { sceneLogic } from './sceneLogic'const TerminalDock = lazyWithRetry(() =>import('./terminal/TerminalDock').then(({ TerminalDock }) => ({ default: TerminalDock })))+// Staff-only, so everyone else skips the chunk and the toolbar selector code it pulls in.+const InternalFeedbackWidget = lazyWithRetry(() =>+ import('~/layout/InternalFeedback/InternalFeedbackWidget').then(({ InternalFeedbackWidget }) => ({+ default: InternalFeedbackWidget,+ }))+)export default function AuthenticatedShell({ children }: { children: React.ReactNode }): JSX.Element {useMountedLogic(apiStatusLogic)@@ -43,6 +50,9 @@ export default function AuthenticatedShell({ children }: { children: React.Reactconst { sceneConfig } = useValues(sceneLogic)const { featureFlags } = useValues(featureFlagLogic)const { isDarkModeOn } = useValues(themeLogic)+ const { user } = useValues(userLogic)+ const showInternalFeedback =+ !!featureFlags[FEATURE_FLAGS.INTERNAL_FEEDBACK_WIDGET] && !!user?.email?.toLowerCase().endsWith('@posthog.com')const runSyncEnabled = featureFlags[FEATURE_FLAGS.WIZARD_RUN_SYNC] === 'wizard-run'const toasts = (<ToastContainer@@ -87,6 +97,13 @@ export default function AuthenticatedShell({ children }: { children: React.Reactbut the doc dialog must be able to open from any surface. */}<WizardHandoffDialog /><WizardSyncDebugPanel />+ {showInternalFeedback && (+ <ErrorBoundary>+ <Suspense fallback={null}>+ <InternalFeedbackWidget />+ </Suspense>+ </ErrorBoundary>+ )}{featureFlags[FEATURE_FLAGS.EXPERIMENTS_DW_AA_TEST] === 'test' && (<div data-attr="experiments-dw-aa-test-variant" className="hidden" />)}diff --git a/posthog/api/internal_feedback.py b/posthog/api/internal_feedback.pynew file mode 100644index 000000000000..b063b477eec7--- /dev/null+++ b/posthog/api/internal_feedback.py@@ -0,0 +1,165 @@+from django.conf import settings++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import serializers, status, viewsets+from rest_framework.parsers import FormParser, MultiPartParser+from rest_framework.permissions import BasePermission, IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from slack_sdk.errors import SlackApiError++from posthog.auth import SessionAuthentication+from posthog.constants import POSTHOG_INTERNAL_EMAIL_SUFFIX+from posthog.egress.slack.client import SlackWebClient+from posthog.models import User+from posthog.permissions import APIScopePermission+from posthog.rate_limit import InternalFeedbackUserThrottle+from posthog.slack.formatting import escape_slack_mrkdwn++logger = structlog.get_logger(__name__)++MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024+++def is_posthog_staff_email(user: User) -> bool:+ # Only a verified address proves ownership. Older accounts carry None, and an email change can set an+ # unowned address without verification when email delivery is off, so None is refused too.+ return (+ bool(user.email)+ and user.email.lower().endswith(POSTHOG_INTERNAL_EMAIL_SUFFIX)+ and user.is_email_verified is True+ )+++class IsPostHogStaffEmail(BasePermission):+ message = "Internal feedback is only available to PostHog team members."++ def has_permission(self, request: Request, view: object) -> bool:+ return isinstance(request.user, User) and is_posthog_staff_email(request.user)+++class InternalFeedbackRequestSerializer(serializers.Serializer):+ comment = serializers.CharField(max_length=4000, help_text="What the person wants to tell the developers.")+ page_url = serializers.URLField(max_length=2000, help_text="URL of the page the feedback is about.")+ element_identifier = serializers.CharField(+ max_length=1000,+ required=False,+ allow_blank=True,+ default="",+ help_text="CSS selector of the element the person selected. Empty for feedback about the whole page.",+ )+ screenshot = serializers.ImageField(+ required=False, help_text="JPEG screenshot of the page, with the selected element outlined when there is one."+ )++ def validate_screenshot(self, value):+ if value is not None and value.size > MAX_SCREENSHOT_BYTES:+ raise serializers.ValidationError("Screenshot must be smaller than 5 MB.")+ return value+++class InternalFeedbackResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(help_text="True when the feedback reached Slack.")+++def build_feedback_message(user: User, page_url: str, element_identifier: str, comment: str) -> str:+ name = escape_slack_mrkdwn(user.get_full_name() or user.email)+ lines = [+ f"*New UI feedback from {name}* ({escape_slack_mrkdwn(user.email)})",+ f"*Page:* {escape_slack_mrkdwn(page_url)}",+ ]+ if element_identifier:+ # A backtick would end the inline code span early.+ identifier = escape_slack_mrkdwn(element_identifier).replace("`", "'")+ lines.append(f"*Element:* `{identifier}`")+ else:+ lines.append("*Element:* whole page")+ lines += ["", escape_slack_mrkdwn(comment)]+ return "\n".join(lines)+++@extend_schema(extensions={"x-product": "platform_features"})+class InternalFeedbackViewSet(viewsets.ViewSet):+ # Session-only and INTERNAL: this is a staff tool in the web app, never an API for tokens.+ scope_object = "INTERNAL"+ authentication_classes = [SessionAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission, IsPostHogStaffEmail]+ throttle_classes = [InternalFeedbackUserThrottle]+ parser_classes = [MultiPartParser, FormParser]++ @extend_schema(+ description="Send feedback about an element or page of the PostHog web app to the team's Slack channel.",+ # A raw dict, not the serializer: drf-spectacular types an ImageField as a plain string here,+ # which a generated client cannot fill with a file. Same workaround as `MediaViewSet.create`.+ request={+ "multipart/form-data": {+ "type": "object",+ "properties": {+ "comment": {+ "type": "string",+ "maxLength": 4000,+ "description": "What the person wants to tell the developers.",+ },+ "page_url": {+ "type": "string",+ "format": "uri",+ "maxLength": 2000,+ "description": "URL of the page the feedback is about.",+ },+ "element_identifier": {+ "type": "string",+ "maxLength": 1000,+ "description": "CSS selector of the element the person selected. Empty for feedback about the whole page.",+ },+ "screenshot": {+ "type": "string",+ "format": "binary",+ "description": "JPEG screenshot of the page, with the selected element outlined when there is one.",+ },+ },+ "required": ["comment", "page_url"],+ }+ },+ responses={+ 200: InternalFeedbackResponseSerializer,+ 503: OpenApiResponse(description="Slack delivery is not configured or Slack refused the message."),+ },+ )+ def create(self, request: Request) -> Response:+ serializer = InternalFeedbackRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data++ token = settings.INTERNAL_FEEDBACK_SLACK_BOT_TOKEN+ channel = settings.INTERNAL_FEEDBACK_SLACK_CHANNEL+ if not token or not channel:+ return Response(+ {"detail": "Feedback delivery is not set up on this instance."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ user = request.user+ assert isinstance(user, User)+ message = build_feedback_message(user, data["page_url"], data["element_identifier"], data["comment"])+ client = SlackWebClient(token=token, source="internal_feedback")+ try:+ screenshot = data.get("screenshot")+ if screenshot is not None:+ client.files_upload_v2(+ channel=channel,+ content=screenshot.read(),+ filename="screenshot.jpg",+ title="Screenshot",+ initial_comment=message,+ )+ else:+ client.chat_postMessage(channel=channel, text=message, unfurl_links=False)+ except SlackApiError as e:+ logger.exception("internal_feedback_slack_failed", error=e.response.get("error"))+ return Response(+ {"detail": "Slack did not accept the feedback. Try again later."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ return Response(InternalFeedbackResponseSerializer({"success": True}).data)diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pyindex 26f267392cf0..b37064c384ff 100644--- a/posthog/api/rest_router.py+++ b/posthog/api/rest_router.py@@ -47,6 +47,7 @@ from . import (instance_settings,instance_status,integration,+ internal_feedback,materialized_column_slot,object_media_preview,organization,@@ -413,6 +414,7 @@ router.register("user_facet_settings",)router.register(r"personal_api_keys", personal_api_key.PersonalAPIKeyViewSet, "personal_api_keys")+router.register(r"internal_feedback", internal_feedback.InternalFeedbackViewSet, "internal_feedback")# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clientsrouter.register(r"cli-auth", cli_auth.CLIAuthViewSet, "cli_auth")router.register(r"instance_status", instance_status.InstanceStatusViewSet, "instance_status")diff --git a/posthog/api/test/test_internal_feedback.py b/posthog/api/test/test_internal_feedback.pynew file mode 100644index 000000000000..75e20830c6aa--- /dev/null+++ b/posthog/api/test/test_internal_feedback.py@@ -0,0 +1,71 @@+from pathlib import Path++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++FIXTURE_IMAGE = Path(__file__).parent / "fixtures" / "a-small-but-valid.gif"+++@override_settings(INTERNAL_FEEDBACK_SLACK_BOT_TOKEN="xoxb-test", INTERNAL_FEEDBACK_SLACK_CHANNEL="C123")+class TestInternalFeedbackAPI(APIBaseTest):+ def _post(self, **extra: object):+ return self.client.post(+ "/api/internal_feedback/",+ {+ "comment": "Button overlaps <!channel>",+ "page_url": "https://us.posthog.com/project/1/insights",+ "element_identifier": '[data-attr="save-insight"]',+ **extra,+ },+ format="multipart",+ )++ @parameterized.expand(+ [+ ("outside_email", "[email protected]", True),+ ("unverified_posthog_email", "[email protected]", False),+ ("unknown_verification_posthog_email", "[email protected]", None),+ ]+ )+ @patch("posthog.api.internal_feedback.SlackWebClient")+ def test_rejects_non_staff(self, _name: str, email: str, verified: bool | None, mock_client: MagicMock) -> None:+ self.user.email = email+ self.user.is_email_verified = verified+ self.user.save()++ response = self._post()++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_client.assert_not_called()++ @parameterized.expand(+ [+ ("element", {}, '*Element:* `[data-attr="save-insight"]`'),+ ("whole_page", {"element_identifier": ""}, "*Element:* whole page"),+ ]+ )+ @patch("posthog.api.internal_feedback.SlackWebClient")+ def test_uploads_screenshot_with_escaped_message(+ self, _name: str, extra: dict[str, str], element_line: str, mock_client: MagicMock+ ) -> None:+ self.user.is_email_verified = True+ self.user.save()++ with FIXTURE_IMAGE.open("rb") as image:+ response = self._post(screenshot=image, **extra)++ assert response.status_code == status.HTTP_200_OK, response.json()+ kwargs = mock_client.return_value.files_upload_v2.call_args.kwargs+ assert kwargs["channel"] == "C123"+ assert kwargs["content"] == FIXTURE_IMAGE.read_bytes()+ message = kwargs["initial_comment"]+ assert self.user.email in message+ assert "https://us.posthog.com/project/1/insights" in message+ assert "<!channel>" in message+ assert "<!channel>" not in message+ assert element_line in messagediff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 68058d951dd9..9ca758c7072f 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -451,6 +451,12 @@ class CodexConnectUserThrottle(UserRateThrottle):rate = "10/hour"+# Each internal feedback post lands in a shared Slack channel, so cap it per user.+class InternalFeedbackUserThrottle(UserRateThrottle):+ scope = "internal_feedback_user"+ rate = "60/hour"++class BurstRateThrottle(PersonalApiKeyRateThrottle):# Throttle class that's applied on all endpoints (except for capture + decide)# Intended to block quick bursts of requests, per projectdiff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 8d297bbfab73..efda2dcf6ac5 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -9,6 +9,10 @@ INTEGRATION_SERVICE_URL = get_from_env("INTEGRATION_SERVICE_URL", "")# Comma-separated `new,old`, newest first. Per deployment, not fleet-wide.INTEGRATION_SERVICE_JWT_SECRET = get_from_env("INTEGRATION_SERVICE_JWT_SECRET", "")+# Bot token and channel for the staff-only UI feedback widget. Empty token disables delivery.+INTERNAL_FEEDBACK_SLACK_BOT_TOKEN = get_from_env("INTERNAL_FEEDBACK_SLACK_BOT_TOKEN", "")+INTERNAL_FEEDBACK_SLACK_CHANNEL = get_from_env("INTERNAL_FEEDBACK_SLACK_CHANNEL", "C09G8Q32R6F")+HUBSPOT_APP_CLIENT_ID = get_from_env("HUBSPOT_APP_CLIENT_ID", "")HUBSPOT_APP_CLIENT_SECRET = get_from_env("HUBSPOT_APP_CLIENT_SECRET", "")diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 9d2991b79f0b..66a235b14779 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -7,6 +7,11 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface InternalFeedbackResponseApi {+ /** True when the feedback reached Slack. */+ success: boolean+}+/*** * `1` - member* * `8` - administrator@@ -1230,6 +1235,26 @@ export interface PatchedPinnedSceneTabsApi {homepage?: PinnedSceneTabApi | null}+export type InternalFeedbackCreateBody = {+ /**+ * What the person wants to tell the developers.+ * @maxLength 4000+ */+ comment: string+ /**+ * URL of the page the feedback is about.+ * @maxLength 2000+ */+ page_url: string+ /**+ * CSS selector of the element the person selected. Empty for feedback about the whole page.+ * @maxLength 1000+ */+ element_identifier?: string+ /** JPEG screenshot of the page, with the selected element outlined when there is one. */+ screenshot?: Blob+}+export type ListParams = {/*** Number of results to return per page.diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.tsindex 8bf872243c88..6f76ea99f1b4 100644--- a/products/platform_features/frontend/generated/api.ts+++ b/products/platform_features/frontend/generated/api.ts@@ -24,6 +24,8 @@ import type {CommentSlackThreadApi,CommentsListParams,DiagnosticReportApi,+ InternalFeedbackCreateBody,+ InternalFeedbackResponseApi,ListParams,MembersListParams,OrganizationAIAccessRequestResponseApi,@@ -81,6 +83,38 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getInternalFeedbackCreateUrl = () => {+ return `/api/internal_feedback/`+}++/**+ * Send feedback about an element or page of the PostHog web app to the team's Slack channel.+ */+export const internalFeedbackCreate = async (+ internalFeedbackCreateBody?: InternalFeedbackCreateBody,+ options?: RequestInit+): Promise<InternalFeedbackResponseApi> => {+ const formData = new FormData()+ if (internalFeedbackCreateBody?.comment !== undefined) {+ formData.append(`comment`, internalFeedbackCreateBody.comment)+ }+ if (internalFeedbackCreateBody?.page_url !== undefined) {+ formData.append(`page_url`, internalFeedbackCreateBody.page_url)+ }+ if (internalFeedbackCreateBody?.element_identifier !== undefined) {+ formData.append(`element_identifier`, internalFeedbackCreateBody.element_identifier)+ }+ if (internalFeedbackCreateBody?.screenshot !== undefined) {+ formData.append(`screenshot`, internalFeedbackCreateBody.screenshot)+ }++ return apiMutator<InternalFeedbackResponseApi>(getInternalFeedbackCreateUrl(), {+ ...options,+ method: 'POST',+ body: formData,+ })+}+export const getListUrl = (params?: ListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.tsindex 19e50b2ef960..0e0d7f43c0cc 100644--- a/products/platform_features/frontend/generated/api.zod.ts+++ b/products/platform_features/frontend/generated/api.zod.ts@@ -9,6 +9,32 @@*/import * as zod from 'zod'+/**+ * Send feedback about an element or page of the PostHog web app to the team's Slack channel.+ */+export const internalFeedbackCreateBodyCommentMax = 4000++export const internalFeedbackCreateBodyPageUrlMax = 2000++export const internalFeedbackCreateBodyElementIdentifierMax = 1000++export const InternalFeedbackCreateBody = /* @__PURE__ */ zod.object({+ comment: zod+ .string()+ .max(internalFeedbackCreateBodyCommentMax)+ .describe('What the person wants to tell the developers.'),+ page_url: zod.url().max(internalFeedbackCreateBodyPageUrlMax).describe('URL of the page the feedback is about.'),+ element_identifier: zod+ .string()+ .max(internalFeedbackCreateBodyElementIdentifierMax)+ .optional()+ .describe('CSS selector of the element the person selected. Empty for feedback about the whole page.'),+ screenshot: zod+ .instanceof(File)+ .optional()+ .describe('JPEG screenshot of the page, with the selected element outlined when there is one.'),+})+export const createBodyNameMax = 64export const createBodyMemberNoticeOneMessageMax = 1000diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yamlindex 31eead9b88ca..63524a7c9cd5 100644--- a/products/platform_features/mcp/tools.yaml+++ b/products/platform_features/mcp/tools.yaml@@ -345,6 +345,9 @@ tools:comments-update:operation: comments_updateenabled: false+ internal-feedback-create:+ operation: internal_feedback_create+ enabled: falsemembers-destroy:operation: members_destroyenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f0c38f7eb552..0e4dcf453d33 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57292,6 +57292,11 @@ export namespace Schemas {line_refs: string;}+ export interface InternalFeedbackResponse {+ /** True when the feedback reached Slack. */+ success: boolean;+ }+/*** * `5` - 5* * `15` - 15@@ -111096,6 +111101,26 @@ export namespace Schemas {Ndjson: 'ndjson',} as const;+ export type InternalFeedbackCreateBody = {+ /**+ * What the person wants to tell the developers.+ * @maxLength 4000+ */+ comment: string;+ /**+ * URL of the page the feedback is about.+ * @maxLength 2000+ */+ page_url: string;+ /**+ * CSS selector of the element the person selected. Empty for feedback about the whole page.+ * @maxLength 1000+ */+ element_identifier?: string;+ /** JPEG screenshot of the page, with the selected element outlined when there is one. */+ screenshot?: Blob;+ };+export type LlmAnalyticsPersonalSpendListParams = {/*** When set, additionally return a `by_bucket` breakdown: a time-ascending UTC cost series for the scoped product at this bucket size in minutes, with per-bucket cost split into uncached input / output / cache read / cache creation components plus the matching token sums. Supported bucket sizes: 5, 15, 30, 60. The window may span at most 600 buckets of the chosen size (e.g. 50 hours at 5-minute buckets).