: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(toolbar): sign in, inspect and show heatmaps in the extension side panel (#116647)
posthog[bot]e666e8982250
diff --git a/.agents/skills/building-the-toolbar/SKILL.md b/.agents/skills/building-the-toolbar/SKILL.mdindex 2071d93dd8f4..34a3e76e1413 100644--- a/.agents/skills/building-the-toolbar/SKILL.md+++ b/.agents/skills/building-the-toolbar/SKILL.md@@ -8,14 +8,15 @@ description: Builds, watches, checks and verifies the PostHog toolbar in both ofOne source tree, `frontend/src/toolbar/`, ships in two forms.Both builds live in `frontend/toolbar-config.mjs` and share its toolbar module plugin, which swaps app modules for the toolbar's shims and keeps denylisted packages out.-| Form | Entry | Output (under `frontend/dist/`) | Runs in |-| ----------------- | -------------------------------------- | --------------------------------------------------- | ------------------------------------------------ |-| Floating toolbar | `src/toolbar/index.tsx` | `toolbar.js` loader, `toolbar/` app chunks | Customer pages, loaded by posthog-js |-| Browser extension | `src/toolbar/extension/panel.tsx` etc. | `toolbar-extension/<browser>/`, one zip per browser | Chrome side panel, Firefox sidebar (Manifest V3) |+| Form | Entry | Output (under `frontend/dist/`) | Runs in |+| ----------------- | ------------------------------------------------ | --------------------------------------------------- | ------------------------------------------------ |+| Floating toolbar | `src/toolbar/index.tsx` | `toolbar.js` loader, `toolbar/` app chunks | Customer pages, loaded by posthog-js |+| Browser extension | `src/toolbar/extension/panel.tsx`, `content.tsx` | `toolbar-extension/<browser>/`, one zip per browser | Chrome side panel, Firefox sidebar (Manifest V3) |## Build both, every time-Its panel imports the floating toolbar's own modules, such as `toolbarConfigLogic`, `toolbarEntitlementsLogic` and `toolbarPosthogJS`, and goes through the same module plugin.+The extension's content script, `extension/content.tsx`, runs the floating toolbar's own kea logics and components on the page, such as `toolbarConfigLogic`, `elementsLogic` and `ElementOverlays`.+The panel imports toolbar modules too, and both go through the same module plugin.So any change under `frontend/src/toolbar/`, or in `toolbar-config.mjs`, can break either form, even when you only meant to touch one.- Build and check both forms for every toolbar change.@@ -71,7 +72,7 @@ Tests and builds don't show a broken overlay, a missing style, or a CSP refusal.- **Extension.** Load `dist/toolbar-extension/chrome` unpacked in Chrome and `dist/toolbar-extension/firefox` as a temporary add-on in Firefox.The steps are in [the extension README](../../../frontend/src/toolbar/extension/README.md#build-and-install); read it before you load the extension the first time.After a rebuild, reload the extension, then close and open the panel.- Check both browsers when you change the extension.+ Check both browsers when you change the extension, and walk the README's [manual checks](../../../frontend/src/toolbar/extension/README.md#check-the-flows-by-hand) for the tools you touched.- **Floating toolbar.** Start the dev stack (see `/run-posthog`), open the Toolbar page at `http://localhost:8010/toolbar`, add a test site that loads posthog-js to the authorized URLs, and launch the toolbar on it.`Toolbar.stories.tsx` renders the floating toolbar in Storybook when you only need to look at a component.diff --git a/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx b/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsxindex 09194d5193e8..11d24a6ebc47 100644--- a/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx+++ b/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx@@ -1,35 +1,32 @@-import { useValues } from 'kea'import React, { useState } from 'react'import { IconInfo } from '@posthog/icons'import { HEATMAP_COLOR_PALETTE_OPTIONS, HEATMAP_TYPE_OPTIONS } from 'lib/components/heatmaps/heatmapDataLogic'-import { HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'+import { HeatmapFilters, HeatmapFixedPositionMode, ScrollDepthPosthogJsError } from 'lib/components/heatmaps/types'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonLabel } from 'lib/lemon-ui/LemonLabel'import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'import { LemonSelect } from 'lib/lemon-ui/LemonSelect'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'-import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'--const ScrollDepthJSWarning = (): JSX.Element | null => {- const { scrollDepthPosthogJsError } = useValues(heatmapToolbarMenuLogic)-- if (!scrollDepthPosthogJsError) {+const ScrollDepthJSWarning = ({ error }: { error: ScrollDepthPosthogJsError }): JSX.Element | null => {+ if (!error) {return null}return (<p className="my-2 bg-danger-highlight border border-danger rounded p-2">- {scrollDepthPosthogJsError === 'version' ? (+ {error === 'version' ? (<>This feature requires a newer version of posthog-js</>- ) : scrollDepthPosthogJsError === 'disabled' ? (+ ) : error === 'disabled' ? (<>Your posthog-js config has <i>disable_scroll_properties</i> set - these properties are required forscroll depth calculations to work.</>- ) : null}+ ) : (+ <>Scroll depth needs posthog-js on this page.</>+ )}</p>)}@@ -76,6 +73,7 @@ interface HeatmapsSettingsProps {setHeatmapColorPalette?: (palette: string | null) => voidheatmapFixedPositionMode?: HeatmapFixedPositionModesetHeatmapFixedPositionMode?: (mode: HeatmapFixedPositionMode) => void+ scrollDepthPosthogJsError?: ScrollDepthPosthogJsError}export const HeatmapsSettings = ({@@ -86,6 +84,7 @@ export const HeatmapsSettings = ({setHeatmapColorPalette,heatmapFixedPositionMode,setHeatmapFixedPositionMode,+ scrollDepthPosthogJsError = null,}: HeatmapsSettingsProps): JSX.Element => {return (<>@@ -110,7 +109,9 @@ export const HeatmapsSettings = ({size="small"/>- {heatmapFilters?.type === 'scrolldepth' && <ScrollDepthJSWarning />}+ {heatmapFilters?.type === 'scrolldepth' && (+ <ScrollDepthJSWarning error={scrollDepthPosthogJsError} />+ )}</div></SectionSetting>diff --git a/frontend/src/lib/components/heatmaps/types.ts b/frontend/src/lib/components/heatmaps/types.tsindex da89a895bcc8..d9746f13636e 100644--- a/frontend/src/lib/components/heatmaps/types.ts+++ b/frontend/src/lib/components/heatmaps/types.ts@@ -96,3 +96,6 @@ export type HeatmapEventsResponse = {total_count: numberhas_more: boolean}++/** `missing` when the page has no posthog-js, which the browser extension can run without. */+export type ScrollDepthPosthogJsError = 'version' | 'disabled' | 'missing' | nulldiff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.mdindex 92fc9991220e..2b9d41937d71 100644--- a/frontend/src/toolbar/TELEMETRY.md+++ b/frontend/src/toolbar/TELEMETRY.md@@ -348,3 +348,38 @@ Fired after a successful screenshot/media upload.| `source` | `'toolbar'` | Always `'toolbar'` |**File:** `screenshot-upload/screenshotUploadLogic.ts`++## Browser extension++### `toolbar extension panel state`++Fired when the side panel shows a new state.++| Property | Type | Description |+| -------------------- | --------------------- | --------------------------------------------------------------- |+| `state` | `string` | The state kind, for example `'ready'` or `'unauthorized-url'` |+| `unsupported_reason` | `string \| undefined` | Why the toolbar can't run on the page, for `'unsupported-page'` |++**File:** `extension/extensionPanelLogic.ts`++### `toolbar extension page tool used`++Fired when the user runs a tool on the page from the extension.++| Property | Type | Description |+| -------- | -------- | --------------------------------------------- |+| `tool` | `string` | `'inspect'`, `'heatmap'`, or `'save-heatmap'` |++**File:** `extension/extensionTelemetry.ts`++### `toolbar extension authenticated`++Fired when the extension finishes the toolbar OAuth flow for a project, which gives the page tools their own access.++| Property | Type | Description |+| ------------- | --------------------- | --------------------------------------------------------------------------- |+| `status` | `string` | `'success'` or `'error'` |+| `interactive` | `boolean` | `true` when the user clicked **Connect**, `false` when the panel started it |+| `error` | `string \| undefined` | The error message, for `'error'` |++**File:** `extension/extensionAuthLogic.ts`diff --git a/frontend/src/toolbar/ToolbarApp.tsx b/frontend/src/toolbar/ToolbarApp.tsxindex 784ab8df734f..3b4baa8250f3 100644--- a/frontend/src/toolbar/ToolbarApp.tsx+++ b/frontend/src/toolbar/ToolbarApp.tsx@@ -12,7 +12,7 @@ import { toolbarLogger } from '~/toolbar/toolbarLogger'import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { ToolbarProps } from '~/types'-import { TOOLBAR_ID } from './utils'+import { TOOLBAR_ID, TOOLBAR_ROOT_ATTRIBUTE } from './utils'import { webVitalsToolbarLogic } from './web-vitals/webVitalsToolbarLogic'type HTMLElementWithShadowRoot = HTMLElement & { shadowRoot: ShadowRoot }@@ -98,7 +98,13 @@ export function ToolbarApp(props: ToolbarProps = {}): JSX.Element {return (<>- <root.div id={TOOLBAR_ID} className="ph-no-capture" ref={shadowRef} onMouseDown={onMouseDown}>+ <root.div+ id={TOOLBAR_ID}+ className="ph-no-capture"+ ref={shadowRef}+ onMouseDown={onMouseDown}+ {...{ [TOOLBAR_ROOT_ATTRIBUTE]: '' }}+ ><div id="posthog-toolbar-styles" />{didRender && (didLoadStyles || props.disableExternalStyles) ? <ToolbarContainer /> : null}<ToastContainer autoClose={60000} transition={Slide} position="bottom-center" />diff --git a/frontend/src/toolbar/elements/ElementOverlays.tsx b/frontend/src/toolbar/elements/ElementOverlays.tsxnew file mode 100644index 000000000000..d25eca5a3eda--- /dev/null+++ b/frontend/src/toolbar/elements/ElementOverlays.tsx@@ -0,0 +1,181 @@+import { useActions, useValues } from 'kea'+import { MouseEvent as ReactMouseEvent, ReactNode, useMemo } from 'react'++import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'+import { useShiftKeyPressed } from 'lib/components/heatmaps/useShiftKeyPressed'++import { AutocaptureElement } from '~/toolbar/elements/AutocaptureElement'+import { AutocaptureElementLabel } from '~/toolbar/elements/AutocaptureElementLabel'+import { elementsLogic } from '~/toolbar/elements/elementsLogic'+import { FocusRect } from '~/toolbar/elements/FocusRect'+import { HeatmapOverlayElements, getStableElementId } from '~/toolbar/elements/HeatmapOverlayElements'+import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { ElementHighlight } from '~/toolbar/product-tours/ElementHighlight'+import { getBoxColors, isInToolbarRoot } from '~/toolbar/utils'++import { ScrollDepth } from './ScrollDepth'++const noop = (): void => {}++export function ElementOverlays({+ showHeatmapCanvas,+ children,+}: {+ showHeatmapCanvas: boolean+ /** More highlights, drawn above the area filter and below the element boxes. */+ children?: ReactNode+}): JSX.Element {+ const {+ heatmapElements,+ elementsToDisplay,+ labelsToDisplay,+ hoverElement,+ selectedElement,+ inspectEnabled,+ highlightElementMeta,+ relativePositionCompensation,+ heatmapEnabled,+ rectUpdateCounter,+ } = useValues(elementsLogic)+ const { setHoverElement, selectElement } = useActions(elementsLogic)+ const { highestClickCount, areaSelectionActive, areaHoverElement, heatmapAreaFilter, areaCandidates } =+ useValues(heatmapToolbarMenuLogic)+ const { refreshClickmap, setAreaHover, selectHeatmapAreaFilter } = useActions(heatmapToolbarMenuLogic)++ const shiftPressed = useShiftKeyPressed(refreshClickmap)+ // while picking an area the page itself must receive pointer events, so all overlays pass through+ const heatmapPointerEvents = shiftPressed || areaSelectionActive ? 'none' : 'all'++ // recomputed on scroll/resize via rectUpdateCounter so the fixed-position highlights track the page+ const areaHoverRect = useMemo(+ () => (areaHoverElement?.isConnected ? areaHoverElement.getBoundingClientRect() : null),+ [areaHoverElement, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps+ )+ const areaFilterRect = useMemo(+ () => (heatmapAreaFilter?.element.isConnected ? heatmapAreaFilter.element.getBoundingClientRect() : null),+ [heatmapAreaFilter, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps+ )+ // already sorted biggest-first, so nested candidates paint children-on-top and stay hoverable+ const areaCandidateRects = useMemo(+ () =>+ areaSelectionActive+ ? areaCandidates+ .filter((element) => element.isConnected)+ .map((element) => ({ element, rect: element.getBoundingClientRect() }))+ : [],+ [areaSelectionActive, areaCandidates, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps+ )++ const hoverAreaCandidate = (e: ReactMouseEvent, element: HTMLElement): void => {+ // the real page leaf under the pointer (not this overlay box) anchors the arrow-key+ // walk, so pressing down still shrinks toward what the user is pointing at+ const leaf = (document.elementsFromPoint(e.clientX, e.clientY) as HTMLElement[]).find(+ (el) => !isInToolbarRoot(el)+ )+ setAreaHover(leaf ?? element, element)+ }++ return (+ <div+ id="posthog-toolbar-elements"+ className="w-full h-full absolute top-0 pointer-events-none z-[2147483010]"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ top: relativePositionCompensation,+ }}+ >+ <ScrollDepth />+ {showHeatmapCanvas && <HeatmapCanvas positioning="absolute" context="toolbar" />}+ {highlightElementMeta?.rect ? <FocusRect rect={highlightElementMeta.rect} /> : null}+ {areaCandidateRects.map(({ element, rect }) => (+ <AutocaptureElement+ key={`area-candidate-${getStableElementId(element)}`}+ rect={rect}+ style={{+ pointerEvents: 'all',+ cursor: 'crosshair',+ zIndex: 1,+ borderRadius: 5,+ opacity: !areaHoverElement || areaHoverElement === element ? 1 : 0.6,+ transition: 'opacity 0.2s, box-shadow 0.2s',+ ...getBoxColors('blue', areaHoverElement === element, 0.1),+ }}+ onMouseOver={(e) => hoverAreaCandidate(e, element)}+ onMouseOut={noop}+ onClick={() => selectHeatmapAreaFilter(areaHoverElement ?? element)}+ />+ ))}+ {areaSelectionActive && areaHoverRect && <ElementHighlight rect={areaHoverRect} />}+ {heatmapEnabled && !areaSelectionActive && areaFilterRect && (+ <ElementHighlight rect={areaFilterRect} isSelected />+ )}+ {children}++ {elementsToDisplay.map(({ rect, element, apparentZIndex }) => {+ return (+ <AutocaptureElement+ key={`inspect-${getStableElementId(element)}`}+ rect={rect}+ style={{+ pointerEvents: heatmapPointerEvents,+ cursor: 'pointer',+ zIndex: apparentZIndex ? apparentZIndex : hoverElement === element ? 2 : 1,+ opacity:+ (!hoverElement && !selectedElement) ||+ selectedElement === element ||+ hoverElement === element+ ? 1+ : 0.4,+ transition: 'opacity 0.2s, box-shadow 0.2s',+ borderRadius: 5,+ ...getBoxColors('blue', hoverElement === element || selectedElement === element),+ }}+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ />+ )+ })}++ <HeatmapOverlayElements+ heatmapElements={heatmapElements}+ hoverElement={hoverElement}+ selectedElement={selectedElement}+ inspectEnabled={inspectEnabled}+ heatmapPointerEvents={heatmapPointerEvents}+ highestClickCount={highestClickCount}+ selectElement={selectElement}+ setHoverElement={setHoverElement}+ />++ {labelsToDisplay.map(({ element, rect, index, visible }, loopIndex) => {+ if (!visible || !rect) {+ return null+ }+ return (+ <AutocaptureElementLabel+ key={`label-${getStableElementId(element)}`}+ rect={rect}+ align="left"+ style={{+ zIndex: 5,+ opacity: hoverElement && hoverElement !== element ? 0.4 : 1,+ transition: 'opacity 0.2s, transform 0.2s linear',+ transform: hoverElement === element ? 'scale(1.3)' : 'none',+ pointerEvents: heatmapPointerEvents,+ cursor: 'pointer',+ color: 'hsla(141, 21%, 12%, 1)',+ background: 'hsl(147, 100%, 62%)',+ boxShadow: 'hsla(141, 100%, 32%, 1) 0px 1px 5px 1px',+ }}+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ >+ {(index || loopIndex) + 1}+ </AutocaptureElementLabel>+ )+ })}+ </div>+ )+}diff --git a/frontend/src/toolbar/elements/Elements.tsx b/frontend/src/toolbar/elements/Elements.tsxindex f8251f62013e..7f294a923b69 100644--- a/frontend/src/toolbar/elements/Elements.tsx+++ b/frontend/src/toolbar/elements/Elements.tsx@@ -1,96 +1,20 @@-import { useActions, useValues } from 'kea'-import { Fragment, MouseEvent as ReactMouseEvent, memo, useMemo } from 'react'+import { useValues } from 'kea'-import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'-import { useShiftKeyPressed } from 'lib/components/heatmaps/useShiftKeyPressed'-import { compactNumber } from 'lib/utils/numbers'--import { AutocaptureElement } from '~/toolbar/elements/AutocaptureElement'-import { AutocaptureElementLabel } from '~/toolbar/elements/AutocaptureElementLabel'import { ElementInfoWindow } from '~/toolbar/elements/ElementInfoWindow'-import { elementsLogic } from '~/toolbar/elements/elementsLogic'-import { FocusRect } from '~/toolbar/elements/FocusRect'-import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { ElementOverlays } from '~/toolbar/elements/ElementOverlays'import { ElementHighlight } from '~/toolbar/product-tours/ElementHighlight'import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'-import { ElementWithMetadata } from '~/toolbar/types'-import { getBoxColors, getHeatMapHue, getToolbarRootElement } from '~/toolbar/utils'import { toolbarLogic } from '../bar/toolbarLogic'-import { ScrollDepth } from './ScrollDepth'--const noop = (): void => {}--let nextElementId = 0-const elementIdMap = new WeakMap<HTMLElement, number>()--function getStableElementId(element: HTMLElement): number {- let id = elementIdMap.get(element)- if (id === undefined) {- id = nextElementId++- elementIdMap.set(element, id)- }- return id-}export function Elements(): JSX.Element {const { visibleMenu: activeToolbarMode } = useValues(toolbarLogic)- const {- heatmapElements,- elementsToDisplay,- labelsToDisplay,- hoverElement,- selectedElement,- inspectEnabled,- highlightElementMeta,- relativePositionCompensation,- heatmapEnabled,- rectUpdateCounter,- } = useValues(elementsLogic)- const { setHoverElement, selectElement } = useActions(elementsLogic)- const { highestClickCount, areaSelectionActive, areaHoverElement, heatmapAreaFilter, areaCandidates } =- useValues(heatmapToolbarMenuLogic)- const { refreshClickmap, setAreaHover, selectHeatmapAreaFilter } = useActions(heatmapToolbarMenuLogic)const {isSelecting: productToursSelecting,hoverElementRect: productToursHoverRect,expandedStepRect: productToursSelectedStepRect,} = useValues(productToursLogic)- const shiftPressed = useShiftKeyPressed(refreshClickmap)- // while picking an area the page itself must receive pointer events, so all overlays pass through- const heatmapPointerEvents = shiftPressed || areaSelectionActive ? 'none' : 'all'-- // recomputed on scroll/resize via rectUpdateCounter so the fixed-position highlights track the page- const areaHoverRect = useMemo(- () => (areaHoverElement?.isConnected ? areaHoverElement.getBoundingClientRect() : null),- [areaHoverElement, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps- )- const areaFilterRect = useMemo(- () => (heatmapAreaFilter?.element.isConnected ? heatmapAreaFilter.element.getBoundingClientRect() : null),- [heatmapAreaFilter, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps- )- // already sorted biggest-first, so nested candidates paint children-on-top and stay hoverable- const areaCandidateRects = useMemo(- () =>- areaSelectionActive- ? areaCandidates- .filter((element) => element.isConnected)- .map((element) => ({ element, rect: element.getBoundingClientRect() }))- : [],- [areaSelectionActive, areaCandidates, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps- )-- const hoverAreaCandidate = (e: ReactMouseEvent, element: HTMLElement): void => {- // the real page leaf under the pointer (not this overlay box) anchors the arrow-key- // walk, so pressing down still shrinks toward what the user is pointing at- const toolbarRoot = getToolbarRootElement()- const leaf = (document.elementsFromPoint(e.clientX, e.clientY) as HTMLElement[]).find(- (el) => !toolbarRoot?.contains(el)- )- setAreaHover(leaf ?? element, element)- }-const { theme } = useValues(toolbarLogic)// KLUDGE: if we put theme directly on the div then@@ -109,229 +33,10 @@ export function Elements(): JSX.Element {<ElementInfoWindow /></div>- <div- id="posthog-toolbar-elements"- className="w-full h-full absolute top-0 pointer-events-none z-[2147483010]"- // eslint-disable-next-line react/forbid-dom-props- style={{- top: relativePositionCompensation,- }}- >- <ScrollDepth />- {activeToolbarMode === 'heatmap' && <HeatmapCanvas positioning="absolute" context="toolbar" />}- {highlightElementMeta?.rect ? <FocusRect rect={highlightElementMeta.rect} /> : null}- {areaCandidateRects.map(({ element, rect }) => (- <AutocaptureElement- key={`area-candidate-${getStableElementId(element)}`}- rect={rect}- style={{- pointerEvents: 'all',- cursor: 'crosshair',- zIndex: 1,- borderRadius: 5,- opacity: !areaHoverElement || areaHoverElement === element ? 1 : 0.6,- transition: 'opacity 0.2s, box-shadow 0.2s',- ...getBoxColors('blue', areaHoverElement === element, 0.1),- }}- onMouseOver={(e) => hoverAreaCandidate(e, element)}- onMouseOut={noop}- onClick={() => selectHeatmapAreaFilter(areaHoverElement ?? element)}- />- ))}- {areaSelectionActive && areaHoverRect && <ElementHighlight rect={areaHoverRect} />}- {heatmapEnabled && !areaSelectionActive && areaFilterRect && (- <ElementHighlight rect={areaFilterRect} isSelected />- )}+ <ElementOverlays showHeatmapCanvas={activeToolbarMode === 'heatmap'}>{productToursSelecting && productToursHoverRect && <ElementHighlight rect={productToursHoverRect} />}{productToursSelectedStepRect && <ElementHighlight rect={productToursSelectedStepRect} isSelected />}-- {elementsToDisplay.map(({ rect, element, apparentZIndex }) => {- return (- <AutocaptureElement- key={`inspect-${getStableElementId(element)}`}- rect={rect}- style={{- pointerEvents: heatmapPointerEvents,- cursor: 'pointer',- zIndex: apparentZIndex ? apparentZIndex : hoverElement === element ? 2 : 1,- opacity:- (!hoverElement && !selectedElement) ||- selectedElement === element ||- hoverElement === element- ? 1- : 0.4,- transition: 'opacity 0.2s, box-shadow 0.2s',- borderRadius: 5,- ...getBoxColors('blue', hoverElement === element || selectedElement === element),- }}- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- />- )- })}-- <HeatmapOverlayElements- heatmapElements={heatmapElements}- hoverElement={hoverElement}- selectedElement={selectedElement}- inspectEnabled={inspectEnabled}- heatmapPointerEvents={heatmapPointerEvents}- highestClickCount={highestClickCount}- selectElement={selectElement}- setHoverElement={setHoverElement}- />-- {labelsToDisplay.map(({ element, rect, index, visible }, loopIndex) => {- if (!visible || !rect) {- return null- }- return (- <AutocaptureElementLabel- key={`label-${getStableElementId(element)}`}- rect={rect}- align="left"- style={{- zIndex: 5,- opacity: hoverElement && hoverElement !== element ? 0.4 : 1,- transition: 'opacity 0.2s, transform 0.2s linear',- transform: hoverElement === element ? 'scale(1.3)' : 'none',- pointerEvents: heatmapPointerEvents,- cursor: 'pointer',- color: 'hsla(141, 21%, 12%, 1)',- background: 'hsl(147, 100%, 62%)',- boxShadow: 'hsla(141, 100%, 32%, 1) 0px 1px 5px 1px',- }}- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- >- {(index || loopIndex) + 1}- </AutocaptureElementLabel>- )- })}- </div>+ </ElementOverlays></>)}--interface HeatmapOverlayElementsProps {- heatmapElements: ElementWithMetadata[]- hoverElement: HTMLElement | null- selectedElement: HTMLElement | null- inspectEnabled: boolean- heatmapPointerEvents: 'none' | 'all'- highestClickCount: number- selectElement: (element: HTMLElement) => void- setHoverElement: (element: HTMLElement | null) => void-}--const HeatmapOverlayElements = memo(function HeatmapOverlayElements({- heatmapElements,- hoverElement,- selectedElement,- inspectEnabled,- heatmapPointerEvents,- highestClickCount,- selectElement,- setHoverElement,-}: HeatmapOverlayElementsProps): JSX.Element {- return (- <>- {heatmapElements.map(({ rect, count, clickCount, rageclickCount, deadclickCount, element, visible }) => {- if (!visible) {- return null- }- const elementId = getStableElementId(element)- return (- <Fragment key={`heatmap-${elementId}`}>- <AutocaptureElement- rect={rect}- style={{- pointerEvents: inspectEnabled ? 'none' : heatmapPointerEvents,- zIndex: hoverElement === element ? 4 : 3,- opacity: !hoverElement || hoverElement === element ? 1 : 0.4,- transition: 'opacity 0.2s, box-shadow 0.2s',- cursor: 'pointer',- borderRadius: 5,- ...getBoxColors(- 'red',- hoverElement === element,- ((count || 0) / highestClickCount) * 0.4- ),- }}- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- />- {!!clickCount && (- <AutocaptureElementLabel- rect={rect}- style={{- pointerEvents: heatmapPointerEvents,- zIndex: 5,- opacity: hoverElement && hoverElement !== element ? 0.4 : 1,- transition: 'opacity 0.2s, transform 0.2s linear',- transform: hoverElement === element ? 'scale(1.3)' : 'none',- cursor: 'pointer',- color: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 20%, 12%, 1)`,- background: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 100%, 62%, 1)`,- boxShadow: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,- }}- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- >- {compactNumber(clickCount || 0)}- </AutocaptureElementLabel>- )}- {!!rageclickCount && (- <AutocaptureElementLabel- rect={rect}- style={{- pointerEvents: heatmapPointerEvents,- zIndex: 5,- opacity: hoverElement && hoverElement !== element ? 0.4 : 1,- transition: 'opacity 0.2s, transform 0.2s linear',- transform: hoverElement === element ? 'scale(1.3)' : 'none',- cursor: 'pointer',- color: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 20%, 12%, 1)`,- background: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 100%, 62%, 1)`,- boxShadow: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,- }}- align="left"- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- >- {compactNumber(rageclickCount)}😡- </AutocaptureElementLabel>- )}- {!!deadclickCount && (- <AutocaptureElementLabel- rect={rect}- style={{- pointerEvents: heatmapPointerEvents,- zIndex: 5,- opacity: hoverElement && hoverElement !== element ? 0.4 : 1,- transition: 'opacity 0.2s, transform 0.2s linear',- transform: hoverElement === element ? 'scale(1.3)' : 'none',- cursor: 'pointer',- color: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 20%, 12%, 1)`,- background: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 100%, 62%, 1)`,- boxShadow: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,- }}- align="left"- onClick={() => selectElement(element)}- onMouseOver={() => selectedElement === null && setHoverElement(element)}- onMouseOut={() => selectedElement === null && setHoverElement(null)}- >- {compactNumber(deadclickCount)}😵- </AutocaptureElementLabel>- )}- </Fragment>- )- })}- </>- )-})diff --git a/frontend/src/toolbar/elements/HeatmapOverlayElements.tsx b/frontend/src/toolbar/elements/HeatmapOverlayElements.tsxnew file mode 100644index 000000000000..e05b093c6f86--- /dev/null+++ b/frontend/src/toolbar/elements/HeatmapOverlayElements.tsx@@ -0,0 +1,141 @@+import { Fragment, memo } from 'react'++import { compactNumber } from 'lib/utils/numbers'++import { AutocaptureElement } from '~/toolbar/elements/AutocaptureElement'+import { AutocaptureElementLabel } from '~/toolbar/elements/AutocaptureElementLabel'+import { ElementWithMetadata } from '~/toolbar/types'+import { getBoxColors, getHeatMapHue } from '~/toolbar/utils'++let nextElementId = 0+const elementIdMap = new WeakMap<HTMLElement, number>()++export function getStableElementId(element: HTMLElement): number {+ let id = elementIdMap.get(element)+ if (id === undefined) {+ id = nextElementId+++ elementIdMap.set(element, id)+ }+ return id+}++interface HeatmapOverlayElementsProps {+ heatmapElements: ElementWithMetadata[]+ hoverElement: HTMLElement | null+ selectedElement: HTMLElement | null+ inspectEnabled: boolean+ heatmapPointerEvents: 'none' | 'all'+ highestClickCount: number+ selectElement: (element: HTMLElement) => void+ setHoverElement: (element: HTMLElement | null) => void+}++export const HeatmapOverlayElements = memo(function HeatmapOverlayElements({+ heatmapElements,+ hoverElement,+ selectedElement,+ inspectEnabled,+ heatmapPointerEvents,+ highestClickCount,+ selectElement,+ setHoverElement,+}: HeatmapOverlayElementsProps): JSX.Element {+ return (+ <>+ {heatmapElements.map(({ rect, count, clickCount, rageclickCount, deadclickCount, element, visible }) => {+ if (!visible) {+ return null+ }+ const elementId = getStableElementId(element)+ return (+ <Fragment key={`heatmap-${elementId}`}>+ <AutocaptureElement+ rect={rect}+ style={{+ pointerEvents: inspectEnabled ? 'none' : heatmapPointerEvents,+ zIndex: hoverElement === element ? 4 : 3,+ opacity: !hoverElement || hoverElement === element ? 1 : 0.4,+ transition: 'opacity 0.2s, box-shadow 0.2s',+ cursor: 'pointer',+ borderRadius: 5,+ ...getBoxColors(+ 'red',+ hoverElement === element,+ ((count || 0) / highestClickCount) * 0.4+ ),+ }}+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ />+ {!!clickCount && (+ <AutocaptureElementLabel+ rect={rect}+ style={{+ pointerEvents: heatmapPointerEvents,+ zIndex: 5,+ opacity: hoverElement && hoverElement !== element ? 0.4 : 1,+ transition: 'opacity 0.2s, transform 0.2s linear',+ transform: hoverElement === element ? 'scale(1.3)' : 'none',+ cursor: 'pointer',+ color: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 20%, 12%, 1)`,+ background: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 100%, 62%, 1)`,+ boxShadow: `hsla(${getHeatMapHue(clickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,+ }}+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ >+ {compactNumber(clickCount || 0)}+ </AutocaptureElementLabel>+ )}+ {!!rageclickCount && (+ <AutocaptureElementLabel+ rect={rect}+ style={{+ pointerEvents: heatmapPointerEvents,+ zIndex: 5,+ opacity: hoverElement && hoverElement !== element ? 0.4 : 1,+ transition: 'opacity 0.2s, transform 0.2s linear',+ transform: hoverElement === element ? 'scale(1.3)' : 'none',+ cursor: 'pointer',+ color: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 20%, 12%, 1)`,+ background: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 100%, 62%, 1)`,+ boxShadow: `hsla(${getHeatMapHue(rageclickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,+ }}+ align="left"+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ >+ {compactNumber(rageclickCount)}😡+ </AutocaptureElementLabel>+ )}+ {!!deadclickCount && (+ <AutocaptureElementLabel+ rect={rect}+ style={{+ pointerEvents: heatmapPointerEvents,+ zIndex: 5,+ opacity: hoverElement && hoverElement !== element ? 0.4 : 1,+ transition: 'opacity 0.2s, transform 0.2s linear',+ transform: hoverElement === element ? 'scale(1.3)' : 'none',+ cursor: 'pointer',+ color: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 20%, 12%, 1)`,+ background: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 100%, 62%, 1)`,+ boxShadow: `hsla(${getHeatMapHue(deadclickCount || 0, highestClickCount)}, 100%, 32%, 1) 0px 1px 5px 1px`,+ }}+ align="left"+ onClick={() => selectElement(element)}+ onMouseOver={() => selectedElement === null && setHoverElement(element)}+ onMouseOut={() => selectedElement === null && setHoverElement(null)}+ >+ {compactNumber(deadclickCount)}😵+ </AutocaptureElementLabel>+ )}+ </Fragment>+ )+ })}+ </>+ )+})diff --git a/frontend/src/toolbar/elements/domElementIndex.ts b/frontend/src/toolbar/elements/domElementIndex.tsindex e6f84d490d2c..087e10a938b4 100644--- a/frontend/src/toolbar/elements/domElementIndex.ts+++ b/frontend/src/toolbar/elements/domElementIndex.ts@@ -4,7 +4,7 @@ import { elementToSelector, matchesDataAttribute } from 'lib/utils/actions'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'-import { TOOLBAR_ID } from '~/toolbar/utils'+import { isToolbarRootElement } from '~/toolbar/utils'import { ElementType } from '~/types'interface ElementFingerprint {@@ -90,7 +90,7 @@ function createFingerprint(}export function hasNonToolbarShadowRoots(pageElements: HTMLElement[]): boolean {- return pageElements.some((el) => !!el.shadowRoot && el.id !== TOOLBAR_ID)+ return pageElements.some((el) => !!el.shadowRoot && !isToolbarRootElement(el))}export function buildDOMIndex(pageElements: HTMLElement[]): DOMIndex {@@ -131,7 +131,7 @@ export function buildDOMIndex(pageElements: HTMLElement[]): DOMIndex {addToIndex(index.byHref, href, element)}- if (element.shadowRoot && element.id !== TOOLBAR_ID) {+ if (element.shadowRoot && !isToolbarRootElement(element)) {index.hasShadowRoots = true}}diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.tsindex c824fd9b59bd..7044bc9ef508 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts@@ -8,6 +8,7 @@ import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { ElementsEventType } from '~/toolbar/types'+import { TOOLBAR_ROOT_ATTRIBUTE } from '~/toolbar/utils'import {LOAD_ALL_MAX_PAGES,@@ -262,6 +263,14 @@ describe('heatmapToolbarMenuLogic', () => {expect(computeAreaCandidates()).toEqual([big, nav])})+ it('skips a toolbar overlay root that covers the page', () => {+ const toolbarRoot = addElement('div', { top: 0, left: 0, width: 800, height: 600 })+ toolbarRoot.setAttribute(TOOLBAR_ROOT_ATTRIBUTE, '')+ const main = addElement('main', { top: 0, left: 0, width: 600, height: 400 })++ expect(computeAreaCandidates()).toEqual([main])+ })+it('collapses a same-rect wrapper chain to its deepest element', () => {const outer = addElement('div', { top: 0, left: 0, width: 800, height: 600 })const inner = addElement('div', { top: 0, left: 0, width: 800, height: 600 }, outer)diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex b5d0ffb00a1e..104c905f7157 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -23,7 +23,7 @@ import {heatmapUrlPatternToRegex,resolveHeatmapUrlFilter,} from 'lib/components/heatmaps/heatmapUrlMatch'-import { HeatmapBoundsFilter } from 'lib/components/heatmaps/types'+import { HeatmapBoundsFilter, ScrollDepthPosthogJsError } from 'lib/components/heatmaps/types'import { FEATURE_FLAGS } from 'lib/constants'import { createSliceYielder } from 'lib/utils/async'import { createVersionChecker } from 'lib/utils/semver'@@ -48,7 +48,7 @@ import {elementIsVisible,elementToActionStep,getParent,- getToolbarRootElement,+ isInToolbarRoot,invalidateZoomCache,trimElement,} from '~/toolbar/utils'@@ -97,12 +97,11 @@ const AREA_CANDIDATE_LIMIT = 300// visibly its own region. Same-rect wrapper chains collapse to their deepest element,// and the result is sorted biggest-first so nested boxes paint children-on-top.export function computeAreaCandidates(): HTMLElement[] {- const toolbarRoot = getToolbarRootElement()const visibilityCache = new WeakMap<HTMLElement, boolean>()const byRectKey = new Map<string, { element: HTMLElement; area: number }>()for (const element of collectAllElementsDeep('*', document) as HTMLElement[]) {- if (toolbarRoot?.contains(element) || !element.matches(`${AREA_TARGET_SELECTOR}, div`)) {+ if (isInToolbarRoot(element) || !element.matches(`${AREA_TARGET_SELECTOR}, div`)) {continue}const rect = element.getBoundingClientRect()@@ -407,7 +406,7 @@ export interface heatmapToolbarMenuLogicValues {processed: numbertotal: number} | null- scrollDepthPosthogJsError: 'disabled' | 'version' | null+ scrollDepthPosthogJsError: ScrollDepthPosthogJsErrorwantedDataAttributes: string[]windowHeight: numberwindowWidth: number@@ -626,7 +625,7 @@ export interface heatmapToolbarMenuLogicMeta {wantedDataAttributes: (dataAttributes: string[]) => string[]clickCount: (countedElements: CountedHTMLElement[]) => numberhighestClickCount: (countedElements: CountedHTMLElement[]) => number- scrollDepthPosthogJsError: (posthog: PostHog | null) => 'disabled' | 'version' | null+ scrollDepthPosthogJsError: (posthog: PostHog | null) => ScrollDepthPosthogJsErrorprocessingInputs: (elementStats: PaginatedResponse<ElementsEventType> | null,dataAttributes: string[],@@ -1014,9 +1013,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([scrollDepthPosthogJsError: [(s) => [s.posthog],- (posthog: PostHog | null): 'version' | 'disabled' | null => {+ (posthog: PostHog | null): ScrollDepthPosthogJsError => {if (!posthog) {- return null+ return 'missing'}const posthogVersion =@@ -1536,8 +1535,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([cache.disposables.add(() => {// capture-phase document listeners so area picking sees page elements before the// page's own handlers do; guarded by areaSelectionActive so they cost nothing otherwise- const isToolbarElement = (element: HTMLElement): boolean =>- getToolbarRootElement()?.contains(element) ?? false+ const isToolbarElement = isInToolbarRootconst onMouseOver = (e: MouseEvent): void => {if (!values.areaSelectionActive) {diff --git a/frontend/src/toolbar/extension/ExtensionFeatureList.tsx b/frontend/src/toolbar/extension/ExtensionFeatureList.tsxindex 05ef358fba78..ab5a8ffe41f5 100644--- a/frontend/src/toolbar/extension/ExtensionFeatureList.tsx+++ b/frontend/src/toolbar/extension/ExtensionFeatureList.tsx@@ -1,62 +1,36 @@-import { useActions, useValues } from 'kea'+import { useActions } from 'kea'-import { IconBolt, IconCursorClick, IconExternal, IconFlask, IconPieChart, IconToggle } from '@posthog/icons'+import { IconExternal } from '@posthog/icons'-import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { ToolbarFeatureGateStatus, toolbarFeatureGateStatus } from '~/toolbar/toolbarEntitlementsLogic'-import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'--import { EXTENSION_FEATURE_ENTRY_POINTS, ExtensionFeatureEntryPoint, ExtensionFeatureKey } from './extensionFeatures'+import { PAGE_TOOLS } from './extensionPageTools'import { extensionPanelLogic } from './extensionPanelLogic'+import { usePageToolDisabledReason } from './usePageToolDisabledReason'-const FEATURE_ICONS: Record<ExtensionFeatureKey, JSX.Element> = {- heatmaps: <IconCursorClick />,- actions: <IconBolt />,- 'feature-flags': <IconToggle />,- 'web-vitals': <IconPieChart />,- experiments: <IconFlask />,-}--const GATE_DISABLED_REASONS: Record<ToolbarFeatureGateStatus, string | null> = {- available: null,- checking: 'Checking plan access…',- unknown: "Couldn't check plan access. Close and open the panel to try again.",- locked: 'Needs a pay-as-you-go subscription',-}--function ExtensionFeatureButton({ entryPoint }: { entryPoint: ExtensionFeatureEntryPoint }): JSX.Element {- const { entitlements } = useValues(extensionPanelLogic)+export function ExtensionFeatureList({ origin }: { origin: string }): JSX.Element {const { openFeature } = useActions(extensionPanelLogic)- // Hooks run unconditionally, so features without a gate read the flag and ignore it.- const rolloutEnabled = useToolbarFeatureFlag(entryPoint.gate?.rolloutFlag ?? FEATURE_FLAGS.TOOLBAR_PAID_HEATMAPS)- const gateStatus = entryPoint.gate- ? toolbarFeatureGateStatus(entryPoint.gate.feature, rolloutEnabled, entitlements, false)- : 'available'+ const disabledReason = usePageToolDisabledReason()- return (- <LemonButton- fullWidth- icon={FEATURE_ICONS[entryPoint.key]}- sideIcon={<IconExternal />}- disabledReason={GATE_DISABLED_REASONS[gateStatus]}- tooltip={`${entryPoint.description}. Opens in PostHog.`}- onClick={() => openFeature(entryPoint.key, entryPoint.path)}- data-attr={`toolbar-extension-feature-${entryPoint.key}`}- >- {entryPoint.label}- </LemonButton>- )-}--export function ExtensionFeatureList({ origin }: { origin: string }): JSX.Element {return (<div className="flex flex-col gap-1">- <div className="text-secondary text-xs">Toolbar tools for {new URL(origin).host}</div>- {EXTENSION_FEATURE_ENTRY_POINTS.map((entryPoint) => (- <ExtensionFeatureButton key={entryPoint.key} entryPoint={entryPoint} />- ))}+ <div className="text-secondary text-xs">Open in PostHog for {new URL(origin).host}</div>+ {PAGE_TOOLS.map(({ feature, ...tool }) =>+ feature ? (+ <LemonButton+ key={feature.key}+ fullWidth+ icon={tool.icon}+ sideIcon={<IconExternal />}+ disabledReason={disabledReason({ ...tool, feature })}+ tooltip={`${tool.description}. Opens in PostHog.`}+ onClick={() => openFeature(feature.key, feature.path)}+ data-attr={`toolbar-extension-feature-${feature.key}`}+ >+ {tool.label}+ </LemonButton>+ ) : null+ )}</div>)}diff --git a/frontend/src/toolbar/extension/ExtensionHeatmapMenu.tsx b/frontend/src/toolbar/extension/ExtensionHeatmapMenu.tsxnew file mode 100644index 000000000000..c06fff9c451a--- /dev/null+++ b/frontend/src/toolbar/extension/ExtensionHeatmapMenu.tsx@@ -0,0 +1,349 @@+import { useActions, useValues } from 'kea'++import { IconMagicWand, IconTarget } from '@posthog/icons'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { HeatmapsSettings } from 'lib/components/heatmaps/HeatMapsSettings'+import { heatmapDateOptions } from 'lib/components/IframedToolbarBrowser/utils'+import { IconSync } from 'lib/lemon-ui/icons'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonSnack } from 'lib/lemon-ui/LemonSnack'+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'+import { Link } from 'lib/lemon-ui/Link'+import { Spinner } from 'lib/lemon-ui/Spinner'++import { urls } from '~/toolbar/urls'++import { ExtensionInspectedElement } from './ExtensionInspectedElement'+import type { PageHeatmapCommand } from './extensionPageHeatmapLogic'+import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'+import { extensionPanelLogic } from './extensionPanelLogic'+import { capturePageToolUsed } from './extensionTelemetry'+import type { PageToolbarHeatmapState } from './pageToolbarBridge'++function HeatmapsCollectionWarning({ heatmap }: { heatmap: PageToolbarHeatmapState }): JSX.Element | null {+ const { projectUrl } = useValues(extensionPanelLogic)+ if (heatmap.heatmapsCollection === 'unsupported') {+ return (+ <LemonBanner type="warning">+ The version of posthog-js on this page doesn't collect heatmap data.+ </LemonBanner>+ )+ }+ if (heatmap.heatmapsCollection === 'disabled') {+ return (+ <LemonBanner type="warning">+ This page doesn't collect heatmap data. Turn it on in your posthog-js configuration or{' '}+ <Link to={projectUrl(urls.settings('environment-heatmaps', 'heatmaps'))} target="_blank">+ in your project settings+ </Link>+ .+ </LemonBanner>+ )+ }+ return null+}++function HeatmapSaveResultMessage({ heatmap }: { heatmap: PageToolbarHeatmapState }): JSX.Element | null {+ const { openHeatmapInPostHog } = useActions(extensionPageToolbarConnectionLogic)+ const result = heatmap.saveResult+ if (!result || heatmap.savingHeatmap) {+ return null+ }+ if (result.status === 'failed') {+ return <div className="text-danger text-xs">Couldn't save this heatmap: {result.error}</div>+ }+ const allWidths = result.savedWidths === result.totalWidths+ return (+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span className={allWidths ? 'text-success' : 'text-warning'}>+ {allWidths+ ? 'Heatmap saved.'+ : result.savedWidths === 0+ ? 'Heatmap saved at your current window width only.'+ : `Heatmap saved with ${result.savedWidths} of ${result.totalWidths} page widths.`}+ </span>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => openHeatmapInPostHog(result.shortId)}+ data-attr="toolbar-extension-open-saved-heatmap"+ >+ Open in PostHog+ </LemonButton>+ </div>+ )+}++export function ExtensionHeatmapMenu(): JSX.Element {+ const { heatmap, wildcardHrefDraft } = useValues(extensionPageToolbarConnectionLogic)+ const { sendCommand, setWildcardHref } = useActions(extensionPageToolbarConnectionLogic)+ const sendHeatmapCommand = (command: PageHeatmapCommand): void => sendCommand({ tool: 'heatmap', command })++ if (!heatmap) {+ return (+ <div className="flex items-center gap-2 text-secondary">+ <Spinner />+ Loading the heatmap…+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1">+ <div className="flex gap-1">+ <LemonInput+ className="flex-1 min-w-0"+ size="small"+ value={wildcardHrefDraft ?? heatmap.wildcardHref}+ onChange={setWildcardHref}+ />+ <LemonButton+ size="small"+ type={heatmap.autoWildcardEnabled ? 'primary' : 'secondary'}+ icon={<IconMagicWand />}+ onClick={() => sendHeatmapCommand({ type: 'auto-wildcard-href' })}+ tooltip={+ <>+ Use <code>*</code> to match any characters in the URL. Click to add wildcards where they+ make sense.+ </>+ }+ data-attr="toolbar-extension-heatmap-wildcard"+ />+ </div>+ <LemonSwitch+ size="small"+ checked={heatmap.autoWildcardEnabled}+ onChange={(enabled) => sendHeatmapCommand({ type: 'set-auto-wildcard-enabled', enabled })}+ label="Add wildcards when you go to another page"+ />+ {heatmap.wildcardHrefTooSpecific && (+ <div className="text-xs text-secondary">+ {heatmap.wildcardHrefEndsWithSlash ? (+ <>+ A trailing slash matches only URLs that end there, so deeper pages and query strings+ drop out. Use <code>*</code> to include them.+ </>+ ) : (+ <>+ This URL is specific, so it matches less data. Use <code>*</code> as a wildcard to match+ more.+ </>+ )}+ </div>+ )}+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <DateFilter+ dateFrom={heatmap.commonFilters.date_from}+ dateTo={heatmap.commonFilters.date_to}+ onChange={(dateFrom, dateTo) =>+ sendHeatmapCommand({+ type: 'set-common-filters',+ filters: { date_from: dateFrom, date_to: dateTo },+ })+ }+ dateOptions={heatmapDateOptions}+ />+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconTarget />}+ active={heatmap.areaSelectionActive}+ onClick={() =>+ sendHeatmapCommand({+ type: heatmap.areaSelectionActive ? 'cancel-area-selection' : 'start-area-selection',+ })+ }+ tooltip="Limit the heatmap and clickmap to one part of the page. Click this, then click an area on the page. Press ↑ or ↓ to grow or shrink the area, and Esc to cancel."+ data-attr="toolbar-extension-heatmap-area-filter"+ >+ {heatmap.areaSelectionActive ? 'Click an area of the page…' : 'Filter to area'}+ </LemonButton>+ </div>+ {heatmap.areaFilter && !heatmap.areaSelectionActive && (+ <div className="flex items-center gap-2">+ <span className="text-secondary text-xs">Filtered to</span>+ <LemonSnack+ className="font-mono text-xs shrink min-w-0 truncate"+ onClose={() => sendHeatmapCommand({ type: 'clear-area-filter' })}+ >+ {heatmap.areaFilter.selector ?? `<${heatmap.areaFilter.tagName}>`}+ </LemonSnack>+ </div>+ )}++ <div className="flex flex-col gap-2 border-t pt-2">+ <LemonSwitch+ fullWidth+ bordered+ label={+ <span className="flex items-center gap-2">+ Heatmaps {heatmap.rawHeatmapLoading && <Spinner />}+ </span>+ }+ checked={!!heatmap.heatmapFilters.enabled}+ onChange={(enabled) => sendHeatmapCommand({ type: 'patch-heatmap-filters', filters: { enabled } })}+ data-attr="toolbar-extension-heatmap-canvas-toggle"+ />+ {heatmap.heatmapFilters.enabled && (+ <>+ <HeatmapsCollectionWarning heatmap={heatmap} />+ <div className="text-xs text-secondary">+ Heatmaps use pointer data sent with standard events. They might not match the page you see+ exactly.+ </div>+ <HeatmapsSettings+ heatmapFilters={heatmap.heatmapFilters}+ patchHeatmapFilters={(filters) =>+ sendHeatmapCommand({ type: 'patch-heatmap-filters', filters })+ }+ viewportRange={heatmap.viewportRange}+ heatmapColorPalette={heatmap.heatmapColorPalette}+ setHeatmapColorPalette={(palette) =>+ sendHeatmapCommand({ type: 'set-color-palette', palette })+ }+ heatmapFixedPositionMode={heatmap.heatmapFixedPositionMode}+ setHeatmapFixedPositionMode={(mode) =>+ sendHeatmapCommand({ type: 'set-fixed-position-mode', mode })+ }+ scrollDepthPosthogJsError={heatmap.scrollDepthPosthogJsError}+ />+ <LemonButton+ type="primary"+ fullWidth+ center+ loading={heatmap.savingHeatmap}+ onClick={() => {+ capturePageToolUsed('save-heatmap')+ sendHeatmapCommand({ type: 'save-heatmap' })+ }}+ data-attr="toolbar-extension-heatmap-save"+ >+ {heatmap.savingHeatmap && heatmap.saveProgress+ ? `Capturing screen widths (${heatmap.saveProgress.done}/${heatmap.saveProgress.total})`+ : 'Save to PostHog'}+ </LemonButton>+ <div className="text-xs text-secondary">+ Captures this page at several screen widths and saves them with the heatmap, so you can open+ it in PostHog later. Works when the page is behind a login.+ </div>+ <HeatmapSaveResultMessage heatmap={heatmap} />+ </>+ )}+ </div>++ <div className="flex flex-col gap-2 border-t pt-2">+ <LemonSwitch+ fullWidth+ bordered+ label={+ <span className="flex items-center gap-2">+ Clickmaps (autocapture){' '}+ {(heatmap.clickmapLoading || !!heatmap.processingProgress) && <Spinner />}+ </span>+ }+ checked={heatmap.clickmapsEnabled}+ onChange={(enabled) => sendHeatmapCommand({ type: 'set-clickmaps-enabled', enabled })}+ data-attr="toolbar-extension-clickmap-toggle"+ />+ {heatmap.clickmapsEnabled && (+ <>+ <div className="text-xs text-secondary">+ Clickmaps use autocapture events. They match clicks to the elements on this page. Hold{' '}+ <kbd>shift</kbd> to click the page under the clickmap.+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <LemonButton+ size="small"+ type="secondary"+ icon={heatmap.loadingAllElementStats ? <Spinner textColored /> : <IconSync />}+ active={heatmap.loadingAllElementStats}+ disabledReason={+ heatmap.canLoadMoreElementStats || heatmap.loadingAllElementStats+ ? null+ : 'All elements in this date range are loaded'+ }+ onClick={() =>+ sendHeatmapCommand({+ type: heatmap.loadingAllElementStats+ ? 'stop-loading-all-element-stats'+ : 'load-all-element-stats',+ })+ }+ data-attr="toolbar-extension-clickmap-load-all"+ >+ {heatmap.loadingAllElementStats ? 'Stop loading' : 'Load all'}+ </LemonButton>+ <LemonSwitch+ className="flex-1"+ size="small"+ bordered+ checked={heatmap.matchLinksByHref}+ onChange={(matchLinksByHref) =>+ sendHeatmapCommand({ type: 'set-match-links-by-href', matchLinksByHref })+ }+ label="Match links by their target URL"+ />+ </div>+ <div className="text-xs">+ <span translate="no">+ {heatmap.countedElements.length} elements / {heatmap.clickCount} clicks+ </span>+ {heatmap.processingProgress && (+ <span className="text-secondary" translate="no">+ {' '}+ (processing {heatmap.processingProgress.processed.toLocaleString()}/+ {heatmap.processingProgress.total.toLocaleString()})+ </span>+ )}+ </div>+ {heatmap.canLoadMoreElementStats && heatmap.loadedElementStatsCount > 0 && (+ <div className="text-xs text-secondary">+ Showing the top {heatmap.loadedElementStatsCount.toLocaleString()} element groups by+ click count. Load all to include the whole date range.+ </div>+ )}+ <ExtensionInspectedElement />+ <div className="flex flex-col">+ {heatmap.countedElements.length === 0 ? (+ <div className="text-secondary text-xs">+ {heatmap.clickmapLoading ? 'Loading clicks…' : 'No clicked elements found.'}+ </div>+ ) : (+ heatmap.countedElements.map((element, index) => (+ <LemonButton+ key={index}+ size="small"+ fullWidth+ onClick={() => sendHeatmapCommand({ type: 'select-counted-element', index })}+ onMouseEnter={() =>+ sendHeatmapCommand({ type: 'highlight-counted-element', index })+ }+ onMouseLeave={() =>+ sendHeatmapCommand({ type: 'highlight-counted-element', index: null })+ }+ >+ <span className="flex flex-1 min-w-0 justify-between gap-2">+ <span className="truncate">+ {index + 1}. {element.text || <code><{element.tagName}></code>}+ </span>+ <span className="shrink-0" translate="no">+ {element.count} clicks+ </span>+ </span>+ </LemonButton>+ ))+ )}+ </div>+ </>+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx b/frontend/src/toolbar/extension/ExtensionInspectedElement.tsxnew file mode 100644index 000000000000..22d4b50d2dbd--- /dev/null+++ b/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx@@ -0,0 +1,80 @@+import { useActions, useValues } from 'kea'++import { IconX } from '@posthog/icons'++import { ElementClickStats } from 'lib/components/heatmaps/ElementClickStats'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Link } from 'lib/lemon-ui/Link'++import { SelectorQualityWarning } from '~/toolbar/elements/SelectorQualityWarning'+import { urls } from '~/toolbar/urls'++import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'+import { extensionPanelLogic } from './extensionPanelLogic'++export function ExtensionInspectedElement(): JSX.Element | null {+ const { inspect, heatmap } = useValues(extensionPageToolbarConnectionLogic)+ const { sendCommand } = useActions(extensionPageToolbarConnectionLogic)+ const { projectUrl } = useValues(extensionPanelLogic)+ const element = inspect?.element+ if (!element) {+ return null+ }+ const { actionStep, stats, actions } = element++ return (+ <div className="flex flex-col gap-2 border rounded p-2 text-xs">+ <div className="flex items-start gap-1">+ <div className="flex-1 min-w-0 flex flex-col gap-1">+ <div className="font-semibold">{inspect.isSelected ? 'Selected element' : 'Hovered element'}</div>+ <code className="break-all" translate="no">+ {actionStep?.selector || `<${element.tagName}>`}+ </code>+ {actionStep?.text && <div className="text-secondary truncate">Text: {actionStep.text}</div>}+ {actionStep?.href && (+ <div className="text-secondary truncate" translate="no">+ Link: {actionStep.href}+ </div>+ )}+ <SelectorQualityWarning selector={actionStep?.selector} compact />+ </div>+ {inspect.isSelected && (+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ tooltip="Clear the selection"+ onClick={() => sendCommand({ tool: 'inspect', command: { type: 'clear-selected-element' } })}+ data-attr="toolbar-extension-clear-inspected-element"+ />+ )}+ </div>+ {stats && (+ <ElementClickStats+ count={stats.count}+ totalCount={heatmap?.clickCount ?? 0}+ rank={stats.rank}+ clickCount={stats.clickCount}+ rageclickCount={stats.rageclickCount}+ deadclickCount={stats.deadclickCount}+ />+ )}+ <div className="flex flex-col gap-1">+ <div className="font-semibold">Actions ({actions.length})</div>+ {actions.length === 0 ? (+ <div className="text-secondary">No actions include this element.</div>+ ) : (+ actions.map((action) => (+ <Link+ key={action.id}+ to={projectUrl(urls.action(action.id))}+ target="_blank"+ className="truncate"+ >+ {action.name || `Action ${action.id}`}+ </Link>+ ))+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/toolbar/extension/ExtensionPageToolbar.tsx b/frontend/src/toolbar/extension/ExtensionPageToolbar.tsxnew file mode 100644index 000000000000..ec7ab1808781--- /dev/null+++ b/frontend/src/toolbar/extension/ExtensionPageToolbar.tsx@@ -0,0 +1,45 @@+import { useActions, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { Spinner } from 'lib/lemon-ui/Spinner'++import { extensionAuthLogic } from './extensionAuthLogic'+import { ExtensionFeatureList } from './ExtensionFeatureList'+import { ExtensionPageToolbarTools } from './ExtensionPageToolbarTools'++export function ExtensionPageToolbar({ origin }: { origin: string }): JSX.Element {+ const { authStatus } = useValues(extensionAuthLogic)+ const { authenticate } = useActions(extensionAuthLogic)++ if (authStatus === 'authenticated') {+ return <ExtensionPageToolbarTools origin={origin} />+ }+ if (authStatus === 'signed-out' || authStatus === 'failed') {+ return (+ <>+ <LemonBanner+ type={authStatus === 'failed' ? 'warning' : 'info'}+ action={{+ children: 'Connect',+ onClick: () => authenticate(true),+ 'data-attr': 'toolbar-extension-connect',+ }}+ >+ {authStatus === 'failed'+ ? "Couldn't connect the toolbar to this project. Connect again, and finish any step PostHog shows in the new tab."+ : 'Connect the toolbar to this project to use its tools on this page.'}+ </LemonBanner>+ <ExtensionFeatureList origin={origin} />+ </>+ )+ }+ return (+ <>+ <div className="flex items-center gap-2 text-secondary text-xs">+ <Spinner />+ Connecting the toolbar to this project…+ </div>+ <ExtensionFeatureList origin={origin} />+ </>+ )+}diff --git a/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx b/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsxnew file mode 100644index 000000000000..2c98824a57ce--- /dev/null+++ b/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx@@ -0,0 +1,130 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { IconExternal, IconX } from '@posthog/icons'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'++import { ExtensionFeatureList } from './ExtensionFeatureList'+import { ExtensionHeatmapMenu } from './ExtensionHeatmapMenu'+import { ExtensionInspectedElement } from './ExtensionInspectedElement'+import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'+import { PAGE_TOOLS, PageToolDefinition, PageToolMode } from './extensionPageTools'+import { extensionPanelLogic } from './extensionPanelLogic'+import { usePageToolDisabledReason } from './usePageToolDisabledReason'++type PanelTool = PageToolDefinition & { mode: PageToolMode }++const PANEL_TOOLS = PAGE_TOOLS.filter((tool): tool is PanelTool => !!tool.mode)++function ToolBody({ mode }: { mode: PageToolMode }): JSX.Element {+ switch (mode) {+ case 'inspect':+ return (+ <>+ <div className="text-xs text-secondary">+ Hover an element on the page to see its selector and actions, or click it to keep it selected.+ Press Esc to stop.+ </div>+ <ExtensionInspectedElement />+ </>+ )+ case 'heatmap':+ return <ExtensionHeatmapMenu />+ }+}++function ToolHeader({ tool }: { tool: PanelTool }): JSX.Element {+ const { openFeature } = useActions(extensionPanelLogic)+ const { setMode } = useActions(extensionPageToolbarConnectionLogic)+ const { feature } = tool++ return (+ <div className="flex items-center gap-1">+ <h3 className="m-0 flex-1 truncate text-sm font-semibold">{tool.label}</h3>+ {feature && (+ <LemonButton+ size="xsmall"+ icon={<IconExternal />}+ tooltip={`Open ${tool.label.toLowerCase()} in PostHog`}+ onClick={() => openFeature(feature.key, feature.path)}+ data-attr={`toolbar-extension-feature-${feature.key}`}+ />+ )}+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ tooltip={`Close ${tool.label.toLowerCase()}`}+ onClick={() => setMode('none')}+ data-attr="toolbar-extension-close-tool"+ />+ </div>+ )+}++export function ExtensionPageToolbarTools({ origin }: { origin: string }): JSX.Element {+ useMountedLogic(extensionPageToolbarConnectionLogic)+ const { mode, connectionStatus } = useValues(extensionPageToolbarConnectionLogic)+ const { setMode, connectPage } = useActions(extensionPageToolbarConnectionLogic)+ const disabledReason = usePageToolDisabledReason()+ const activeTool = PANEL_TOOLS.find((tool) => tool.mode === mode)++ return (+ <div className="flex flex-col gap-2">+ <LemonSegmentedButton+ fullWidth+ size="small"+ value={activeTool?.mode}+ onChange={(toolMode) => setMode(toolMode === mode ? 'none' : toolMode)}+ options={PANEL_TOOLS.map((tool) => ({+ value: tool.mode,+ icon: tool.icon,+ tooltip: tool.label,+ disabledReason: disabledReason(tool) ?? undefined,+ 'data-attr': `toolbar-extension-mode-${tool.mode}`,+ }))}+ />+ {connectionStatus === 'failed' ? (+ <LemonBanner+ type="warning"+ action={{+ children: 'Try again',+ onClick: connectPage,+ 'data-attr': 'toolbar-extension-reconnect',+ }}+ >+ The extension couldn't reach this page. Reload the page and try again.+ </LemonBanner>+ ) : activeTool ? (+ <>+ <ToolHeader tool={activeTool} />+ <ToolBody mode={activeTool.mode} />+ </>+ ) : (+ <>+ <div className="flex flex-col gap-1">+ {PANEL_TOOLS.map((tool) => (+ <LemonButton+ key={tool.mode}+ fullWidth+ icon={tool.icon}+ disabledReason={disabledReason(tool)}+ onClick={() => setMode(tool.mode)}+ data-attr={`toolbar-extension-open-${tool.mode}`}+ >+ <span className="flex min-w-0 flex-col">+ <span>{tool.label}</span>+ <span className="text-xs font-normal text-secondary whitespace-normal">+ {tool.description}+ </span>+ </span>+ </LemonButton>+ ))}+ </div>+ <ExtensionFeatureList origin={origin} />+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/toolbar/extension/ExtensionPanel.tsx b/frontend/src/toolbar/extension/ExtensionPanel.tsxindex 7c3eaa449e16..56370dcad9c6 100644--- a/frontend/src/toolbar/extension/ExtensionPanel.tsx+++ b/frontend/src/toolbar/extension/ExtensionPanel.tsx@@ -6,7 +6,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner'import { urls } from '~/toolbar/urls'-import { ExtensionFeatureList } from './ExtensionFeatureList'+import { ExtensionPageToolbar } from './ExtensionPageToolbar'import { extensionPanelLogic } from './extensionPanelLogic'import { ExtensionPanelSettings } from './ExtensionPanelSettings'import type { ExtensionPanelState, UnsupportedPageReason } from './extensionPanelState'@@ -90,7 +90,7 @@ function ExtensionPanelBody({ panelState }: { panelState: ExtensionPanelState })</LemonBanner>)case 'ready':- return <ExtensionFeatureList origin={panelState.origin} />+ return <ExtensionPageToolbar origin={panelState.origin} />}}diff --git a/frontend/src/toolbar/extension/README.md b/frontend/src/toolbar/extension/README.mdindex af236d59c13a..5ae61db520ec 100644--- a/frontend/src/toolbar/extension/README.md+++ b/frontend/src/toolbar/extension/README.md@@ -36,3 +36,69 @@ After a rebuild, click the reload icon on the extension card, then close and opeFirefox removes a temporary add-on when it quits.A permanent install needs an add-on signed by addons.mozilla.org.++## Permissions++| Permission | Why |+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `http://*/*`, `https://*/*` | The side panel reads the URL of the active tab and runs scripts in it when the user switches tabs. The same grant calls the PostHog API with your PostHog login, on Cloud and on a self-hosted host. |+| `scripting` | Injects the content script, and reads the page's posthog-js settings in the page's world. |+| `storage` | Saves the PostHog host and the toolbar's OAuth tokens for each project. |+| `sidePanel` (Chrome) | Shows the side panel. |++The manifest also lists `content.css` and its fonts in `web_accessible_resources`, because the content script links them into its shadow root on the page.++### Site access++Both browsers let the user take site access back from an extension.+When the extension can't reach the PostHog host, the panel asks for access to it.+When it can't reach the site, the panel asks the user to reload the page and try again.++## How the page tools work++The page tools run the floating toolbar's own logics in the content script, and draw its overlays in the content script's shadow root:++- `elementsLogic` for Inspect.+- `heatmapToolbarMenuLogic`, `heatmapDataLogic` and `heatmapCaptureLogic` for the heatmap.++The panel shows their controls. It sends each command to the tool it belongs to, and gets their state back through a port.++```mermaid+flowchart LR+ panel[Side panel] -- commands --> port((port))+ port -- state, tokens --> panel+ port --- content[Content script]+ content -- toolbarConfigLogic with the extension's tokens --> logics[Toolbar logics]+ logics -- bearer token --> api[PostHog API]+ logics -- overlays --> page[(Page)]+ content -- window.postMessage --- agent[Page agent]+ agent -- posthog-js --> page+```++- **Sign-in.** The panel calls PostHog with the PostHog session cookie for the checks it runs before the page tools.+ A session cookie sent from an extension page fails Django's CSRF origin check on writes, so the page tools use the toolbar's OAuth flow instead.+ When the panel first shows the tools for a project, it opens `/toolbar_oauth/authorize/` in a background tab with the page as the redirect.+ It reads the code from that tab's URL hash, closes the tab, and exchanges the code with its own PKCE verifier.+ The tokens are stored per PostHog host and project.+ If that fails, or the tokens expire again, the panel shows **Connect**, which runs the same flow in a tab the user can see.+- **Refresh.** The content script refreshes the tokens on a 401 like the floating toolbar does, and sends the new tokens to the panel to store.+- **Storage.** In extension mode `toolbarConfigLogic` doesn't read the page's URL hash or write the page's `localStorage`, so it leaves the floating toolbar's session on the page alone.+- **State.** Each tool's state is one memoized slice. The page posts only the slices that changed, at most every 100 ms, so a panel component re-renders only for its own tool.+- **posthog-js.** The content script can't reach the page's `window.posthog`, so the panel injects `page-agent.js` into the page's world with the content script.+ The content script asks the page agent for the page's posthog-js settings when the page tools start, and stands in for posthog-js with them.+ When a page loads posthog-js later, the page agent reports it, and the page tools start again with it.+- **Injection.** The panel injects the content script on first use. The script answers a ping, so the panel doesn't inject it twice.+- **Navigation.** When a single-page app changes the URL, the port stays open and the page tools follow the new URL.+ A new document closes the port. The panel then connects again and turns the mode the user picked back on.+ The page tools stop 30 seconds after the last panel disconnects, so a quick reopen keeps their data.++## Check the flows by hand++Use a site in the project's authorized URLs. Do these steps in Chrome and in Firefox.++1. Open the panel on the site. The panel connects the toolbar to the project: a tab opens and closes by itself.+2. Click the Inspect icon and hover an element. The panel shows its selector and actions. Click the element to keep it selected.+3. Click **Heatmap**. Check the clickmap counts, the heatmap canvas, the scroll depth type, **Filter to area**, **Load all**, and **Save to PostHog**.+4. Reload the page. The heatmap comes back.+5. Switch to a tab with another site, then back. The panel shows the state of each tab.+6. Switch the project in the panel. The panel connects the toolbar to the new project.diff --git a/frontend/src/toolbar/extension/content.tsx b/frontend/src/toolbar/extension/content.tsxnew file mode 100644index 000000000000..a78057f32e83--- /dev/null+++ b/frontend/src/toolbar/extension/content.tsx@@ -0,0 +1,54 @@+import '~/styles'+import '~/toolbar/styles.scss'++import { resetContext } from 'kea'+import { disposablesPlugin } from 'kea-disposables'+import { formsPlugin } from 'kea-forms'+import { loadersPlugin } from 'kea-loaders'+import { localStoragePlugin } from 'kea-localstorage'+import { subscriptionsPlugin } from 'kea-subscriptions'+import { waitForPlugin } from 'kea-waitfor'+import { windowValuesPlugin } from 'kea-window-values'++import { TOOLBAR_EXTENSION_ID, TOOLBAR_ROOT_ATTRIBUTE } from '~/toolbar/utils'++import { answerContentScriptPing } from './extensionBrowser'+import { PageToolbarHost } from './pageToolbarHost'++const INSTALLED_FLAG = '__posthogToolbarExtensionContent'++function resetPageToolbarContext(): void {+ // The prefix keeps the settings the toolbar logics persist in the page's localStorage apart from the floating toolbar's.+ resetContext({+ plugins: [+ disposablesPlugin,+ localStoragePlugin({ prefix: 'posthogToolbarExtension' }),+ windowValuesPlugin({ window }),+ formsPlugin,+ loadersPlugin,+ subscriptionsPlugin,+ waitForPlugin,+ ],+ })+}++function install(): void {+ resetPageToolbarContext()+ const host = document.createElement('div')+ host.id = TOOLBAR_EXTENSION_ID+ host.setAttribute(TOOLBAR_ROOT_ATTRIBUTE, '')+ // ph-no-capture keeps the page's own posthog-js from recording the overlay.+ host.className = 'ph-no-capture'+ host.style.cssText =+ 'position:absolute;top:0;left:0;width:100%;height:100%;overflow:visible;z-index:2147483647;pointer-events:none'+ const shadowRoot = host.attachShadow({ mode: 'open' })+ document.documentElement.appendChild(host)+ new PageToolbarHost(shadowRoot, resetPageToolbarContext).listen()+ answerContentScriptPing()+}++const contentGlobal = globalThis as unknown as Record<string, boolean | undefined>+if (!contentGlobal[INSTALLED_FLAG]) {+ contentGlobal[INSTALLED_FLAG] = true+ install()+}diff --git a/frontend/src/toolbar/extension/extensionAuthLogic.ts b/frontend/src/toolbar/extension/extensionAuthLogic.tsnew file mode 100644index 000000000000..8564b5883bcd--- /dev/null+++ b/frontend/src/toolbar/extension/extensionAuthLogic.ts@@ -0,0 +1,200 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'++import type { UserApi } from '~/generated/core/api.schemas'+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'++import { getStoredTokens, setStoredTokens } from './extensionBrowser'+import { authenticateToolbar } from './extensionOAuth'+import { extensionPanelLogic } from './extensionPanelLogic'+import type { ExtensionPanelState } from './extensionPanelState'+import type { PageToolbarTokens } from './pageToolbarBridge'++export type ToolbarAuthStatus = 'loading' | 'signed-out' | 'authenticating' | 'authenticated' | 'failed'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionAuthLogicValues {+ panelState: ExtensionPanelState // extensionPanelLogic+ tabUrl: string | null | undefined // extensionPanelLogic+ uiHost: string // extensionPanelLogic+ user: UserApi | null // extensionPanelLogic+ authStatus: ToolbarAuthStatus+ authenticating: boolean+ autoAuthenticationKey: string | null+ currentKey: string | null+ failed: boolean+ loadedKey: string | null+ tokens: PageToolbarTokens | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionAuthLogicActions {+ authenticate: (interactive: boolean) => {+ interactive: boolean+ }+ authenticateFailure: () => {+ value: true+ }+ loadTokens: (key: string) => {+ key: string+ }+ setTokens: (+ key: string,+ tokens: PageToolbarTokens | null+ ) => {+ key: string+ tokens: PageToolbarTokens | null+ }+ tokensExpired: () => {+ value: true+ }+ updateTokens: (tokens: PageToolbarTokens) => {+ tokens: PageToolbarTokens+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionAuthLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ currentKey: (uiHost: string, user: UserApi | null) => string | null+ authStatus: (+ currentKey: string | null,+ loadedKey: string | null,+ tokens: PageToolbarTokens | null,+ authenticating: boolean,+ failed: boolean+ ) => ToolbarAuthStatus+ autoAuthenticationKey: (+ currentKey: string | null,+ authStatus: ToolbarAuthStatus,+ panelState: ExtensionPanelState+ ) => string | null+ }+}++export type extensionAuthLogicType = MakeLogicType<+ extensionAuthLogicValues,+ extensionAuthLogicActions,+ Record<string, any>,+ extensionAuthLogicMeta+>++/** The page tools use OAuth tokens, because a session cookie sent from an extension page fails Django's CSRF check. */+export const extensionAuthLogic = kea<extensionAuthLogicType>([+ path(['toolbar', 'extension', 'extensionAuthLogic']),+ connect(() => ({+ values: [extensionPanelLogic, ['uiHost', 'user', 'tabUrl', 'panelState']],+ })),+ actions({+ loadTokens: (key: string) => ({ key }),+ setTokens: (key: string, tokens: PageToolbarTokens | null) => ({ key, tokens }),+ updateTokens: (tokens: PageToolbarTokens) => ({ tokens }),+ tokensExpired: true,+ authenticate: (interactive: boolean) => ({ interactive }),+ authenticateFailure: true,+ }),+ reducers({+ loadedKey: [null as string | null, { setTokens: (_, { key }) => key }],+ tokens: [+ null as PageToolbarTokens | null,+ {+ loadTokens: () => null,+ setTokens: (_, { tokens }) => tokens,+ updateTokens: (_, { tokens }) => tokens,+ tokensExpired: () => null,+ },+ ],+ authenticating: [false, { authenticate: () => true, setTokens: () => false, authenticateFailure: () => false }],+ failed: [false, { authenticate: () => false, authenticateFailure: () => true, loadTokens: () => false }],+ }),+ selectors({+ currentKey: [+ (s) => [s.uiHost, s.user],+ (uiHost: string, user: UserApi | null): string | null => (user ? `${uiHost}|${user.team.id}` : null),+ ],+ authStatus: [+ (s) => [s.currentKey, s.loadedKey, s.tokens, s.authenticating, s.failed],+ (+ currentKey: string | null,+ loadedKey: string | null,+ tokens: PageToolbarTokens | null,+ authenticating: boolean,+ failed: boolean+ ): ToolbarAuthStatus => {+ if (authenticating) {+ return 'authenticating'+ }+ if (!currentKey || currentKey !== loadedKey) {+ return 'loading'+ }+ if (tokens) {+ return 'authenticated'+ }+ return failed ? 'failed' : 'signed-out'+ },+ ],+ autoAuthenticationKey: [+ (s) => [s.currentKey, s.authStatus, s.panelState],+ (+ currentKey: string | null,+ authStatus: ToolbarAuthStatus,+ panelState: ExtensionPanelState+ ): string | null => (authStatus === 'signed-out' && panelState.kind === 'ready' ? currentKey : null),+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ loadTokens: async ({ key }) => {+ const tokens = await getStoredTokens(key)+ if (values.currentKey === key) {+ actions.setTokens(key, tokens)+ }+ },+ updateTokens: ({ tokens }) => {+ if (values.currentKey) {+ void setStoredTokens(values.currentKey, tokens)+ }+ },+ tokensExpired: () => {+ if (values.currentKey) {+ void setStoredTokens(values.currentKey, null)+ }+ },+ authenticate: async ({ interactive }) => {+ const key = values.currentKey+ const pageUrl = values.tabUrl+ if (!key || !pageUrl) {+ actions.authenticateFailure()+ return+ }+ cache.autoAuthenticatedKeys = (cache.autoAuthenticatedKeys ?? new Set<string>()).add(key)+ try {+ const tokens = await authenticateToolbar({ uiHost: values.uiHost, pageUrl, interactive })+ await setStoredTokens(key, tokens)+ // pinned: analytics event name+ toolbarPosthogJS.capture('toolbar extension authenticated', { status: 'success', interactive })+ actions.setTokens(key, tokens)+ } catch (error) {+ toolbarPosthogJS.capture('toolbar extension authenticated', {+ status: 'error',+ interactive,+ error: String(error),+ })+ actions.authenticateFailure()+ }+ },+ })),+ subscriptions(({ actions, cache }) => ({+ currentKey: (currentKey: string | null) => {+ if (currentKey) {+ actions.loadTokens(currentKey)+ }+ },+ autoAuthenticationKey: (key: string | null) => {+ // Connects by itself once per project. After a failure, or when the tokens expire again, the user decides.+ const autoAuthenticatedKeys: Set<string> | undefined = cache.autoAuthenticatedKeys+ if (key && !autoAuthenticatedKeys?.has(key)) {+ actions.authenticate(false)+ }+ },+ })),+])diff --git a/frontend/src/toolbar/extension/extensionBrowser.ts b/frontend/src/toolbar/extension/extensionBrowser.tsindex e54ce0af92eb..d60290992349 100644--- a/frontend/src/toolbar/extension/extensionBrowser.ts+++ b/frontend/src/toolbar/extension/extensionBrowser.ts@@ -1,10 +1,19 @@+import { PAGE_TOOLBAR_PORT, PageToolbarTokens } from './pageToolbarBridge'+// Firefox and Chrome both expose the promise-based `chrome.*` namespace to Manifest V3 extensions.-// Only the calls the side panel and the background script make are typed here.+// Only the calls the side panel, the background script and the content script make are typed here.interface ExtensionTab {id?: numberurl?: string}+// Returning true keeps sendResponse open for an async response.+type RuntimeMessageListener = (+ message: unknown,+ sender: unknown,+ sendResponse: (response: unknown) => void+) => boolean | void+interface ExtensionPermissions {origins: string[]}@@ -19,6 +28,14 @@ interface TabChangeInfo {status?: string}+export interface ExtensionPort {+ name: string+ postMessage: (message: unknown) => void+ disconnect: () => void+ onMessage: ExtensionEvent<(message: unknown) => void>+ onDisconnect: ExtensionEvent<() => void>+}+interface ExtensionEvent<Listener> {addListener: (listener: Listener) => voidremoveListener: (listener: Listener) => void@@ -27,8 +44,12 @@ interface ExtensionEvent<Listener> {interface ExtensionBrowserApi {tabs: {query: (query: { active: true; windowId?: number; currentWindow?: true }) => Promise<ExtensionTab[]>- create: (properties: { url: string }) => Promise<unknown>+ create: (properties: { url: string; active?: boolean }) => Promise<ExtensionTab>+ remove: (tabId: number) => Promise<void>+ connect: (tabId: number, connectInfo: { name: string }) => ExtensionPort+ sendMessage: (tabId: number, message: unknown) => Promise<unknown>onActivated: ExtensionEvent<(activeInfo: TabActiveInfo) => void>+ onRemoved: ExtensionEvent<(tabId: number) => void>onUpdated: ExtensionEvent<(tabId: number,@@ -46,6 +67,22 @@ interface ExtensionBrowserApi {set: (items: Record<string, unknown>) => Promise<void>}}+ scripting: {+ executeScript: <Args extends unknown[], Result>(injection: {+ target: { tabId: number }+ files?: string[]+ world?: 'ISOLATED' | 'MAIN'+ func?: (...args: Args) => Result+ args?: Args+ }) => Promise<{ result?: Result }[]>+ }+ runtime: {+ onMessage: {+ addListener: (listener: RuntimeMessageListener) => void+ }+ onConnect: ExtensionEvent<(port: ExtensionPort) => void>+ getURL: (path: string) => string+ }permissions: {contains: (permissions: ExtensionPermissions) => Promise<boolean>request: (permissions: ExtensionPermissions) => Promise<boolean>@@ -68,6 +105,8 @@ const extensionBrowser = ((globalThis as unknown as { browser?: ExtensionBrowser// pinned: extension storage key, renaming it resets the saved PostHog hostconst UI_HOST_STORAGE_KEY = 'posthogUiHost'+const CONTENT_SCRIPT_FILE = 'content.js'+export function openPanelFromToolbarButton(): void {if (extensionBrowser.sidePanel) {void extensionBrowser.sidePanel.setPanelBehavior({ openPanelOnActionClick: true })@@ -140,6 +179,112 @@ export async function hasHostPermission(uiHost: string): Promise<boolean> {}/** Must run inside the click handler: browsers show the permission prompt only for a user gesture. */-export async function requestHostPermission(uiHost: string): Promise<boolean> {- return await extensionBrowser.permissions.request(originPattern(uiHost))+export async function requestHostPermission(url: string): Promise<boolean> {+ return await extensionBrowser.permissions.request(originPattern(url))+}++// pinned: extension message, the panel and an already injected content script must agree on it+const CONTENT_SCRIPT_PING = 'posthog-toolbar-extension-ping'++export async function ensureContentScript(tabId: number): Promise<void> {+ const installed = await extensionBrowser.tabs.sendMessage(tabId, CONTENT_SCRIPT_PING).then(+ (response) => response === true,+ () => false+ )+ if (!installed) {+ await extensionBrowser.scripting.executeScript({ target: { tabId }, files: [CONTENT_SCRIPT_FILE] })+ }+}++export function answerContentScriptPing(): void {+ extensionBrowser.runtime.onMessage.addListener((message, _sender, sendResponse) => {+ if (message === CONTENT_SCRIPT_PING) {+ sendResponse(true)+ }+ })+}++export function extensionFileUrl(path: string): string {+ return extensionBrowser.runtime.getURL(path)+}++export function connectToPageToolbar(tabId: number): ExtensionPort {+ return extensionBrowser.tabs.connect(tabId, { name: PAGE_TOOLBAR_PORT })+}++export function onPageToolbarConnect(handler: (port: ExtensionPort) => void): void {+ extensionBrowser.runtime.onConnect.addListener((port) => {+ if (port.name === PAGE_TOOLBAR_PORT) {+ handler(port)+ }+ })+}++const PAGE_AGENT_FILE = 'page-agent.js'++/** Runs the page agent in the page's own world, where it can call the page's posthog-js for the content script. */+export async function injectPageAgent(tabId: number): Promise<void> {+ await extensionBrowser.scripting.executeScript({ target: { tabId }, world: 'MAIN', files: [PAGE_AGENT_FILE] })+}++export async function waitForTabUrl(+ url: string,+ matches: (tabUrl: string) => boolean,+ { timeoutMs, active }: { timeoutMs: number; active: boolean }+): Promise<string> {+ const tab = await extensionBrowser.tabs.create({ url, active })+ const tabId = tab.id+ if (tabId === undefined) {+ throw new Error('The browser did not open the tab')+ }+ return await new Promise((resolve, reject) => {+ const finish = (result: { url: string } | { error: Error }): void => {+ clearTimeout(timeout)+ extensionBrowser.tabs.onUpdated.removeListener(onUpdated)+ extensionBrowser.tabs.onRemoved.removeListener(onRemoved)+ if ('url' in result) {+ void extensionBrowser.tabs.remove(tabId).catch(() => undefined)+ resolve(result.url)+ } else {+ reject(result.error)+ }+ }+ const onUpdated = (updatedTabId: number, changeInfo: TabChangeInfo): void => {+ if (updatedTabId === tabId && changeInfo.url && matches(changeInfo.url)) {+ finish({ url: changeInfo.url })+ }+ }+ const onRemoved = (removedTabId: number): void => {+ if (removedTabId === tabId) {+ finish({ error: new Error('The tab closed before it finished') })+ }+ }+ const timeout = setTimeout(() => {+ void extensionBrowser.tabs.remove(tabId).catch(() => undefined)+ finish({ error: new Error('The tab did not finish in time') })+ }, timeoutMs)+ extensionBrowser.tabs.onUpdated.addListener(onUpdated)+ extensionBrowser.tabs.onRemoved.addListener(onRemoved)+ })+}++// pinned: extension storage key, renaming it signs every project out of the toolbar+const TOKENS_STORAGE_KEY = 'posthogToolbarTokens'++export async function getStoredTokens(key: string): Promise<PageToolbarTokens | null> {+ const stored = await extensionBrowser.storage.local.get(TOKENS_STORAGE_KEY)+ const tokensByKey = stored[TOKENS_STORAGE_KEY] as Record<string, PageToolbarTokens> | undefined+ const tokens = tokensByKey?.[key]+ return tokens && typeof tokens.accessToken === 'string' && typeof tokens.clientId === 'string' ? tokens : null+}++export async function setStoredTokens(key: string, tokens: PageToolbarTokens | null): Promise<void> {+ const stored = await extensionBrowser.storage.local.get(TOKENS_STORAGE_KEY)+ const tokensByKey = { ...(stored[TOKENS_STORAGE_KEY] as Record<string, PageToolbarTokens> | undefined) }+ if (tokens) {+ tokensByKey[key] = tokens+ } else {+ delete tokensByKey[key]+ }+ await extensionBrowser.storage.local.set({ [TOKENS_STORAGE_KEY]: tokensByKey })}diff --git a/frontend/src/toolbar/extension/extensionFeatures.ts b/frontend/src/toolbar/extension/extensionFeatures.tsdeleted file mode 100644index df40feda25a5..000000000000--- a/frontend/src/toolbar/extension/extensionFeatures.ts+++ /dev/null@@ -1,52 +0,0 @@-import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'--import { urls } from '~/toolbar/urls'-import { AvailableFeature } from '~/types'--// pinned: sent as the `feature` property of `toolbar extension feature opened`-export type ExtensionFeatureKey = 'heatmaps' | 'actions' | 'feature-flags' | 'experiments' | 'web-vitals'--export interface ExtensionFeatureEntryPoint {- key: ExtensionFeatureKey- label: string- description: string- /** PostHog app path, relative to the project. */- path: string- /** The plan gate the floating toolbar applies to this feature. */- gate?: { feature: AvailableFeature; rolloutFlag: FeatureFlagKey }-}--/** The floating toolbar's menus, in toolbar order. */-export const EXTENSION_FEATURE_ENTRY_POINTS: ExtensionFeatureEntryPoint[] = [- {- key: 'heatmaps',- label: 'Heatmaps',- description: 'See where people click and how far they scroll',- path: urls.heatmaps(),- gate: { feature: AvailableFeature.TOOLBAR_HEATMAPS, rolloutFlag: FEATURE_FLAGS.TOOLBAR_PAID_HEATMAPS },- },- {- key: 'actions',- label: 'Actions',- description: 'Define actions from elements on your pages',- path: urls.actions(),- },- {- key: 'feature-flags',- label: 'Feature flags',- description: 'Review and override flags',- path: urls.featureFlags(),- },- {- key: 'web-vitals',- label: 'Web vitals',- description: 'Check page load performance',- path: urls.webAnalyticsWebVitals(),- },- {- key: 'experiments',- label: 'Experiments',- description: 'Create and review web experiments',- path: urls.experiments(),- },-]diff --git a/frontend/src/toolbar/extension/extensionOAuth.ts b/frontend/src/toolbar/extension/extensionOAuth.tsnew file mode 100644index 000000000000..8df7b2837c93--- /dev/null+++ b/frontend/src/toolbar/extension/extensionOAuth.ts@@ -0,0 +1,57 @@+import { generatePKCE, parseToolbarAuthHash, requestOAuthTokens } from '~/toolbar/utils'++import { waitForTabUrl } from './extensionBrowser'+import type { PageToolbarTokens } from './pageToolbarBridge'++// A background tab normally redirects back within a few seconds. A tab the user watches can stop on a login or+// consent page, so it gets longer.+const BACKGROUND_AUTH_TIMEOUT_MS = 20_000+const INTERACTIVE_AUTH_TIMEOUT_MS = 180_000++class OAuthExchangeError extends Error {}++function pageUrlWithoutHash(pageUrl: string): string {+ const url = new URL(pageUrl)+ url.hash = ''+ return url.toString()+}++/**+ * Runs the floating toolbar's OAuth flow in a separate tab. PostHog redirects that tab to the page with the code in the+ * URL hash, so the page must be one of the project's authorized URLs. The extension keeps the PKCE verifier, reads the+ * code from the tab's URL, and exchanges it for tokens.+ */+export async function authenticateToolbar({+ uiHost,+ pageUrl,+ interactive,+}: {+ uiHost: string+ pageUrl: string+ interactive: boolean+}): Promise<PageToolbarTokens> {+ const { verifier, challenge } = await generatePKCE()+ const authorizeUrl = `${uiHost}/toolbar_oauth/authorize/?${new URLSearchParams({+ redirect: pageUrlWithoutHash(pageUrl),+ code_challenge: challenge,+ })}`+ const callbackUrl = await waitForTabUrl(authorizeUrl, (url) => !!parseToolbarAuthHash(new URL(url).hash), {+ active: interactive,+ timeoutMs: interactive ? INTERACTIVE_AUTH_TIMEOUT_MS : BACKGROUND_AUTH_TIMEOUT_MS,+ })+ const authParams = parseToolbarAuthHash(new URL(callbackUrl).hash)+ if (!authParams) {+ throw new OAuthExchangeError('PostHog returned no authorization code')+ }++ const { status, accessToken, refreshToken } = await requestOAuthTokens({+ uiHost,+ code: authParams.code,+ clientId: authParams.clientId,+ verifier,+ })+ if (!accessToken) {+ throw new OAuthExchangeError(`The token exchange failed with status ${status}`)+ }+ return { accessToken, refreshToken, clientId: authParams.clientId }+}diff --git a/frontend/src/toolbar/extension/extensionPageHeatmapLogic.ts b/frontend/src/toolbar/extension/extensionPageHeatmapLogic.tsnew file mode 100644index 000000000000..14b06b1e4bf6--- /dev/null+++ b/frontend/src/toolbar/extension/extensionPageHeatmapLogic.ts@@ -0,0 +1,492 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import type { PostHog } from 'posthog-js'++import type {+ CommonFilters,+ HeatmapFilters,+ HeatmapFixedPositionMode,+ ScrollDepthPosthogJsError,+} from 'lib/components/heatmaps/types'++import { elementsLogic } from '~/toolbar/elements/elementsLogic'+import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'+import { heatmapCaptureLogic } from '~/toolbar/stats/heatmapCaptureLogic'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import type { CountedHTMLElement } from '~/toolbar/types'++import type { CaptureProgress, CaptureSummary } from '../stats/heatmapCaptureLogic'+import type { HeatmapSaveResult, PageToolbarHeatmapState } from './pageToolbarBridge'++export type PageHeatmapCommand =+ | { type: 'set-wildcard-href'; href: string }+ | { type: 'auto-wildcard-href' }+ | { type: 'set-auto-wildcard-enabled'; enabled: boolean }+ | { type: 'set-common-filters'; filters: CommonFilters }+ | { type: 'patch-heatmap-filters'; filters: Partial<HeatmapFilters> }+ | { type: 'set-clickmaps-enabled'; enabled: boolean }+ | { type: 'set-match-links-by-href'; matchLinksByHref: boolean }+ | { type: 'set-fixed-position-mode'; mode: HeatmapFixedPositionMode }+ | { type: 'set-color-palette'; palette: string | null }+ | { type: 'load-all-element-stats' }+ | { type: 'stop-loading-all-element-stats' }+ | { type: 'start-area-selection' }+ | { type: 'cancel-area-selection' }+ | { type: 'clear-area-filter' }+ | { type: 'highlight-counted-element'; index: number | null }+ | { type: 'select-counted-element'; index: number }+ | { type: 'save-heatmap' }++const MAX_ELEMENT_TEXT_LENGTH = 255++type HeatmapFiltersState = Pick<+ PageToolbarHeatmapState,+ | 'wildcardHref'+ | 'autoWildcardEnabled'+ | 'wildcardHrefTooSpecific'+ | 'wildcardHrefEndsWithSlash'+ | 'commonFilters'+ | 'heatmapFilters'+ | 'heatmapColorPalette'+ | 'heatmapFixedPositionMode'+ | 'viewportRange'+ | 'rawHeatmapLoading'+>++type HeatmapClickmapState = Pick<+ PageToolbarHeatmapState,+ | 'heatmapsCollection'+ | 'scrollDepthPosthogJsError'+ | 'clickmapsEnabled'+ | 'clickmapLoading'+ | 'processingProgress'+ | 'matchLinksByHref'+ | 'countedElements'+ | 'clickCount'+ | 'canLoadMoreElementStats'+>++type HeatmapAreaAndSaveState = Pick<+ PageToolbarHeatmapState,+ | 'loadedElementStatsCount'+ | 'loadingAllElementStats'+ | 'areaSelectionActive'+ | 'areaFilter'+ | 'savingHeatmap'+ | 'saveProgress'+ | 'saveResult'+>++type SaveOutcome = { status: 'saved'; shortId: string } | { status: 'failed'; error: string }++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageHeatmapLogicValues {+ autoWildcardEnabled: boolean // currentPageLogic+ wildcardHref: string // currentPageLogic+ wildcardHrefEndsWithSlash: boolean // currentPageLogic+ wildcardHrefTooSpecific: boolean // currentPageLogic+ captureProgress: CaptureProgress | null // heatmapCaptureLogic+ captureResultLoading: boolean // heatmapCaptureLogic+ captureSummary: CaptureSummary | null // heatmapCaptureLogic+ areaSelectionActive: boolean // heatmapToolbarMenuLogic+ canLoadMoreElementStats: boolean // heatmapToolbarMenuLogic+ clickCount: number // heatmapToolbarMenuLogic+ clickmapsEnabled: boolean // heatmapToolbarMenuLogic+ commonFilters: CommonFilters // heatmapToolbarMenuLogic+ countedElements: CountedHTMLElement[] // heatmapToolbarMenuLogic+ elementStatsLoading: boolean // heatmapToolbarMenuLogic+ elementsLoading: boolean // heatmapToolbarMenuLogic+ heatmapAreaFilter: {+ element: HTMLElement+ selector: string | null+ } | null // heatmapToolbarMenuLogic+ heatmapColorPalette: string | null // heatmapToolbarMenuLogic+ heatmapFilters: HeatmapFilters // heatmapToolbarMenuLogic+ heatmapFixedPositionMode: HeatmapFixedPositionMode // heatmapToolbarMenuLogic+ loadedElementStatsCount: number // heatmapToolbarMenuLogic+ loadingAllElementStats: boolean // heatmapToolbarMenuLogic+ matchLinksByHref: boolean // heatmapToolbarMenuLogic+ processingProgress: {+ processed: number+ total: number+ } | null // heatmapToolbarMenuLogic+ rawHeatmapLoading: boolean // heatmapToolbarMenuLogic+ scrollDepthPosthogJsError: ScrollDepthPosthogJsError // heatmapToolbarMenuLogic+ viewportRange: {+ max: number+ min: number+ } // heatmapToolbarMenuLogic+ posthog: PostHog | null // toolbarConfigLogic+ areaAndSaveState: HeatmapAreaAndSaveState+ clickmapState: HeatmapClickmapState+ countedElementInfos: PageToolbarHeatmapState['countedElements']+ filtersState: HeatmapFiltersState+ heatmapsCollection: PageToolbarHeatmapState['heatmapsCollection']+ pageState: PageToolbarHeatmapState+ saveOutcome: SaveOutcome | null+ saveResult: HeatmapSaveResult | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageHeatmapLogicActions {+ saveToPostHogFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // heatmapCaptureLogic+ saveToPostHogSuccess: (+ captureResult: {+ id: string+ short_id: string+ },+ payload?: any+ ) => {+ captureResult: {+ id: string+ short_id: string+ }+ payload?: any+ } // heatmapCaptureLogic+ handleCommand: (command: PageHeatmapCommand) => {+ command: PageHeatmapCommand+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageHeatmapLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ heatmapsCollection: (posthog: PostHog | null) => PageToolbarHeatmapState['heatmapsCollection']+ countedElementInfos: (countedElements: CountedHTMLElement[]) => PageToolbarHeatmapState['countedElements']+ saveResult: (saveOutcome: SaveOutcome | null, captureSummary: CaptureSummary | null) => HeatmapSaveResult | null+ filtersState: (+ wildcardHref: string,+ autoWildcardEnabled: boolean,+ wildcardHrefTooSpecific: boolean,+ wildcardHrefEndsWithSlash: boolean,+ commonFilters: CommonFilters,+ heatmapFilters: HeatmapFilters,+ heatmapColorPalette: string | null,+ heatmapFixedPositionMode: HeatmapFixedPositionMode,+ viewportRange: {+ max: number+ min: number+ },+ rawHeatmapLoading: boolean+ ) => HeatmapFiltersState+ clickmapState: (+ heatmapsCollection: 'disabled' | 'enabled' | 'unknown' | 'unsupported',+ scrollDepthPosthogJsError: ScrollDepthPosthogJsError,+ clickmapsEnabled: boolean,+ elementStatsLoading: boolean,+ elementsLoading: boolean,+ processingProgress: {+ processed: number+ total: number+ } | null,+ matchLinksByHref: boolean,+ countedElementInfos: {+ count: number+ tagName: string+ text: string+ }[],+ clickCount: number,+ canLoadMoreElementStats: boolean+ ) => HeatmapClickmapState+ areaAndSaveState: (+ loadedElementStatsCount: number,+ loadingAllElementStats: boolean,+ areaSelectionActive: boolean,+ heatmapAreaFilter: {+ element: HTMLElement+ selector: string | null+ } | null,+ captureResultLoading: boolean,+ captureProgress: CaptureProgress | null,+ saveResult: HeatmapSaveResult | null+ ) => HeatmapAreaAndSaveState+ pageState: (+ filtersState: HeatmapFiltersState,+ clickmapState: HeatmapClickmapState,+ areaAndSaveState: HeatmapAreaAndSaveState+ ) => PageToolbarHeatmapState+ }+}++export type extensionPageHeatmapLogicType = MakeLogicType<+ extensionPageHeatmapLogicValues,+ extensionPageHeatmapLogicActions,+ Record<string, any>,+ extensionPageHeatmapLogicMeta+>++/** Runs in the content script, next to the toolbar's heatmap logics. */+export const extensionPageHeatmapLogic = kea<extensionPageHeatmapLogicType>([+ path(['toolbar', 'extension', 'extensionPageHeatmapLogic']),+ connect(() => ({+ values: [+ currentPageLogic,+ ['wildcardHref', 'autoWildcardEnabled', 'wildcardHrefTooSpecific', 'wildcardHrefEndsWithSlash'],+ heatmapToolbarMenuLogic,+ [+ 'commonFilters',+ 'heatmapFilters',+ 'heatmapColorPalette',+ 'heatmapFixedPositionMode',+ 'viewportRange',+ 'rawHeatmapLoading',+ 'scrollDepthPosthogJsError',+ 'clickmapsEnabled',+ 'elementStatsLoading',+ 'elementsLoading',+ 'processingProgress',+ 'matchLinksByHref',+ 'countedElements',+ 'clickCount',+ 'canLoadMoreElementStats',+ 'loadedElementStatsCount',+ 'loadingAllElementStats',+ 'areaSelectionActive',+ 'heatmapAreaFilter',+ ],+ toolbarConfigLogic,+ ['posthog'],+ heatmapCaptureLogic,+ ['captureResultLoading', 'captureProgress', 'captureSummary'],+ ],+ actions: [heatmapCaptureLogic, ['saveToPostHogSuccess', 'saveToPostHogFailure']],+ })),+ actions({+ handleCommand: (command: PageHeatmapCommand) => ({ command }),+ }),+ reducers({+ saveOutcome: [+ null as SaveOutcome | null,+ {+ saveToPostHogSuccess: (_, { captureResult }) =>+ captureResult ? { status: 'saved', shortId: captureResult.short_id } : null,+ saveToPostHogFailure: (_, { error }) => ({ status: 'failed', error }),+ },+ ],+ }),+ selectors({+ heatmapsCollection: [+ (s) => [s.posthog],+ (posthog: PostHog | null): PageToolbarHeatmapState['heatmapsCollection'] =>+ !posthog+ ? 'unknown'+ : !posthog.heatmaps+ ? 'unsupported'+ : posthog.heatmaps.isEnabled+ ? 'enabled'+ : 'disabled',+ ],+ // Reading `innerText` lays out the page, so it runs only when the counted elements change.+ countedElementInfos: [+ (s) => [s.countedElements],+ (countedElements: CountedHTMLElement[]): PageToolbarHeatmapState['countedElements'] =>+ countedElements.map(({ element, count }) => ({+ text: element.innerText?.trim().substring(0, MAX_ELEMENT_TEXT_LENGTH) ?? '',+ tagName: element.tagName.toLowerCase(),+ count,+ })),+ ],+ saveResult: [+ (s) => [s.saveOutcome, s.captureSummary],+ (+ saveOutcome: SaveOutcome | null,+ captureSummary: { savedWidths: number; totalWidths: number } | null+ ): HeatmapSaveResult | null =>+ saveOutcome?.status === 'saved'+ ? {+ ...saveOutcome,+ savedWidths: captureSummary?.savedWidths ?? 0,+ totalWidths: captureSummary?.totalWidths ?? 0,+ }+ : saveOutcome,+ ],+ // kea types a selector with up to about a dozen inputs, so the slice comes from three smaller ones.+ filtersState: [+ (s) => [+ s.wildcardHref,+ s.autoWildcardEnabled,+ s.wildcardHrefTooSpecific,+ s.wildcardHrefEndsWithSlash,+ s.commonFilters,+ s.heatmapFilters,+ s.heatmapColorPalette,+ s.heatmapFixedPositionMode,+ s.viewportRange,+ s.rawHeatmapLoading,+ ],+ (+ wildcardHref: string,+ autoWildcardEnabled: boolean,+ wildcardHrefTooSpecific: boolean,+ wildcardHrefEndsWithSlash: boolean,+ commonFilters: CommonFilters,+ heatmapFilters: HeatmapFilters,+ heatmapColorPalette: string | null,+ heatmapFixedPositionMode: HeatmapFixedPositionMode,+ viewportRange: { min: number; max: number },+ rawHeatmapLoading: boolean+ ): HeatmapFiltersState => ({+ wildcardHref,+ autoWildcardEnabled,+ wildcardHrefTooSpecific,+ wildcardHrefEndsWithSlash,+ commonFilters,+ heatmapFilters,+ heatmapColorPalette,+ heatmapFixedPositionMode,+ viewportRange,+ rawHeatmapLoading,+ }),+ ],+ clickmapState: [+ (s) => [+ s.heatmapsCollection,+ s.scrollDepthPosthogJsError,+ s.clickmapsEnabled,+ s.elementStatsLoading,+ s.elementsLoading,+ s.processingProgress,+ s.matchLinksByHref,+ s.countedElementInfos,+ s.clickCount,+ s.canLoadMoreElementStats,+ ],+ (+ heatmapsCollection: PageToolbarHeatmapState['heatmapsCollection'],+ scrollDepthPosthogJsError: ScrollDepthPosthogJsError,+ clickmapsEnabled: boolean,+ elementStatsLoading: boolean,+ elementsLoading: boolean,+ processingProgress: PageToolbarHeatmapState['processingProgress'],+ matchLinksByHref: boolean,+ countedElementInfos: PageToolbarHeatmapState['countedElements'],+ clickCount: number,+ canLoadMoreElementStats: boolean+ ): HeatmapClickmapState => ({+ heatmapsCollection,+ scrollDepthPosthogJsError,+ clickmapsEnabled,+ clickmapLoading: elementStatsLoading || elementsLoading,+ processingProgress,+ matchLinksByHref,+ countedElements: countedElementInfos,+ clickCount,+ canLoadMoreElementStats,+ }),+ ],+ areaAndSaveState: [+ (s) => [+ s.loadedElementStatsCount,+ s.loadingAllElementStats,+ s.areaSelectionActive,+ s.heatmapAreaFilter,+ s.captureResultLoading,+ s.captureProgress,+ s.saveResult,+ ],+ (+ loadedElementStatsCount: number,+ loadingAllElementStats: boolean,+ areaSelectionActive: boolean,+ heatmapAreaFilter: { element: HTMLElement; selector: string | null } | null,+ captureResultLoading: boolean,+ captureProgress: PageToolbarHeatmapState['saveProgress'],+ saveResult: HeatmapSaveResult | null+ ): HeatmapAreaAndSaveState => ({+ loadedElementStatsCount,+ loadingAllElementStats,+ areaSelectionActive,+ areaFilter: heatmapAreaFilter+ ? { selector: heatmapAreaFilter.selector, tagName: heatmapAreaFilter.element.tagName.toLowerCase() }+ : null,+ savingHeatmap: captureResultLoading,+ saveProgress: captureProgress,+ saveResult,+ }),+ ],+ pageState: [+ (s) => [s.filtersState, s.clickmapState, s.areaAndSaveState],+ (+ filtersState: HeatmapFiltersState,+ clickmapState: HeatmapClickmapState,+ areaAndSaveState: HeatmapAreaAndSaveState+ ): PageToolbarHeatmapState => ({+ ...filtersState,+ ...clickmapState,+ ...areaAndSaveState,+ }),+ ],+ }),+ listeners(({ values }) => ({+ handleCommand: ({ command }) => {+ const heatmap = heatmapToolbarMenuLogic.actions+ const page = currentPageLogic.actions+ switch (command.type) {+ case 'set-wildcard-href':+ page.setWildcardHref(command.href)+ return+ case 'auto-wildcard-href':+ page.autoWildcardHref()+ return+ case 'set-auto-wildcard-enabled':+ page.setAutoWildcardEnabled(command.enabled)+ return+ case 'set-common-filters':+ heatmap.setCommonFilters(command.filters)+ return+ case 'patch-heatmap-filters':+ heatmap.patchHeatmapFilters(command.filters)+ return+ case 'set-clickmaps-enabled':+ heatmap.toggleClickmapsEnabled(command.enabled)+ return+ case 'set-match-links-by-href':+ heatmap.setMatchLinksByHref(command.matchLinksByHref)+ return+ case 'set-fixed-position-mode':+ heatmap.setHeatmapFixedPositionMode(command.mode)+ return+ case 'set-color-palette':+ heatmap.setHeatmapColorPalette(command.palette)+ return+ case 'load-all-element-stats':+ heatmap.startLoadingAllElementStats()+ return+ case 'stop-loading-all-element-stats':+ heatmap.stopLoadingAllElementStats()+ return+ case 'start-area-selection':+ heatmap.startAreaSelection()+ return+ case 'cancel-area-selection':+ heatmap.cancelAreaSelection()+ return+ case 'clear-area-filter':+ heatmap.selectHeatmapAreaFilter(null)+ return+ case 'highlight-counted-element':+ elementsLogic.actions.setHighlightElement(+ command.index === null ? null : (values.countedElements[command.index]?.element ?? null)+ )+ return+ case 'select-counted-element': {+ const element = values.countedElements[command.index]?.element+ if (element) {+ element.scrollIntoView({ block: 'center', behavior: 'smooth' })+ elementsLogic.actions.setSelectedElement(element)+ }+ return+ }+ case 'save-heatmap':+ heatmapCaptureLogic.actions.saveToPostHog()+ return+ }+ },+ })),+])diff --git a/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts b/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.tsnew file mode 100644index 000000000000..46c60f1c8040--- /dev/null+++ b/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts@@ -0,0 +1,279 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ listeners,+ path,+ reducers,+ selectors,+} from 'kea'++import { urls } from '~/toolbar/urls'++import { extensionAuthLogic } from './extensionAuthLogic'+import { ExtensionPort, connectToPageToolbar, ensureContentScript, injectPageAgent, openTab } from './extensionBrowser'+import { extensionPanelLogic } from './extensionPanelLogic'+import { capturePageToolUsed } from './extensionTelemetry'+import {+ PageToolbarCommand,+ PageToolbarMode,+ PageToolbarRequest,+ PageToolbarState,+ isPageToolbarMessage,+} from './pageToolbarBridge'+import type { PageToolbarHeatmapState, PageToolbarInspectState, PageToolbarTokens } from './pageToolbarBridge'++export type PageToolbarConnectionStatus = 'idle' | 'connecting' | 'connected' | 'failed'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarConnectionLogicValues {+ tokens: PageToolbarTokens | null // extensionAuthLogic+ dataAttributes: string[] // extensionPanelLogic+ projectUrl: (path: string) => string // extensionPanelLogic+ tabId: number | null // extensionPanelLogic+ tabUrl: string | null | undefined // extensionPanelLogic+ uiHost: string // extensionPanelLogic+ connectionStatus: PageToolbarConnectionStatus+ heatmap: PageToolbarHeatmapState | null+ inspect: PageToolbarInspectState | null+ mode: PageToolbarMode+ pageToolbarState: PageToolbarState | null+ wantedMode: PageToolbarMode+ wildcardHrefDraft: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarConnectionLogicActions {+ setTokens: (+ key: string,+ tokens: PageToolbarTokens | null+ ) => {+ key: string+ tokens: PageToolbarTokens | null+ } // extensionAuthLogic+ tokensExpired: () => {+ value: true+ } // extensionAuthLogic+ updateTokens: (tokens: PageToolbarTokens) => {+ tokens: PageToolbarTokens+ } // extensionAuthLogic+ setTab: (+ tabId: number | null,+ tabUrl: string | null+ ) => {+ tabId: number | null+ tabUrl: string | null+ } // extensionPanelLogic+ connectPage: () => {+ value: true+ }+ openHeatmapInPostHog: (shortId: string) => {+ shortId: string+ }+ receivePatch: (patch: Partial<PageToolbarState>) => {+ patch: Partial<PageToolbarState>+ }+ receiveState: (state: PageToolbarState | null) => {+ state: PageToolbarState | null+ }+ sendCommand: (message: PageToolbarCommand) => {+ message: PageToolbarCommand+ }+ setConnectionStatus: (status: PageToolbarConnectionStatus) => {+ status: PageToolbarConnectionStatus+ }+ setMode: (mode: PageToolbarMode) => {+ mode: PageToolbarMode+ }+ setWildcardHref: (href: string) => {+ href: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarConnectionLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ mode: (pageToolbarState: PageToolbarState | null, wantedMode: PageToolbarMode) => PageToolbarMode+ inspect: (pageToolbarState: PageToolbarState | null) => PageToolbarInspectState | null+ heatmap: (pageToolbarState: PageToolbarState | null) => PageToolbarHeatmapState | null+ }+}++export type extensionPageToolbarConnectionLogicType = MakeLogicType<+ extensionPageToolbarConnectionLogicValues,+ extensionPageToolbarConnectionLogicActions,+ Record<string, any>,+ extensionPageToolbarConnectionLogicMeta+>++export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConnectionLogicType>([+ path(['toolbar', 'extension', 'extensionPageToolbarConnectionLogic']),+ connect(() => ({+ values: [+ extensionPanelLogic,+ ['tabId', 'tabUrl', 'uiHost', 'dataAttributes', 'projectUrl'],+ extensionAuthLogic,+ ['tokens'],+ ],+ actions: [extensionPanelLogic, ['setTab'], extensionAuthLogic, ['setTokens', 'updateTokens', 'tokensExpired']],+ })),+ actions({+ connectPage: true,+ setConnectionStatus: (status: PageToolbarConnectionStatus) => ({ status }),+ receiveState: (state: PageToolbarState | null) => ({ state }),+ receivePatch: (patch: Partial<PageToolbarState>) => ({ patch }),+ sendCommand: (message: PageToolbarCommand) => ({ message }),+ setMode: (mode: PageToolbarMode) => ({ mode }),+ setWildcardHref: (href: string) => ({ href }),+ openHeatmapInPostHog: (shortId: string) => ({ shortId }),+ }),+ reducers({+ connectionStatus: [+ 'idle' as PageToolbarConnectionStatus,+ { setConnectionStatus: (_, { status }) => status, connectPage: () => 'connecting' },+ ],+ // A patch keeps every slice it doesn't carry, so a component that reads one slice skips unrelated messages.+ pageToolbarState: [+ null as PageToolbarState | null,+ {+ receiveState: (_, { state }) => state,+ receivePatch: (state, { patch }) => (state ? { ...state, ...patch } : state),+ setTab: () => null,+ },+ ],+ // The page echoes the URL back a moment later. Until then the input shows what the user typed, so a fast typist+ // doesn't lose characters to an older echo.+ wildcardHrefDraft: [+ null as string | null,+ {+ setWildcardHref: (_, { href }) => href,+ receivePatch: (draft, { patch }) => (patch.heatmap?.wildcardHref === draft ? null : draft),+ setTab: () => null,+ },+ ],+ // The page loses its tools when it reloads, so the panel turns the mode the user picked back on.+ wantedMode: [+ 'none' as PageToolbarMode,+ {+ setMode: (_, { mode }) => mode,+ receiveState: (mode, { state }) => state?.mode ?? mode,+ receivePatch: (mode, { patch }) => patch.mode ?? mode,+ },+ ],+ }),+ selectors({+ mode: [+ (s) => [s.pageToolbarState, s.wantedMode],+ (pageToolbarState: PageToolbarState | null, wantedMode: PageToolbarMode): PageToolbarMode =>+ pageToolbarState?.mode ?? wantedMode,+ ],+ inspect: [+ (s) => [s.pageToolbarState],+ (pageToolbarState: PageToolbarState | null) => pageToolbarState?.inspect ?? null,+ ],+ heatmap: [+ (s) => [s.pageToolbarState],+ (pageToolbarState: PageToolbarState | null) => pageToolbarState?.heatmap ?? null,+ ],+ }),+ listeners(({ actions, values, cache }) => {+ const post = (message: PageToolbarRequest): void => {+ cache.port?.postMessage(message)+ }+ return {+ connectPage: async (_, breakpoint) => {+ cache.port?.disconnect()+ cache.port = null+ const { tabId, tabUrl, tokens } = values+ if (tabId === null || !tabUrl || !tokens) {+ actions.setConnectionStatus('idle')+ return+ }+ try {+ await Promise.all([ensureContentScript(tabId), injectPageAgent(tabId)])+ } catch {+ actions.setConnectionStatus('failed')+ return+ }+ breakpoint()+ const port: ExtensionPort = connectToPageToolbar(tabId)+ cache.port = port+ cache.portTabId = tabId+ port.onMessage.addListener((message) => {+ if (!isPageToolbarMessage(message) || cache.port !== port) {+ return+ }+ if (message.type === 'state') {+ actions.receiveState(message.state)+ } else if (message.type === 'patch') {+ actions.receivePatch(message.patch)+ } else if (message.type === 'tokens') {+ actions.updateTokens(message.tokens)+ } else if (message.type === 'token-expired') {+ actions.tokensExpired()+ }+ })+ // A new document has no content script, so the port closes when the tab loads another page.+ port.onDisconnect.addListener(() => {+ if (cache.port === port) {+ cache.port = null+ actions.setConnectionStatus('idle')+ actions.receiveState(null)+ }+ })+ post({+ type: 'start',+ session: { ...tokens, uiHost: values.uiHost, dataAttributes: values.dataAttributes },+ href: tabUrl,+ })+ if (values.wantedMode !== 'none') {+ actions.sendCommand({ tool: 'session', command: { type: 'set-mode', mode: values.wantedMode } })+ }+ actions.setConnectionStatus('connected')+ },+ setWildcardHref: ({ href }) => {+ actions.sendCommand({ tool: 'heatmap', command: { type: 'set-wildcard-href', href } })+ },+ sendCommand: ({ message }) => {+ post(message)+ },+ setMode: ({ mode }) => {+ if (mode !== 'none') {+ capturePageToolUsed(mode)+ }+ actions.sendCommand({ tool: 'session', command: { type: 'set-mode', mode } })+ },+ setTab: ({ tabId, tabUrl }) => {+ // A single-page app changes the URL in the same document, so the page tools keep running there.+ if (cache.port && cache.portTabId === tabId && tabUrl) {+ actions.sendCommand({ tool: 'session', command: { type: 'set-href', href: tabUrl } })+ return+ }+ actions.connectPage()+ },+ setTokens: ({ tokens }) => {+ if (!tokens) {+ return+ }+ if (cache.port) {+ actions.sendCommand({ tool: 'session', command: { type: 'set-tokens', tokens } })+ } else {+ actions.connectPage()+ }+ },+ openHeatmapInPostHog: ({ shortId }) => {+ void openTab(values.projectUrl(urls.heatmap(shortId)))+ },+ }+ }),+ afterMount(({ actions }) => {+ actions.connectPage()+ }),+ beforeUnmount(({ cache }) => {+ cache.port?.disconnect()+ cache.port = null+ }),+])diff --git a/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts b/frontend/src/toolbar/extension/extensionPageToolbarLogic.tsnew file mode 100644index 000000000000..5479dd7f49a8--- /dev/null+++ b/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts@@ -0,0 +1,164 @@+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'++import { elementsLogic } from '~/toolbar/elements/elementsLogic'+import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import type { ElementWithMetadata } from '~/toolbar/types'++import type { FragileSelectorResult } from '../utils/selectorQuality'+import { extensionPageHeatmapLogic } from './extensionPageHeatmapLogic'+import type {+ InspectedElementInfo,+ PageToolCommands,+ PageToolName,+ PageToolbarCommand,+ PageToolbarInspectState,+ PageToolbarMode,+ PageToolbarState,+ PageToolbarTokens,+} from './pageToolbarBridge'++export type PageSessionCommand =+ | { type: 'set-mode'; mode: PageToolbarMode }+ | { type: 'set-tokens'; tokens: PageToolbarTokens }+ | { type: 'set-href'; href: string }++export type PageInspectCommand = { type: 'clear-selected-element' }++function inspectedElementInfo(meta: ElementWithMetadata | null): InspectedElementInfo | null {+ if (!meta) {+ return null+ }+ return {+ tagName: meta.element.tagName.toLowerCase(),+ actionStep: meta.actionStep ?? null,+ stats: meta.position+ ? {+ count: meta.count ?? 0,+ clickCount: meta.clickCount ?? 0,+ rageclickCount: meta.rageclickCount ?? 0,+ deadclickCount: meta.deadclickCount ?? 0,+ rank: meta.position,+ }+ : null,+ actions: (meta.actions ?? []).map(({ action }) => ({ id: action.id, name: action.name ?? null })),+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarLogicValues {+ activeMeta:+ | (ElementWithMetadata & {+ selectorQuality: FragileSelectorResult | null+ })+ | null // elementsLogic+ activeMetaIsSelected: boolean // elementsLogic+ inspectEnabled: boolean // elementsLogic+ heatmapEnabled: boolean // heatmapToolbarMenuLogic+ inspectState: PageToolbarInspectState+ mode: PageToolbarMode+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarLogicActions {+ handleCommand: (message: PageToolbarCommand) => {+ message: PageToolbarCommand+ }+ setMode: (mode: PageToolbarMode) => {+ mode: PageToolbarMode+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface extensionPageToolbarLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ mode: (inspectEnabled: boolean, heatmapEnabled: boolean) => PageToolbarMode+ inspectState: (+ activeMeta:+ | (ElementWithMetadata & {+ selectorQuality: FragileSelectorResult | null+ })+ | null,+ activeMetaIsSelected: boolean+ ) => PageToolbarInspectState+ }+}++export type extensionPageToolbarLogicType = MakeLogicType<+ extensionPageToolbarLogicValues,+ extensionPageToolbarLogicActions,+ Record<string, any>,+ extensionPageToolbarLogicMeta+>++/** Runs in the content script. Mount it after `toolbarConfigLogic`, because the connected logics read its tokens. */+export const extensionPageToolbarLogic = kea<extensionPageToolbarLogicType>([+ path(['toolbar', 'extension', 'extensionPageToolbarLogic']),+ connect(() => ({+ values: [+ elementsLogic,+ ['inspectEnabled', 'activeMeta', 'activeMetaIsSelected'],+ heatmapToolbarMenuLogic,+ ['heatmapEnabled'],+ ],+ logic: [extensionPageHeatmapLogic],+ })),+ actions({+ handleCommand: (message: PageToolbarCommand) => ({ message }),+ setMode: (mode: PageToolbarMode) => ({ mode }),+ }),+ selectors({+ mode: [+ (s) => [s.inspectEnabled, s.heatmapEnabled],+ (inspectEnabled: boolean, heatmapEnabled: boolean): PageToolbarMode =>+ inspectEnabled ? 'inspect' : heatmapEnabled ? 'heatmap' : 'none',+ ],+ inspectState: [+ (s) => [s.activeMeta, s.activeMetaIsSelected],+ (activeMeta: ElementWithMetadata | null, activeMetaIsSelected: boolean): PageToolbarInspectState => ({+ element: inspectedElementInfo(activeMeta),+ isSelected: activeMetaIsSelected,+ }),+ ],+ }),+ listeners(({ actions }) => ({+ setMode: ({ mode }) => {+ // The floating toolbar opens one menu at a time, and each menu turns the others' page modes off.+ elementsLogic.actions.disableInspect()+ heatmapToolbarMenuLogic.actions.disableHeatmap()+ if (mode === 'inspect') {+ elementsLogic.actions.enableInspect()+ } else if (mode === 'heatmap') {+ heatmapToolbarMenuLogic.actions.enableHeatmap()+ }+ },+ handleCommand: ({ message }) => {+ const handlers: { [Tool in PageToolName]: (command: PageToolCommands[Tool]) => void } = {+ session: (command) => {+ if (command.type === 'set-mode') {+ actions.setMode(command.mode)+ } else if (command.type === 'set-href') {+ currentPageLogic.actions.setHref(command.href)+ } else {+ const { accessToken, refreshToken, clientId } = command.tokens+ toolbarConfigLogic.actions.setOAuthTokens(accessToken, refreshToken, clientId)+ }+ },+ inspect: () => elementsLogic.actions.setSelectedElement(null),+ heatmap: (command) => extensionPageHeatmapLogic.actions.handleCommand(command),+ }+ ;(handlers[message.tool] as (command: PageToolbarCommand['command']) => void)(message.command)+ },+ })),+])++/** Every slice comes from a memoized selector, so the host posts only the slices whose reference changed. */+export function getPageToolbarState(): PageToolbarState {+ const { mode, inspectState } = extensionPageToolbarLogic.values+ return {+ mode,+ inspect: inspectState,+ heatmap: extensionPageHeatmapLogic.values.pageState,+ }+}diff --git a/frontend/src/toolbar/extension/extensionPageTools.tsx b/frontend/src/toolbar/extension/extensionPageTools.tsxnew file mode 100644index 000000000000..98aaee45bcde--- /dev/null+++ b/frontend/src/toolbar/extension/extensionPageTools.tsx@@ -0,0 +1,65 @@+import { IconBolt, IconCursorClick, IconFlask, IconPieChart, IconSearch, IconToggle } from '@posthog/icons'++import { urls } from '~/toolbar/urls'+import { AvailableFeature } from '~/types'++import type { PageToolbarMode } from './pageToolbarBridge'++export type PageToolMode = Exclude<PageToolbarMode, 'none'>++// pinned: sent as the `feature` property of `toolbar extension feature opened`+export type ExtensionFeatureKey = 'heatmaps' | 'actions' | 'feature-flags' | 'experiments' | 'web-vitals'++export interface PageToolDefinition {+ /** Missing for a tool the panel only links to in PostHog. */+ mode?: PageToolMode+ label: string+ description: string+ icon: JSX.Element+ /** The tool's page in PostHog. */+ feature?: { key: ExtensionFeatureKey; path: string }+ /** The paid feature the floating toolbar gates this tool on. */+ gate?: AvailableFeature+}++/** The floating toolbar's buttons, in toolbar order, with its "More" menu last. */+export const PAGE_TOOLS: PageToolDefinition[] = [+ {+ mode: 'inspect',+ label: 'Inspect',+ description: "Hover the page to see each element's selector, clicks and actions",+ icon: <IconSearch />,+ },+ {+ mode: 'heatmap',+ label: 'Heatmap',+ description: 'Show where people click and how far they scroll',+ icon: <IconCursorClick />,+ feature: { key: 'heatmaps', path: urls.heatmaps() },+ gate: AvailableFeature.TOOLBAR_HEATMAPS,+ },+ {+ label: 'Actions',+ description: 'Create and edit actions from elements on the page',+ icon: <IconBolt />,+ feature: { key: 'actions', path: urls.actions() },+ },+ {+ label: 'Feature flags',+ description: 'Override feature flags on this page',+ icon: <IconToggle />,+ feature: { key: 'feature-flags', path: urls.featureFlags() },+ },+ {+ label: 'Web vitals',+ description: 'Check how fast this page loads',+ icon: <IconPieChart />,+ feature: { key: 'web-vitals', path: urls.webAnalyticsWebVitals() },+ },+ {+ label: 'Experiments',+ description: 'Build no-code web experiments and preview their variants on the page',+ icon: <IconFlask />,+ feature: { key: 'experiments', path: urls.experiments() },+ },+]diff --git a/frontend/src/toolbar/extension/extensionPanelLogic.ts b/frontend/src/toolbar/extension/extensionPanelLogic.tsindex dda4b46da51c..cb9cc3010e8d 100644--- a/frontend/src/toolbar/extension/extensionPanelLogic.ts+++ b/frontend/src/toolbar/extension/extensionPanelLogic.ts@@ -22,7 +22,7 @@ import {requestHostPermission,setStoredUiHost,} from './extensionBrowser'-import type { ExtensionFeatureKey } from './extensionFeatures'+import type { ExtensionFeatureKey } from './extensionPageTools'import {ExtensionPanelState,SessionUserResult,@@ -32,6 +32,9 @@ import {const DEFAULT_UI_HOST = 'https://us.posthog.com'+// The project setting's default, used until the project loads.+const DEFAULT_DATA_ATTRIBUTES = ['data-attr']+// Matches the toolbar's entitlements request timeout.const REQUEST_TIMEOUT_MS = 5000@@ -74,6 +77,7 @@ async function readResponse(request: Promise<Response>): Promise<{ status: numbeexport interface extensionPanelLogicValues {authorizedUrls: string[] | 'error' | nullauthorizedUrlsLoading: boolean+ dataAttributes: string[]entitlements: ToolbarEntitlementsApiEntitlements | nullhostPermission: boolean | nullpanelState: ExtensionPanelState@@ -83,6 +87,7 @@ export interface extensionPanelLogicValues {sessionUserLoading: booleansettingsExpanded: booleansettingsNeeded: boolean+ tabId: number | nulltabUrl: string | null | undefinedtoolbarAccess: ToolbarAccessResult | nulltoolbarAccessLoading: boolean@@ -165,6 +170,9 @@ export interface extensionPanelLogicActions {retry: () => {value: true}+ setDataAttributes: (dataAttributes: string[]) => {+ dataAttributes: string[]+ }setHostPermission: (granted: boolean) => {granted: boolean}@@ -174,7 +182,11 @@ export interface extensionPanelLogicActions {setSettingsExpanded: (expanded: boolean) => {expanded: boolean}- setTabUrl: (tabUrl: string | null) => {+ setTab: (+ tabId: number | null,+ tabUrl: string | null+ ) => {+ tabId: number | nulltabUrl: string | null}setUiHost: (uiHost: string) => {@@ -213,7 +225,8 @@ export type extensionPanelLogicType = MakeLogicType<export const extensionPanelLogic = kea<extensionPanelLogicType>([path(['toolbar', 'extension', 'extensionPanelLogic']),actions({- setTabUrl: (tabUrl: string | null) => ({ tabUrl }),+ setTab: (tabId: number | null, tabUrl: string | null) => ({ tabId, tabUrl }),+ setDataAttributes: (dataAttributes: string[]) => ({ dataAttributes }),setUiHost: (uiHost: string) => ({ uiHost }),setHostPermission: (granted: boolean) => ({ granted }),requestHostPermission: true,@@ -226,7 +239,9 @@ export const extensionPanelLogic = kea<extensionPanelLogicType>([setSettingsExpanded: (expanded: boolean) => ({ expanded }),}),reducers({- tabUrl: [undefined as string | null | undefined, { setTabUrl: (_, { tabUrl }) => tabUrl }],+ tabId: [null as number | null, { setTab: (_, { tabId }) => tabId }],+ tabUrl: [undefined as string | null | undefined, { setTab: (_, { tabUrl }) => tabUrl }],+ dataAttributes: [DEFAULT_DATA_ATTRIBUTES, { setDataAttributes: (_, { dataAttributes }) => dataAttributes }],uiHost: [DEFAULT_UI_HOST as string, { setUiHost: (_, { uiHost }) => uiHost }],projectSwitchFailed: [false,@@ -238,7 +253,7 @@ export const extensionPanelLogic = kea<extensionPanelLogicType>([],settingsExpanded: [false, { setSettingsExpanded: (_, { expanded }) => expanded }],}),- loaders(({ values }) => ({+ loaders(({ actions, values }) => ({sessionUser: [null as SessionUserResult | null,{@@ -301,7 +316,15 @@ export const extensionPanelLogic = kea<extensionPanelLogicType>([if (status !== 200 || !data) {return 'error'}- return ((data as ProjectBackwardCompatApi).app_urls ?? []).filter(+ const project = data as ProjectBackwardCompatApi+ if (Array.isArray(project.data_attributes)) {+ actions.setDataAttributes(+ project.data_attributes.filter(+ (attribute): attribute is string => typeof attribute === 'string'+ )+ )+ }+ return (project.app_urls ?? []).filter((url): url is string => typeof url === 'string' && url.length > 0)},@@ -377,7 +400,7 @@ export const extensionPanelLogic = kea<extensionPanelLogicType>([actions.loadToolbarAccess()}},- setTabUrl: () => {+ setTab: () => {// The panel stays open while the user logs in, switches project or adds an authorized URL in another// tab, so check again when the user comes back.if (RECHECK_ON_TAB_CHANGE.includes(values.panelState.kind)) {@@ -448,10 +471,10 @@ export const extensionPanelLogic = kea<extensionPanelLogicType>([toolbarPosthogJS.opt_in_capturing()void getStoredUiHost().then((stored) => actions.setUiHost(canonicalizeUiHost(stored) ?? DEFAULT_UI_HOST))void getActiveTab().then(- (tab) => actions.setTabUrl(tab?.url ?? null),- () => actions.setTabUrl(null)+ (tab) => actions.setTab(tab?.id ?? null, tab?.url ?? null),+ () => actions.setTab(null, null))- cache.removeActiveTabListener = onActiveTabChange((tab) => actions.setTabUrl(tab?.url ?? null))+ cache.removeActiveTabListener = onActiveTabChange((tab) => actions.setTab(tab?.id ?? null, tab?.url ?? null))}),beforeUnmount(({ cache }) => {cache.removeActiveTabListener?.()diff --git a/frontend/src/toolbar/extension/extensionTelemetry.ts b/frontend/src/toolbar/extension/extensionTelemetry.tsnew file mode 100644index 000000000000..26c800a4bfa3--- /dev/null+++ b/frontend/src/toolbar/extension/extensionTelemetry.ts@@ -0,0 +1,9 @@+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'++// pinned: sent as the `tool` property of `toolbar extension page tool used`+type PageToolKey = 'heatmap' | 'inspect' | 'save-heatmap'++export function capturePageToolUsed(tool: PageToolKey, properties?: Record<string, unknown>): void {+ // pinned: analytics event name+ toolbarPosthogJS.capture('toolbar extension page tool used', { tool, ...properties })+}diff --git a/frontend/src/toolbar/extension/pageAgent.ts b/frontend/src/toolbar/extension/pageAgent.tsnew file mode 100644index 000000000000..15e09549c95b--- /dev/null+++ b/frontend/src/toolbar/extension/pageAgent.ts@@ -0,0 +1,87 @@+import {+ PAGE_AGENT_REPLY_SOURCE,+ PageAgentReply,+ PageAgentReplyMessage,+ isPageAgentRequestMessage,+} from './pageAgentProtocol'+import type { PageAnalyticsInfo } from './pageToolbarBridge'++interface PagePosthog {+ __loaded?: boolean+ version?: string+ config?: {+ disable_scroll_properties?: boolean+ scroll_root_selector?: string | string[]+ }+ heatmaps?: { isEnabled?: boolean }+}++// The panel injects this file again on each connection, so a second run in the same page must do nothing.+const INSTALLED_FLAG = '__posthogToolbarExtensionPageAgent'++// An async snippet loads posthog-js after the page loads, so the agent watches for it this often, for this long.+const POSTHOG_CHECK_INTERVAL_MS = 500+const POSTHOG_CHECK_DURATION_MS = 10_000++/** A page can replace any of these with a getter that throws, so each read stands alone. */+function read<T>(get: () => T | null | undefined, fallback: T): T {+ try {+ return get() ?? fallback+ } catch {+ return fallback+ }+}++/** The snippet's stub array has none of posthog-js's methods until the library loads. */+function pagePosthog(): PagePosthog | null {+ const posthog = (window as unknown as { posthog?: PagePosthog }).posthog+ return posthog && typeof posthog === 'object' && (posthog.__loaded || typeof posthog.version === 'string')+ ? posthog+ : null+}++function analyticsInfo(posthog: PagePosthog): PageAnalyticsInfo {+ return {+ version: read(() => posthog.version, null),+ scrollPropertiesDisabled: !!read(() => posthog.config?.disable_scroll_properties, false),+ scrollRootSelector: read(() => posthog.config?.scroll_root_selector, null),+ heatmapsEnabled: posthog.heatmaps ? !!read(() => posthog.heatmaps?.isEnabled, false) : null,+ }+}++function reply(message: PageAgentReply): void {+ window.postMessage(+ { source: PAGE_AGENT_REPLY_SOURCE, reply: message } satisfies PageAgentReplyMessage,+ window.location.origin+ )+}++function install(): void {+ window.addEventListener('message', (event) => {+ if (event.source !== window || !isPageAgentRequestMessage(event.data)) {+ return+ }+ const posthog = pagePosthog()+ reply({ kind: 'analytics', id: event.data.id, info: posthog ? analyticsInfo(posthog) : null })+ })++ if (pagePosthog()) {+ return+ }+ const startedAt = Date.now()+ const interval = setInterval(() => {+ const loaded = pagePosthog()+ if (loaded) {+ reply({ kind: 'analytics', id: null, info: analyticsInfo(loaded) })+ }+ if (loaded || Date.now() - startedAt > POSTHOG_CHECK_DURATION_MS) {+ clearInterval(interval)+ }+ }, POSTHOG_CHECK_INTERVAL_MS)+}++const pageGlobal = window as unknown as Record<string, boolean | undefined>+if (!pageGlobal[INSTALLED_FLAG]) {+ pageGlobal[INSTALLED_FLAG] = true+ install()+}diff --git a/frontend/src/toolbar/extension/pageAgentProtocol.ts b/frontend/src/toolbar/extension/pageAgentProtocol.tsnew file mode 100644index 000000000000..a13c8aad0e1e--- /dev/null+++ b/frontend/src/toolbar/extension/pageAgentProtocol.ts@@ -0,0 +1,42 @@+import type { PageAnalyticsInfo } from './pageToolbarBridge'++// The content script's isolated world can't call the page's `window.posthog`, so the page agent calls it from the+// page's own world.++// pinned: page message sources, the page agent and an already injected content script must agree on them+export const PAGE_AGENT_REQUEST_SOURCE = 'posthog-toolbar-extension-request'+export const PAGE_AGENT_REPLY_SOURCE = 'posthog-toolbar-extension-reply'++export type PageAgentRequest = { method: 'read-analytics' }++/** `id` is null when the page agent reports by itself that posthog-js appeared on the page. */+export type PageAgentReply = { kind: 'analytics'; id: number | null; info: PageAnalyticsInfo | null }++export interface PageAgentRequestMessage {+ source: typeof PAGE_AGENT_REQUEST_SOURCE+ id: number+ request: PageAgentRequest+}++export interface PageAgentReplyMessage {+ source: typeof PAGE_AGENT_REPLY_SOURCE+ reply: PageAgentReply+}++export function isPageAgentRequestMessage(data: unknown): data is PageAgentRequestMessage {+ return (+ !!data &&+ typeof data === 'object' &&+ (data as Partial<PageAgentRequestMessage>).source === PAGE_AGENT_REQUEST_SOURCE &&+ typeof (data as Partial<PageAgentRequestMessage>).id === 'number'+ )+}++export function isPageAgentReplyMessage(data: unknown): data is PageAgentReplyMessage {+ return (+ !!data &&+ typeof data === 'object' &&+ (data as Partial<PageAgentReplyMessage>).source === PAGE_AGENT_REPLY_SOURCE &&+ !!(data as Partial<PageAgentReplyMessage>).reply+ )+}diff --git a/frontend/src/toolbar/extension/pagePosthogBridge.ts b/frontend/src/toolbar/extension/pagePosthogBridge.tsnew file mode 100644index 000000000000..4d6804d22840--- /dev/null+++ b/frontend/src/toolbar/extension/pagePosthogBridge.ts@@ -0,0 +1,94 @@+import type { PostHog } from 'posthog-js'++import {+ PAGE_AGENT_REQUEST_SOURCE,+ PageAgentReply,+ PageAgentRequest,+ PageAgentRequestMessage,+ isPageAgentReplyMessage,+} from './pageAgentProtocol'+import type { PageAnalyticsInfo } from './pageToolbarBridge'++// The page agent answers in milliseconds. Past this, the page most likely reloaded or has no agent.+const ANALYTICS_TIMEOUT_MS = 1000++let nextRequestId = 1++function postToPageAgent(request: PageAgentRequest): number {+ const id = nextRequestId+++ window.postMessage(+ { source: PAGE_AGENT_REQUEST_SOURCE, id, request } satisfies PageAgentRequestMessage,+ window.location.origin+ )+ return id+}++function onPageAgentReply(handler: (reply: PageAgentReply) => void): () => void {+ const listener = (event: MessageEvent): void => {+ if (event.source === window && isPageAgentReplyMessage(event.data)) {+ handler(event.data.reply)+ }+ }+ window.addEventListener('message', listener)+ return () => window.removeEventListener('message', listener)+}++/** Resolves with null when the page has no posthog-js. */+export function requestPageAnalytics(): Promise<PageAnalyticsInfo | null> {+ return new Promise((resolve) => {+ const id = postToPageAgent({ method: 'read-analytics' })+ const finish = (info: PageAnalyticsInfo | null): void => {+ clearTimeout(timeout)+ removeListener()+ resolve(info)+ }+ const timeout = setTimeout(() => finish(null), ANALYTICS_TIMEOUT_MS)+ const removeListener = onPageAgentReply((reply) => {+ if (reply.kind === 'analytics' && reply.id === id) {+ finish(reply.info)+ }+ })+ })+}++/** The page agent reports by itself when a page's posthog-js loads after the page tools started. */+export function onPagePosthogAppeared(handler: () => void): void {+ onPageAgentReply((reply) => {+ if (reply.kind === 'analytics' && reply.id === null && reply.info) {+ handler()+ }+ })+}++/** Stands in for the page's posthog-js in the content script, with the settings the page agent read from it. */+export class PagePosthogBridge {+ /** The parts of posthog-js that the toolbar's logics read. */+ readonly posthog: PostHog++ constructor(info: PageAnalyticsInfo) {+ this.posthog = {+ version: info.version ?? undefined,+ config: {+ disable_scroll_properties: info.scrollPropertiesDisabled,+ scroll_root_selector: info.scrollRootSelector ?? undefined,+ },+ heatmaps: info.heatmapsEnabled === null ? undefined : { isEnabled: info.heatmapsEnabled },+ // Matches posthog-js, which measures scroll depth on the page's scroll root when the config names one.+ scrollManager: { scrollY: () => scrollRoot(info.scrollRootSelector)?.scrollTop ?? window.scrollY },+ } as unknown as PostHog+ }+}++function scrollRoot(selector: string | string[] | null): Element | null {+ for (const candidate of Array.isArray(selector) ? selector : selector ? [selector] : []) {+ try {+ const element = document.querySelector(candidate)+ if (element) {+ return element+ }+ } catch {+ // The page's config names an invalid selector, which posthog-js skips too.+ }+ }+ return null+}diff --git a/frontend/src/toolbar/extension/pageToolbarBridge.ts b/frontend/src/toolbar/extension/pageToolbarBridge.tsnew file mode 100644index 000000000000..a219971e43fc--- /dev/null+++ b/frontend/src/toolbar/extension/pageToolbarBridge.ts@@ -0,0 +1,141 @@+import type {+ CommonFilters,+ HeatmapFilters,+ HeatmapFixedPositionMode,+ ScrollDepthPosthogJsError,+} from 'lib/components/heatmaps/types'++import type { ActionStepType } from '~/types'++import type { PageHeatmapCommand } from './extensionPageHeatmapLogic'+import type { PageInspectCommand, PageSessionCommand } from './extensionPageToolbarLogic'++/**+ * The content script runs the toolbar's own logics in the page, signed in with the extension's OAuth tokens. The panel+ * shows their controls. A port carries commands to the page and state back to the panel.+ */++// pinned: extension port name, the panel and an already injected content script must agree on it+export const PAGE_TOOLBAR_PORT = 'posthog-toolbar-page'++export type PageToolbarMode = 'none' | 'heatmap' | 'inspect'++/** What the content script reads from the page's posthog-js through the page agent. */+export interface PageAnalyticsInfo {+ version: string | null+ scrollPropertiesDisabled: boolean+ /** The page's `scroll_root_selector`, which posthog-js measures scroll depth on instead of the window. */+ scrollRootSelector: string | string[] | null+ /** Null when the posthog-js version has no heatmaps module. */+ heatmapsEnabled: boolean | null+}++export interface PageToolbarTokens {+ accessToken: string+ refreshToken: string | null+ clientId: string+}++export interface PageToolbarSession extends PageToolbarTokens {+ uiHost: string+ dataAttributes: string[]+}++/** Each tool keeps its command types next to the logic that runs them in the page. */+export interface PageToolCommands {+ session: PageSessionCommand+ inspect: PageInspectCommand+ heatmap: PageHeatmapCommand+}++export type PageToolName = keyof PageToolCommands++export type PageToolbarCommand = {+ [Tool in PageToolName]: { tool: Tool; command: PageToolCommands[Tool] }+}[PageToolName]++/** The panel sends `start` once per connection, then commands. */+export type PageToolbarRequest = { type: 'start'; session: PageToolbarSession; href: string } | PageToolbarCommand++export interface InspectedElementInfo {+ tagName: string+ actionStep: ActionStepType | null+ /** Null when the clickmap has no clicks for the element. */+ stats: {+ count: number+ clickCount: number+ rageclickCount: number+ deadclickCount: number+ rank: number+ } | null+ actions: { id: number; name: string | null }[]+}++export interface PageToolbarInspectState {+ /** The hovered or selected element in inspect mode, or an element picked from the clickmap list. */+ element: InspectedElementInfo | null+ isSelected: boolean+}++export interface PageToolbarHeatmapState {+ wildcardHref: string+ autoWildcardEnabled: boolean+ wildcardHrefTooSpecific: boolean+ wildcardHrefEndsWithSlash: boolean+ commonFilters: CommonFilters+ heatmapFilters: HeatmapFilters+ heatmapColorPalette: string | null+ heatmapFixedPositionMode: HeatmapFixedPositionMode+ viewportRange: { min: number; max: number }+ rawHeatmapLoading: boolean+ /** Whether the page's posthog-js collects heatmap data. `unknown` when the page has no `window.posthog`. */+ heatmapsCollection: 'enabled' | 'disabled' | 'unsupported' | 'unknown'+ scrollDepthPosthogJsError: ScrollDepthPosthogJsError+ clickmapsEnabled: boolean+ clickmapLoading: boolean+ processingProgress: { processed: number; total: number } | null+ matchLinksByHref: boolean+ countedElements: { text: string; tagName: string; count: number }[]+ clickCount: number+ canLoadMoreElementStats: boolean+ loadedElementStatsCount: number+ loadingAllElementStats: boolean+ areaSelectionActive: boolean+ areaFilter: { selector: string | null; tagName: string } | null+ savingHeatmap: boolean+ saveProgress: { done: number; total: number } | null+ saveResult: HeatmapSaveResult | null+}++export type HeatmapSaveResult =+ | { status: 'saved'; shortId: string; savedWidths: number; totalWidths: number }+ | { status: 'failed'; error: string }++export interface PageToolbarState {+ mode: PageToolbarMode+ inspect: PageToolbarInspectState+ heatmap: PageToolbarHeatmapState+}++export type PageToolbarMessage =+ | { type: 'state'; state: PageToolbarState }+ /** The slices that changed since the last message. The rest keep their earlier value. */+ | { type: 'patch'; patch: Partial<PageToolbarState> }+ /** The page refreshed the tokens, which rotates the refresh token. */+ | { type: 'tokens'; tokens: PageToolbarTokens }+ | { type: 'token-expired' }++function isObject(message: unknown): message is Record<string, unknown> {+ return !!message && typeof message === 'object'+}++export function isPageToolbarRequest(message: unknown): message is PageToolbarRequest {+ return (+ isObject(message) &&+ (message.type === 'start' || (typeof message.tool === 'string' && isObject(message.command)))+ )+}++export function isPageToolbarMessage(message: unknown): message is PageToolbarMessage {+ return isObject(message) && typeof message.type === 'string'+}diff --git a/frontend/src/toolbar/extension/pageToolbarHost.tsx b/frontend/src/toolbar/extension/pageToolbarHost.tsxnew file mode 100644index 000000000000..2bbbc6f1d70e--- /dev/null+++ b/frontend/src/toolbar/extension/pageToolbarHost.tsx@@ -0,0 +1,238 @@+import { getContext } from 'kea'+import { Root, createRoot } from 'react-dom/client'++import { ElementOverlays } from '~/toolbar/elements/ElementOverlays'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { ToolbarProps } from '~/types'++import { ExtensionPort, extensionFileUrl, onPageToolbarConnect } from './extensionBrowser'+import { extensionPageToolbarLogic, getPageToolbarState } from './extensionPageToolbarLogic'+import { PagePosthogBridge, onPagePosthogAppeared, requestPageAnalytics } from './pagePosthogBridge'+import {+ PageToolbarMessage,+ PageToolbarMode,+ PageToolbarSession,+ PageToolbarState,+ isPageToolbarRequest,+} from './pageToolbarBridge'++const STATE_POST_INTERVAL_MS = 100++// A reload or a quick reopen of the panel keeps the page tools, and their loaded data, for this long.+const IDLE_STOP_MS = 30 * 1000++function PageToolbarOverlays(): JSX.Element {+ return (+ // The toolbar stylesheet scopes its colors to a theme attribute.+ // eslint-disable-next-line react/no-unknown-property+ <div {...{ theme: 'light' }}>+ <ElementOverlays showHeatmapCanvas />+ </div>+ )+}++export class PageToolbarHost {+ private session: { session: PageToolbarSession; href: string } | null = null+ private uiHost: string | null = null+ private posthogBridge: PagePosthogBridge | null = null+ private unmountLogics: (() => void) | null = null+ private overlayRoot: Root | null = null+ private ports = new Set<ExtensionPort>()+ private lastState: PageToolbarState | null = null+ private lastAccessToken: string | null = null+ private postTimeout: ReturnType<typeof setTimeout> | null = null+ private idleTimeout: ReturnType<typeof setTimeout> | null = null+ private starting: Promise<void> | null = null++ constructor(+ private readonly shadowRoot: ShadowRoot,+ private readonly resetLogics: () => void+ ) {}++ listen(): void {+ onPageToolbarConnect((port) => this.addPort(port))+ // A page that loads posthog-js after the page tools started gets them again with the page's posthog-js.+ onPagePosthogAppeared(() => {+ const current = this.session+ if (this.unmountLogics && !this.posthogBridge && current) {+ const { mode } = extensionPageToolbarLogic.values+ this.stop()+ this.queueStart(current.session, current.href, [...this.ports], mode)+ }+ })+ }++ private addPort(port: ExtensionPort): void {+ this.ports.add(port)+ this.clearIdleTimeout()+ port.onMessage.addListener((message) => {+ if (!isPageToolbarRequest(message)) {+ return+ }+ if ('tool' in message) {+ void this.starting?.then(() => {+ if (this.unmountLogics) {+ extensionPageToolbarLogic.actions.handleCommand(message)+ }+ })+ return+ }+ this.queueStart(message.session, message.href, [port])+ })+ port.onDisconnect.addListener(() => {+ this.ports.delete(port)+ if (this.ports.size === 0 && this.unmountLogics) {+ // Without a panel nobody can turn the page tools off, so they stop with the last panel.+ extensionPageToolbarLogic.actions.setMode('none')+ this.idleTimeout = setTimeout(() => this.stop(), IDLE_STOP_MS)+ }+ })+ }++ /** Starts run one after another, so two panels connecting at once can't mount the page tools twice. */+ private queueStart(+ session: PageToolbarSession,+ href: string,+ ports: ExtensionPort[],+ mode?: PageToolbarMode+ ): void {+ this.starting = (this.starting ?? Promise.resolve())+ .then(() => this.start(session, href))+ .then(() => {+ if (mode && mode !== 'none') {+ extensionPageToolbarLogic.actions.setMode(mode)+ }+ ports.forEach((port) => this.postFullState(port))+ })+ }++ private async start(session: PageToolbarSession, href: string): Promise<void> {+ this.session = { session, href }+ if (this.unmountLogics && this.uiHost === session.uiHost) {+ toolbarConfigLogic.actions.setOAuthTokens(session.accessToken, session.refreshToken, session.clientId)+ extensionPageToolbarLogic.actions.handleCommand({ tool: 'session', command: { type: 'set-href', href } })+ return+ }+ this.stop()+ const pageAnalytics = await requestPageAnalytics()+ this.posthogBridge = pageAnalytics ? new PagePosthogBridge(pageAnalytics) : null+ const props: ToolbarProps = {+ source: 'extension',+ uiHost: session.uiHost,+ accessToken: session.accessToken,+ refreshToken: session.refreshToken ?? undefined,+ clientId: session.clientId,+ dataAttributes: session.dataAttributes,+ posthog: this.posthogBridge?.posthog,+ }+ const unsubscribe = getContext().store.subscribe(() => this.scheduleStatePost())+ const unmountConfig = toolbarConfigLogic(props).mount()+ const unmountPageToolbar = extensionPageToolbarLogic.mount()+ this.unmountLogics = () => {+ unsubscribe()+ unmountPageToolbar()+ unmountConfig()+ // The toolbar mounts some logics for good, and they keep toolbarConfigLogic with the last session's props+ // mounted. A fresh context makes the next start use the new host and tokens.+ this.resetLogics()+ }+ this.uiHost = session.uiHost+ this.lastAccessToken = session.accessToken+ extensionPageToolbarLogic.actions.handleCommand({ tool: 'session', command: { type: 'set-href', href } })+ this.renderOverlays()+ }++ private stop(): void {+ this.clearIdleTimeout()+ if (this.postTimeout !== null) {+ clearTimeout(this.postTimeout)+ this.postTimeout = null+ }+ this.shadowRoot+ .querySelectorAll(`link[href="${extensionFileUrl('content.css')}"]`)+ .forEach((link) => link.remove())+ this.overlayRoot?.unmount()+ this.overlayRoot = null+ this.unmountLogics?.()+ this.unmountLogics = null+ this.posthogBridge = null+ this.uiHost = null+ this.lastState = null+ }++ private clearIdleTimeout(): void {+ if (this.idleTimeout !== null) {+ clearTimeout(this.idleTimeout)+ this.idleTimeout = null+ }+ }++ private renderOverlays(): void {+ const stylesheet = document.createElement('link')+ stylesheet.rel = 'stylesheet'+ stylesheet.href = extensionFileUrl('content.css')+ const container = document.createElement('div')+ const overlayRoot = createRoot(container)+ this.overlayRoot = overlayRoot+ // heatmap.js sizes its canvas once, when it mounts, so the overlays wait for the stylesheet that sizes them.+ const render = (): void => {+ if (this.overlayRoot === overlayRoot) {+ overlayRoot.render(<PageToolbarOverlays />)+ }+ }+ stylesheet.addEventListener('load', render, { once: true })+ stylesheet.addEventListener('error', render, { once: true })+ this.shadowRoot.append(stylesheet, container)+ }++ private scheduleStatePost(): void {+ if (this.postTimeout === null && this.unmountLogics && this.ports.size > 0) {+ this.postTimeout = setTimeout(() => {+ this.postTimeout = null+ this.postChanges()+ }, STATE_POST_INTERVAL_MS)+ }+ }++ /** A new panel gets every slice, the other panels keep getting patches. */+ private postFullState(port: ExtensionPort): void {+ if (!this.unmountLogics) {+ return+ }+ const state = getPageToolbarState()+ this.lastState = state+ port.postMessage({ type: 'state', state } satisfies PageToolbarMessage)+ }++ private postChanges(): void {+ if (!this.unmountLogics) {+ return+ }+ const { accessToken, refreshToken, clientId } = toolbarConfigLogic.values+ if (accessToken !== this.lastAccessToken) {+ this.lastAccessToken = accessToken+ this.broadcast(+ accessToken && clientId+ ? { type: 'tokens', tokens: { accessToken, refreshToken, clientId } }+ : { type: 'token-expired' }+ )+ }+ const state = getPageToolbarState()+ const previous = this.lastState+ this.lastState = state+ const patch = Object.fromEntries(+ (Object.keys(state) as (keyof PageToolbarState)[])+ .filter((slice) => !previous || state[slice] !== previous[slice])+ .map((slice) => [slice, state[slice]])+ ) as Partial<PageToolbarState>+ if (Object.keys(patch).length > 0) {+ this.broadcast({ type: 'patch', patch })+ }+ }++ private broadcast(message: PageToolbarMessage): void {+ for (const port of this.ports) {+ port.postMessage(message)+ }+ }+}diff --git a/frontend/src/toolbar/extension/panel.tsx b/frontend/src/toolbar/extension/panel.tsxindex e954eedfa052..1dda9ed21bcc 100644--- a/frontend/src/toolbar/extension/panel.tsx+++ b/frontend/src/toolbar/extension/panel.tsx@@ -5,11 +5,13 @@ import { loadersPlugin } from 'kea-loaders'import { subscriptionsPlugin } from 'kea-subscriptions'import { createRoot } from 'react-dom/client'+import { extensionAuthLogic } from './extensionAuthLogic'import { ExtensionPanel } from './ExtensionPanel'import { extensionPanelLogic } from './extensionPanelLogic'resetContext({ plugins: [loadersPlugin, subscriptionsPlugin] })extensionPanelLogic.mount()+extensionAuthLogic.mount()const container = document.getElementById('root')if (container) {diff --git a/frontend/src/toolbar/extension/usePageToolDisabledReason.ts b/frontend/src/toolbar/extension/usePageToolDisabledReason.tsnew file mode 100644index 000000000000..b61fedfd29d7--- /dev/null+++ b/frontend/src/toolbar/extension/usePageToolDisabledReason.ts@@ -0,0 +1,26 @@+import { useValues } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'++import { ToolbarFeatureGateStatus, toolbarFeatureGateStatus } from '~/toolbar/toolbarEntitlementsLogic'+import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'++import type { PageToolDefinition } from './extensionPageTools'+import { extensionPanelLogic } from './extensionPanelLogic'++const GATE_DISABLED_REASONS: Record<ToolbarFeatureGateStatus, string | null> = {+ available: null,+ checking: 'Checking plan access…',+ unknown: "Couldn't check plan access. Close and open the panel to try again.",+ locked: 'Needs a pay-as-you-go subscription',+}++/** Applies the floating toolbar's plan gate to the panel's tools. */+export function usePageToolDisabledReason(): (tool: PageToolDefinition) => string | null {+ const { entitlements } = useValues(extensionPanelLogic)+ const rolloutEnabled = useToolbarFeatureFlag(FEATURE_FLAGS.TOOLBAR_PAID_HEATMAPS)+ return (tool) =>+ tool.gate+ ? GATE_DISABLED_REASONS[toolbarFeatureGateStatus(tool.gate, rolloutEnabled, entitlements, false)]+ : null+}diff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsxindex 48804673d424..71d6969bc39b 100644--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx@@ -107,6 +107,7 @@ export const HeatmapToolbarMenu = (): JSX.Element => {heatmapAreaFilter,loadingAllElementStats,loadAllPagesLoaded,+ scrollDepthPosthogJsError,} = useValues(heatmapToolbarMenuLogic)const {setCommonFilters,@@ -258,6 +259,7 @@ export const HeatmapToolbarMenu = (): JSX.Element => {setHeatmapColorPalette={setHeatmapColorPalette}heatmapFixedPositionMode={heatmapFixedPositionMode}setHeatmapFixedPositionMode={setHeatmapFixedPositionMode}+ scrollDepthPosthogJsError={scrollDepthPosthogJsError}/><div className="pt-2 border-t mt-2">diff --git a/frontend/src/toolbar/stats/heatmapCaptureLogic.ts b/frontend/src/toolbar/stats/heatmapCaptureLogic.tsindex 697337edb604..f77acf889dc0 100644--- a/frontend/src/toolbar/stats/heatmapCaptureLogic.ts+++ b/frontend/src/toolbar/stats/heatmapCaptureLogic.ts@@ -22,12 +22,12 @@ interface HeatmapCaptureResult {short_id: string}-interface CaptureProgress {+export interface CaptureProgress {done: numbertotal: number}-interface CaptureSummary {+export interface CaptureSummary {savedWidths: numbertotalWidths: number}diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.tsindex 95061572322f..eef00405603c 100644--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts@@ -793,6 +793,55 @@ describe('toolbar toolbarConfigLogic', () => {})})+ it('leaves the page storage alone when the browser extension mounts it', () => {+ const floatingToolbarSession = JSON.stringify({+ accessToken: 'page-access',+ refreshToken: 'page-refresh',+ clientId: 'page-client',+ uiHost: 'http://localhost',+ })+ localStorage.setItem(OAUTH_LOCALSTORAGE_KEY, floatingToolbarSession)+ const logic = toolbarConfigLogic.build({+ source: 'extension',+ uiHost: 'http://localhost',+ accessToken: 'extension-access',+ refreshToken: 'extension-refresh',+ clientId: 'extension-client',+ })+ logic.mount()++ logic.actions.setOAuthTokens('rotated-access', 'rotated-refresh', 'extension-client')+ expect(logic.values.accessToken).toEqual('rotated-access')+ logic.actions.tokenExpired()+ logic.actions.logout()++ expect(localStorage.getItem(OAUTH_LOCALSTORAGE_KEY)).toEqual(floatingToolbarSession)+ expect(localStorage.getItem('_postHogToolbarParams')).toBeNull()+ })++ it.each(['authenticate', 'confirmAuthenticate'] as const)(+ 'expires the session instead of redirecting the page on %s when the browser extension mounts it',+ async (action) => {+ const pageHref = window.location.href+ const logic = toolbarConfigLogic.build({+ source: 'extension',+ uiHost: 'https://us.posthog.com',+ accessToken: 'extension-access',+ clientId: 'extension-client',+ })+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions[action]()+ })+ .toDispatchActions(['tokenExpired'])+ .toMatchValues({ accessToken: null, authStatus: 'idle' })++ expect(localStorage.getItem(PKCE_STORAGE_KEY)).toBeNull()+ expect(window.location.href).toEqual(pageHref)+ }+ )+it('logout clears both localStorage keys', () => {const logic = toolbarConfigLogic.build({ apiURL: 'http://localhost' })logic.mount()diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.tsindex 84b0845128d5..04bd4c76e517 100644--- a/frontend/src/toolbar/toolbarConfigLogic.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.ts@@ -27,6 +27,7 @@ import {OAUTH_LOCALSTORAGE_KEY,PKCE_STORAGE_KEY,readToolbarAuthHash,+ requestOAuthTokens,safeFetch,} from './utils'@@ -56,6 +57,7 @@ export interface toolbarConfigLogicValues {experimentId: ExperimentIdType | nullisAuthenticated: booleanisTrustedUiHost: boolean+ ownsPageSession: booleanposthog: PostHog | nullproductTourId: string | nullprops: ToolbarProps@@ -122,6 +124,7 @@ export interface toolbarConfigLogicActions {export interface toolbarConfigLogicMeta {__keaTypeGenInternalSelectorTypes: {posthog: (props: ToolbarProps) => PostHog | null+ ownsPageSession: (props: ToolbarProps) => booleanuiHost: (props: ToolbarProps) => stringapiHostResolution: (props: ToolbarProps) => {host: string@@ -213,6 +216,12 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([selectors({posthog: [(s) => [s.props], (props: ToolbarProps) => props.posthog ?? null],+ /**+ * False when the browser extension mounts this logic in its content script with tokens it owns. The page's URL+ * hash and localStorage belong to the customer's site there, and posthog-js launches the floating toolbar from+ * that storage.+ */+ ownsPageSession: [(s) => [s.props], (props: ToolbarProps): boolean => props.source !== 'extension'],// PostHog app URL used for OAuth and navigation links.//// Every candidate (props.uiHost, requestRouter, config.ui_host, apiURL) is@@ -311,6 +320,13 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([authenticate: () => {toolbarLogger.info('auth', 'Authentication initiated')+ // The extension signs in from its panel. OAuth here would write PKCE to the+ // customer's storage and navigate their tab, so hand the panel an expired session.+ if (!values.ownsPageSession) {+ actions.tokenExpired()+ return+ }+// If the uiHost check found a problem, open the config modal instead of proceeding.if (values.authStatus === 'error') {toolbarPosthogJS.capture('toolbar ui host config modal opened', { ui_host: values.uiHost })@@ -334,6 +350,10 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([actions.openAuthConfirmModal()},confirmAuthenticate: async () => {+ if (!values.ownsPageSession) {+ actions.tokenExpired()+ return+ }// Re-check status because the modal can sit open arbitrarily long — the// reachability check may have flipped to 'error' while the user read the// dialog, and we must not redirect to an unreachable host.@@ -387,6 +407,9 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([logout: () => {toolbarLogger.info('auth', 'User logged out')toolbarPosthogJS.capture('toolbar logout')+ if (!values.ownsPageSession) {+ return+ }localStorage.removeItem(LOCALSTORAGE_KEY)localStorage.removeItem(OAUTH_LOCALSTORAGE_KEY)localStorage.removeItem(PKCE_STORAGE_KEY)@@ -395,6 +418,9 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([tokenExpired: () => {toolbarPosthogJS.capture('toolbar token expired')toolbarLogger.warn('auth', 'Session expired, clearing session')+ if (!values.ownsPageSession) {+ return+ }if (values.props.source !== 'localstorage') {lemonToast.error('Please re-authenticate to continue using the toolbar.')}@@ -405,6 +431,9 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([actions.persistConfig()},persistConfig: () => {+ if (!values.ownsPageSession) {+ return+ }// Most params we don't change, only those that we may have modified during the sessionconst toolbarParams: ToolbarProps = {...values.props,@@ -442,6 +471,9 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([})),afterMount(({ props, values, actions, cache }) => {+ if (!values.ownsPageSession) {+ return+ }// Read hash params WITHOUT modifying the URL. The URL cleanup is deferred// to avoid triggering SPA routers that watch for history.replaceState changes// and could destroy/re-mount the page (and the toolbar) mid-initialization.@@ -483,11 +515,13 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([verifyUiHostReachability(props, values, actions, authParams)}),- beforeUnmount(({ cache }) => {+ beforeUnmount(({ values, cache }) => {if (cache.hashRetryTimeout !== undefined) {clearTimeout(cache.hashRetryTimeout)}- cleanToolbarAuthHash()+ if (values.ownsPageSession) {+ cleanToolbarAuthHash()+ }}),])@@ -821,13 +855,7 @@ function startCodeExchange(authParams: { code: string; clientId: string },actions: TokenActions): void {- void exchangeCodeForTokens(- `${uiHost}/oauth/token/`,- `${uiHost}/toolbar_oauth/callback`,- authParams.code,- authParams.clientId,- actions- ).then((succeeded) => {+ void exchangeCodeForTokens(uiHost, authParams.code, authParams.clientId, actions).then((succeeded) => {if (!succeeded) {// Code exchange failed (stale code, expired PKCE, network error).// Fall back to stored OAuth tokens so users don't have to@@ -844,8 +872,7 @@ function startCodeExchange(const PKCE_TTL_MS = 10 * 60 * 1000 // 10 minutesasync function exchangeCodeForTokens(- tokenEndpoint: string,- redirectUri: string,+ uiHost: string,code: string,clientId: string,actions: TokenActions@@ -872,27 +899,14 @@ async function exchangeCodeForTokens(return false}- const body = new URLSearchParams({- grant_type: 'authorization_code',- client_id: clientId,- code,- redirect_uri: redirectUri,- code_verifier: pkceData.verifier,- })-// Every failure in the exchange is an expected request outcome (stale/reused code,// expired PKCE, network hiccup, proxy error page) - tracked via the capture events// and logs, never reported to error tracking.const startTime = performance.now()try {- const res = await safeFetch(tokenEndpoint, {- method: 'POST',- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },- body: body.toString(),- })- const data = await res.json().catch(() => null)- const access = asNonEmptyString(data?.access_token)- const refresh = asNonEmptyString(data?.refresh_token)+ const res = await requestOAuthTokens({ uiHost, code, clientId, verifier: pkceData.verifier })+ const access = res.accessToken+ const refresh = res.refreshToken// A refresh token is optional: impersonation-minted tokens are refresh-less by design// (they can't outlive the admin's impersonation session), so require only the access// token here. Without a refresh token the short-lived access token is used until it@@ -906,7 +920,7 @@ async function exchangeCodeForTokens(actions.setOAuthTokens(access, refresh, clientId)return true}- const errorString = asNonEmptyString(data?.error) ?? 'unknown'+ const errorString = res.error ?? 'unknown'toolbarPosthogJS.capture('toolbar oauth exchange', {status: 'error',error: errorString,diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.tsindex fec5520a3c61..f17c3bcc52b9 100644--- a/frontend/src/toolbar/utils.ts+++ b/frontend/src/toolbar/utils.ts@@ -13,6 +13,24 @@ import { Experiment, ActionStepType, ExperimentStatus } from '~/types'import { ActionStepPropertyKey } from './actions/ActionStep'export const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'+// The browser extension's content script draws its overlay in this host.+export const TOOLBAR_EXTENSION_ID = '__POSTHOG_TOOLBAR_EXTENSION__'+// pinned: DOM attribute, the floating toolbar and the extension mark their roots with it so neither counts as page content+export const TOOLBAR_ROOT_ATTRIBUTE = 'data-posthog-toolbar-root'++export function isToolbarRootElement(element: Element): boolean {+ return element.hasAttribute(TOOLBAR_ROOT_ATTRIBUTE)+}++/** True for a toolbar root and everything inside it, shadow DOM included. */+export function isInToolbarRoot(element: HTMLElement): boolean {+ for (let current: HTMLElement | null = element; current; current = getParent(current)) {+ if (isToolbarRootElement(current)) {+ return true+ }+ }+ return false+}// Props arrive via the `__posthog=<base64>` URL fragment, so the static type is not// load-bearing at runtime — verify before storing strings that flow into auth headers.@@ -67,11 +85,15 @@ export interface ToolbarAuthParams {* Returns the matched params if found, or null.*/export function readToolbarAuthHash(): ToolbarAuthParams | null {+ return parseToolbarAuthHash(window.location.hash)+}++export function parseToolbarAuthHash(rawHash: string): ToolbarAuthParams | null {let hash: stringtry {- hash = decodeURIComponent(window.location.hash)+ hash = decodeURIComponent(rawHash)} catch {- hash = window.location.hash+ hash = rawHash}const codeMatch = hash.match(/__posthog_toolbar=code:([^,]+),client_id:([^,&]+)/)if (!codeMatch) {@@ -125,6 +147,38 @@ export function cleanToolbarAuthHash(): void {history.replaceState(null, '', location.pathname + location.search + (cleanHash || ''))}+/** Exchanges a toolbar OAuth code for tokens, for the floating toolbar and the browser extension. Rejects on a network failure. */+export async function requestOAuthTokens({+ uiHost,+ code,+ clientId,+ verifier,+}: {+ uiHost: string+ code: string+ clientId: string+ verifier: string+}): Promise<{ status: number; accessToken: string | null; refreshToken: string | null; error: string | null }> {+ const response = await safeFetch(`${uiHost}/oauth/token/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ client_id: clientId,+ code,+ redirect_uri: `${uiHost}/toolbar_oauth/callback`,+ code_verifier: verifier,+ }).toString(),+ })+ const data = await response.json().catch(() => null)+ return {+ status: response.status,+ accessToken: asNonEmptyString(data?.access_token),+ refreshToken: asNonEmptyString(data?.refresh_token),+ error: asNonEmptyString(data?.error),+ }+}+export async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {const bytes = new Uint8Array(48)crypto.getRandomValues(bytes)@@ -229,10 +283,6 @@ export function elementToActionStep(element: HTMLElement, dataAttributes: string}}-export function getToolbarRootElement(): HTMLElement | null {- return window.document.getElementById(TOOLBAR_ID) || null-}-export function hasCursorPointer(element: HTMLElement): boolean {return window.getComputedStyle(element)?.getPropertyValue('cursor') === 'pointer'}@@ -258,8 +308,8 @@ export function trimElement(if (!element) {return null}- const rootElement = getToolbarRootElement()- if (rootElement && isParentOf(element, rootElement)) {+ const parent = getParent(element)+ if (parent && isInToolbarRoot(parent)) {return null}@@ -392,7 +442,7 @@ export function getAllClickTargets(})const shadowElements = allElements- .filter((el) => el.shadowRoot && el.getAttribute('id') !== TOOLBAR_ID)+ .filter((el) => el.shadowRoot && !isToolbarRootElement(el)).map((el: HTMLElement) => (el.shadowRoot ? getAllClickTargets(el.shadowRoot, targetSelector) : [])).reduce((a, b) => {a.push(...b)diff --git a/frontend/src/toolbar/utils/responsiveScreenshot.ts b/frontend/src/toolbar/utils/responsiveScreenshot.tsindex 135440862149..968cb26a1b98 100644--- a/frontend/src/toolbar/utils/responsiveScreenshot.ts+++ b/frontend/src/toolbar/utils/responsiveScreenshot.ts@@ -3,7 +3,7 @@ import { BLANK_IMAGE } from 'lib/utils/captureElementImage'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'-import { TOOLBAR_ID, toError } from '~/toolbar/utils'+import { TOOLBAR_ROOT_ATTRIBUTE, toError } from '~/toolbar/utils'import { captureElementScreenshot } from '~/toolbar/utils/screenshot'export const RESPONSIVE_CAPTURE_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]@@ -36,7 +36,7 @@ function populateIframe(iframe: HTMLIFrameElement): void {const importedHtml = doc.importNode(document.documentElement, true)importedHtml.querySelectorAll('script, noscript').forEach((node) => node.remove())- importedHtml.querySelector(`#${TOOLBAR_ID}`)?.remove()+ importedHtml.querySelectorAll(`[${TOOLBAR_ROOT_ATTRIBUTE}]`).forEach((node) => node.remove())let head = importedHtml.querySelector('head')if (!head) {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b300bd61c67b..08697061629c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1039,7 +1039,7 @@ export const TOOLBAR_USER_INTENTS = ['edit-product-tour','preview-product-tour',] as const satisfies readonly ToolbarUserIntent[]-export type ToolbarSource = 'url' | 'localstorage'+export type ToolbarSource = 'url' | 'localstorage' | 'extension'export type ToolbarVersion = 'toolbar'export type ExperimentIdType = number | 'new' | 'web'diff --git a/frontend/toolbar-config.mjs b/frontend/toolbar-config.mjsindex ecd5bb308b8c..9b79f08db771 100644--- a/frontend/toolbar-config.mjs+++ b/frontend/toolbar-config.mjs@@ -71,7 +71,7 @@ const deniedPatterns = [/scenes\/billing/]* CloudFront limit), bin/check-toolbar-graph.mjs (boundary edges, forbidden packages, source* budget), and bin/check-toolbar-csp-eval.mjs (no eval on customer pages).*/-function createToolbarModulePlugin(dirname) {+function createToolbarModulePlugin(dirname, extraDeniedPatterns = []) {// Shims must also catch relative imports of the same modules (e.g. dataThemeLogic's// `./teamLogic`), otherwise the real logic and its whole app graph leak into the bundle.// Map each shimmed module's extensionless absolute path to its shim.@@ -101,7 +101,8 @@ function createToolbarModulePlugin(dirname) {}const shouldDeny =- deniedPaths.includes(args.path) || deniedPatterns.some((pattern) => pattern.test(args.path))+ deniedPaths.includes(args.path) ||+ [...deniedPatterns, ...extraDeniedPatterns].some((pattern) => pattern.test(args.path))if (shouldDeny) {return { path: args.path, namespace: 'empty-module', sideEffects: false }}@@ -250,7 +251,8 @@ export async function finalizeToolbarBuild(dirname, buildResponse) {// The browser extension ships one panel bundle in a folder per browser. Only the manifest differs://// dist/toolbar-extension/<browser>/manifest.json-// dist/toolbar-extension/<browser>/panel.html, panel.js, panel.css, background.js, assets/, icons/+// dist/toolbar-extension/<browser>/panel.html, panel.js, panel.css, background.js, content.js, content.css,+// assets/, icons///// Load the folder unpacked in Chrome, or as a temporary add-on in Firefox.const TOOLBAR_EXTENSION_BROWSERS = ['chrome', 'firefox']@@ -311,15 +313,29 @@ export function getToolbarExtensionBuildConfig(dirname) {}}-/** Firefox doesn't run a module as a background script, so the background script is one classic script. */+/**+ * The panel injects content.js into the tab with `scripting.executeScript`, which runs a file as a classic script, and+ * Firefox doesn't run a module as a background script. So each of these scripts is one self-contained IIFE.+ */export function getToolbarExtensionScriptsBuildConfig(dirname) {return {...toolbarExtensionBaseConfig(dirname),name: 'Toolbar extension scripts',- entryPoints: { background: 'src/toolbar/extension/background.ts' },+ entryPoints: {+ background: 'src/toolbar/extension/background.ts',+ content: 'src/toolbar/extension/content.tsx',+ 'page-agent': 'src/toolbar/extension/pageAgent.ts',+ },format: 'iife',splitting: false,- extraPlugins: [createToolbarModulePlugin(dirname)],+ // An IIFE inlines every lazy import. The content script never runs hedgehog mode (pixi needs `new Function`,+ // which Manifest V3 forbids) or the product tours editor, so they stay out of every page it's injected into.+ extraPlugins: [+ createToolbarModulePlugin(dirname, [+ /^@posthog\/hedgehog-mode$/,+ /product-tours\/editor\/generateStepHtml$/,+ ]),+ ],}}@@ -336,8 +352,9 @@ function buildToolbarExtensionManifest(browser) {default_title: 'Open PostHog',default_icon: TOOLBAR_EXTENSION_ICONS,},- permissions: ['storage'],+ permissions: ['scripting', 'storage'],host_permissions: ['http://*/*', 'https://*/*'],+ web_accessible_resources: [{ resources: ['content.css', 'assets/*'], matches: ['http://*/*', 'https://*/*'] }],}if (browser === 'firefox') {manifest.sidebar_action = {