Skip to content

: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.

feat(toolbar): edit actions and override flags in the extension side panel (#121476)

Rafael Audibertef116d925864
diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.md
index 2b9d41937d71..393fd71bd59d 100644
--- a/frontend/src/toolbar/TELEMETRY.md
+++ b/frontend/src/toolbar/TELEMETRY.md
@@ -366,9 +366,10 @@ Fired when the side panel shows a new state.
Fired when the user runs a tool on the page from the extension.
-| Property | Type | Description |
-| -------- | -------- | --------------------------------------------- |
-| `tool` | `string` | `'inspect'`, `'heatmap'`, or `'save-heatmap'` |
+| Property | Type | Description |
+| --------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `tool` | `string` | `'inspect'`, `'heatmap'`, `'save-heatmap'`, `'actions'`, `'create-action'`, `'save-action'`, `'flags'`, `'override-flag'`, `'clear-flag-overrides'`, or `'impersonate-flags'` |
+| `payload` | `boolean \| undefined` | `true` when `'override-flag'` sets a payload |
**File:** `extension/extensionTelemetry.ts`
diff --git a/frontend/src/toolbar/actions/ActionStepEditor.tsx b/frontend/src/toolbar/actions/ActionStepEditor.tsx
new file mode 100644
index 000000000000..23729fe7c259
--- /dev/null
+++ b/frontend/src/toolbar/actions/ActionStepEditor.tsx
@@ -0,0 +1,103 @@
+import { IconPencil, IconSearch, IconTrash } from '@posthog/icons'
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { StepField } from '~/toolbar/actions/StepField'
+import { SelectorQualityWarning } from '~/toolbar/elements/SelectorQualityWarning'
+import { ActionStepForm } from '~/toolbar/types'
+
+interface ActionStepEditorProps {
+ step: ActionStepForm
+ index: number
+ /** True while the user picks this step's element on the page. */
+ inspecting: boolean
+ onInspect: () => void
+ onEditSelector: () => void
+ onRemove: () => void
+}
+
+/** One element of an action form. Render it inside the form's `Group name={['steps', index]}`. */
+export function ActionStepEditor({
+ step,
+ index,
+ inspecting,
+ onInspect,
+ onEditSelector,
+ onRemove,
+}: ActionStepEditorProps): JSX.Element {
+ return (
+ <>
+ <div className="flex flex-row justify-between">
+ <h3>
+ {index > 0 ? 'OR ' : null}Element #{index + 1}
+ </h3>
+ <LemonButton type="tertiary" size="small" onClick={onRemove} sideIcon={<IconTrash />}>
+ Remove
+ </LemonButton>
+ </div>
+
+ <div className="action-inspect">
+ <LemonButton
+ size="small"
+ type={inspecting ? 'primary' : 'secondary'}
+ onClick={(e) => {
+ e.stopPropagation()
+ onInspect()
+ }}
+ icon={<IconSearch />}
+ >
+ {step?.event === '$autocapture' ? 'Change Element' : 'Select Element'}
+ </LemonButton>
+ </div>
+
+ {step?.event === '$autocapture' || inspecting ? (
+ <>
+ <StepField
+ step={step}
+ item="selector"
+ label="Selector"
+ caption="CSS selector that uniquely identifies your element"
+ />
+ <SelectorQualityWarning selector={step?.selector} />
+ <div className="flex flex-row justify-end mb-2">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPencil />}
+ onClick={(e) => {
+ e.stopPropagation()
+ onEditSelector()
+ }}
+ >
+ Edit the selector
+ </LemonButton>
+ </div>
+ <StepField
+ step={step}
+ item="href"
+ label="Link target"
+ caption={
+ <>
+ If your element is a link, the location that the link opens (<code>href</code> tag)
+ </>
+ }
+ />
+ <LemonTag type="highlight">
+ <span className="uppercase">and</span>
+ </LemonTag>
+ <StepField step={step} item="text" label="Text" caption="Text content inside your element" />
+ <LemonTag type="highlight">
+ <span className="uppercase">and</span>
+ </LemonTag>
+ <StepField
+ step={step}
+ item="url"
+ label="Page URL"
+ caption="Elements will match only when triggered from the URL."
+ />
+ </>
+ ) : null}
+ </>
+ )
+}
diff --git a/frontend/src/toolbar/actions/ActionsEditingToolbarMenu.tsx b/frontend/src/toolbar/actions/ActionsEditingToolbarMenu.tsx
index c3a1c4420cdc..7f4b8ea1efff 100644
--- a/frontend/src/toolbar/actions/ActionsEditingToolbarMenu.tsx
+++ b/frontend/src/toolbar/actions/ActionsEditingToolbarMenu.tsx
@@ -1,17 +1,16 @@
import { useActions, useValues } from 'kea'
import { Field, Form, Group } from 'kea-forms'
-import { IconPencil, IconPlus, IconSearch, IconTrash } from '@posthog/icons'
-import { LemonDivider, LemonTag } from '@posthog/lemon-ui'
+import { IconPlus } from '@posthog/icons'
+import { LemonDivider } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { actionsTabLogic } from '~/toolbar/actions/actionsTabLogic'
+import { ActionStepEditor } from '~/toolbar/actions/ActionStepEditor'
import { SelectorEditingModal } from '~/toolbar/actions/SelectorEditingModal'
-import { StepField } from '~/toolbar/actions/StepField'
import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'
-import { SelectorQualityWarning } from '~/toolbar/elements/SelectorQualityWarning'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
export const ActionsEditingToolbarMenu = (): JSX.Element => {
@@ -72,99 +71,27 @@ export const ActionsEditingToolbarMenu = (): JSX.Element => {
<Group key={index} name={['steps', index]}>
<LemonDivider />
<div key={index} className="p-1 flex flex-col gap-2">
- <div className="flex flex-row justify-between">
- <h3>
- {index > 0 ? 'OR ' : null}Element #{index + 1}
- </h3>
- <LemonButton
- type="tertiary"
- size="small"
- onClick={() =>
- setActionFormValue(
- 'steps',
- //actionForm.steps without the step at index
- actionForm.steps?.filter((_, i) => i !== index)
- )
- }
- sideIcon={<IconTrash />}
- >
- Remove
- </LemonButton>
- </div>
-
- <div className="action-inspect">
- <LemonButton
- size="small"
- type={inspectingElement === index ? 'primary' : 'secondary'}
- onClick={(e) => {
- e.stopPropagation()
- inspectForElementWithIndex(inspectingElement === index ? null : index)
- }}
- icon={<IconSearch />}
- >
- {step?.event === '$autocapture' ? 'Change Element' : 'Select Element'}
- </LemonButton>
- </div>
-
- {step?.event === '$autocapture' || inspectingElement === index ? (
- <>
- <StepField
- step={step}
- item="selector"
- label="Selector"
- caption="CSS selector that uniquely identifies your element"
- />
- <SelectorQualityWarning selector={step?.selector} />
- <div className="flex flex-row justify-end mb-2">
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconPencil />}
- onClick={(e) => {
- e.stopPropagation()
- toolbarPosthogJS.capture(
- 'toolbar_manual_selector_modal_opened',
- {
- selector: step?.selector ?? null,
- }
- )
- editSelectorWithIndex(index)
- }}
- >
- Edit the selector
- </LemonButton>
- </div>
- <StepField
- step={step}
- item="href"
- label="Link target"
- caption={
- <>
- If your element is a link, the location that the link opens (
- <code>href</code> tag)
- </>
- }
- />
- <LemonTag type="highlight">
- <span className="uppercase">and</span>
- </LemonTag>
- <StepField
- step={step}
- item="text"
- label="Text"
- caption="Text content inside your element"
- />
- <LemonTag type="highlight">
- <span className="uppercase">and</span>
- </LemonTag>
- <StepField
- step={step}
- item="url"
- label="Page URL"
- caption="Elements will match only when triggered from the URL."
- />
- </>
- ) : null}
+ <ActionStepEditor
+ step={step}
+ index={index}
+ inspecting={inspectingElement === index}
+ onInspect={() =>
+ inspectForElementWithIndex(inspectingElement === index ? null : index)
+ }
+ onEditSelector={() => {
+ toolbarPosthogJS.capture('toolbar_manual_selector_modal_opened', {
+ selector: step?.selector ?? null,
+ })
+ editSelectorWithIndex(index)
+ }}
+ onRemove={() =>
+ setActionFormValue(
+ 'steps',
+ //actionForm.steps without the step at index
+ actionForm.steps?.filter((_, i) => i !== index)
+ )
+ }
+ />
{index === (actionForm.steps?.length || 0) - 1 ? (
<div className="text-right mt-4">
diff --git a/frontend/src/toolbar/actions/SelectorCount.tsx b/frontend/src/toolbar/actions/SelectorCount.tsx
index dda8c5e6167d..9e8041372819 100644
--- a/frontend/src/toolbar/actions/SelectorCount.tsx
+++ b/frontend/src/toolbar/actions/SelectorCount.tsx
@@ -1,30 +1,32 @@
-import { querySelectorAllDeep } from 'query-selector-shadow-dom'
-import { useMemo } from 'react'
+import { useContext, useEffect, useMemo } from 'react'
import { pluralize } from 'lib/utils/strings'
+import { SelectorCountContext } from './SelectorCountContext'
+
interface SelectorCountProps {
selector: string | null
}
export function SelectorCount({ selector }: SelectorCountProps): JSX.Element | null {
- const [matches, selectorError] = useMemo(() => {
- let _selectorError = false
- let _matches = 0
+ const counter = useContext(SelectorCountContext)
+
+ useEffect(() => {
if (selector) {
- try {
- _matches = querySelectorAllDeep(selector).length
- } catch {
- _selectorError = true
- }
+ counter.request(selector)
}
- return [_matches, _selectorError]
- }, [selector])
+ }, [counter, selector])
+
+ const count = useMemo(() => (selector ? counter.count(selector) : 0), [counter, selector])
+
+ if (selector === null || count === undefined) {
+ return null
+ }
- return selector === null ? null : (
+ return (
<>
- <small className={`float-right ${selectorError && 'text-danger'}`}>
- {selectorError ? 'Invalid selector' : `Matches ${pluralize(matches, 'element')}`}
+ <small className={`float-right ${count === null && 'text-danger'}`}>
+ {count === null ? 'Invalid selector' : `Matches ${pluralize(count, 'element')}`}
</small>
</>
)
diff --git a/frontend/src/toolbar/actions/SelectorCountContext.ts b/frontend/src/toolbar/actions/SelectorCountContext.ts
new file mode 100644
index 000000000000..7f8d80b666d4
--- /dev/null
+++ b/frontend/src/toolbar/actions/SelectorCountContext.ts
@@ -0,0 +1,23 @@
+import { querySelectorAllDeep } from 'query-selector-shadow-dom'
+import { createContext } from 'react'
+
+export interface SelectorMatchCounter {
+ /** `undefined` while the count is pending, `null` for an invalid selector. */
+ count: (selector: string) => number | null | undefined
+ request: (selector: string) => void
+}
+
+/** Counts in the document the component renders in, which is the page for the floating toolbar. */
+const pageDocumentCounter: SelectorMatchCounter = {
+ count: (selector) => {
+ try {
+ return querySelectorAllDeep(selector).length
+ } catch {
+ return null
+ }
+ },
+ request: () => {},
+}
+
+// The extension side panel renders the editors in its own page, so it provides a counter for the customer's page.
+export const SelectorCountContext = createContext<SelectorMatchCounter>(pageDocumentCounter)
diff --git a/frontend/src/toolbar/actions/SelectorEditingModal.tsx b/frontend/src/toolbar/actions/SelectorEditingModal.tsx
index 677b8c3a1a8f..147bb69f13b5 100644
--- a/frontend/src/toolbar/actions/SelectorEditingModal.tsx
+++ b/frontend/src/toolbar/actions/SelectorEditingModal.tsx
@@ -6,18 +6,23 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { ElementType } from '~/types'
+import { SelectorCount } from './SelectorCount'
+
export const SelectorEditingModal = ({
isOpen,
setIsOpen,
activeElementChain,
onChange,
startingSelector,
+ checkUniqueness = true,
}: {
isOpen: boolean
setIsOpen: (open: boolean) => void
activeElementChain: ElementType[]
onChange?: (selector: string | null) => void
startingSelector?: string | null
+ /** Pass false where the modal doesn't render in the page whose elements it edits. */
+ checkUniqueness?: boolean
}): JSX.Element => {
const [chosenSelector, setChosenSelector] = useState<string | null>(null)
@@ -50,10 +55,11 @@ export const SelectorEditingModal = ({
editable={true}
highlight={false}
elements={activeElementChain}
- checkUniqueness={true}
+ checkUniqueness={checkUniqueness}
onChange={setChosenSelector}
startingSelector={startingSelector ?? undefined}
/>
+ {!checkUniqueness && chosenSelector ? <SelectorCount selector={chosenSelector} /> : null}
</LemonModal>
)
}
diff --git a/frontend/src/toolbar/actions/actionsTabLogic.test.ts b/frontend/src/toolbar/actions/actionsTabLogic.test.ts
index 6a1f2f47d8ad..32528edc55a8 100644
--- a/frontend/src/toolbar/actions/actionsTabLogic.test.ts
+++ b/frontend/src/toolbar/actions/actionsTabLogic.test.ts
@@ -109,6 +109,7 @@ describe('actionsTabLogic form submission', () => {
})
.delay(0)
.toDispatchActions(['submitActionForm', 'submitActionFormFailure'])
+ .toNotHaveDispatchedActions(['submitActionFormSuccess'])
})
it('handles error response when json parsing fails', async () => {
@@ -128,6 +129,7 @@ describe('actionsTabLogic form submission', () => {
})
.delay(0)
.toDispatchActions(['submitActionForm', 'submitActionFormFailure'])
+ .toNotHaveDispatchedActions(['submitActionFormSuccess'])
})
it('sets creation_context when automatic action creation is enabled', async () => {
diff --git a/frontend/src/toolbar/actions/actionsTabLogic.tsx b/frontend/src/toolbar/actions/actionsTabLogic.tsx
index 5f921ae18dd5..b26c929004d9 100644
--- a/frontend/src/toolbar/actions/actionsTabLogic.tsx
+++ b/frontend/src/toolbar/actions/actionsTabLogic.tsx
@@ -404,8 +404,8 @@ export const actionsTabLogic = kea<actionsTabLogicType>([
})
if (!result.ok) {
- actions.submitActionFormFailure(new Error(result.error.detail), {})
- return
+ // Throwing makes the form report a failure instead of a successful submit.
+ throw new Error(result.error.detail)
}
const response = result.data
breakpoint() // guard against stale async after unmount
@@ -536,7 +536,8 @@ export const actionsTabLogic = kea<actionsTabLogicType>([
actions.showButtonActions()
}
- toolbarLogic.actions.setVisibleMenu('actions')
+ // The browser extension runs this logic without the floating toolbar's bar.
+ toolbarLogic.findMounted()?.actions.setVisibleMenu('actions')
}
},
inspectElementSelected: ({ element, index }) => {
diff --git a/frontend/src/toolbar/extension/ExtensionActionEditor.tsx b/frontend/src/toolbar/extension/ExtensionActionEditor.tsx
new file mode 100644
index 000000000000..3ccb1bdb2bc0
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionActionEditor.tsx
@@ -0,0 +1,121 @@
+import { useActions, useValues } from 'kea'
+import { Field, Form, Group } from 'kea-forms'
+
+import { IconArrowLeft, IconPlus } from '@posthog/icons'
+import { LemonDivider } from '@posthog/lemon-ui'
+
+import { IconOpenInNew } 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 { Link } from 'lib/lemon-ui/Link'
+
+import { ActionStepEditor } from '~/toolbar/actions/ActionStepEditor'
+import { SelectorEditingModal } from '~/toolbar/actions/SelectorEditingModal'
+import { urls } from '~/toolbar/urls'
+
+import { extensionActionsLogic } from './extensionActionsLogic'
+import { extensionPanelLogic } from './extensionPanelLogic'
+
+export function ExtensionActionEditor(): JSX.Element | null {
+ const { actionsState, actionForm, editingSelector, saving } = useValues(extensionActionsLogic)
+ const { selectAction, inspectForStep, setActionFormValue, setEditingSelector, applySelector } =
+ useActions(extensionActionsLogic)
+ const { projectUrl } = useValues(extensionPanelLogic)
+
+ if (!actionsState || actionsState.selectedActionId === null) {
+ return null
+ }
+ const { selectedActionId, inspectingElement, actionFormElementsChains, saveResult } = actionsState
+ const steps = actionForm.steps ?? []
+ const isNew = selectedActionId === 'new'
+
+ return (
+ <>
+ <SelectorEditingModal
+ isOpen={editingSelector !== null}
+ setIsOpen={() => setEditingSelector(null)}
+ activeElementChain={editingSelector !== null ? (actionFormElementsChains[editingSelector] ?? []) : []}
+ startingSelector={editingSelector !== null ? steps[editingSelector]?.selector : null}
+ checkUniqueness={false}
+ onChange={(selector) => {
+ if (selector && editingSelector !== null) {
+ applySelector(editingSelector, selector)
+ }
+ }}
+ />
+ <Form logic={extensionActionsLogic} formKey="actionForm" enableFormOnSubmit className="flex flex-col gap-2">
+ <div className="flex items-center gap-1">
+ <LemonButton
+ size="small"
+ icon={<IconArrowLeft />}
+ tooltip="Back to the actions"
+ onClick={() => selectAction(null)}
+ data-attr="toolbar-extension-action-back"
+ />
+ <span className="font-semibold flex-1">{isNew ? 'New action' : 'Edit action'}</span>
+ {!isNew && (
+ <Link to={projectUrl(urls.action(selectedActionId))} target="_blank" className="text-xs">
+ Open in PostHog <IconOpenInNew />
+ </Link>
+ )}
+ </div>
+ {saveResult?.status === 'failed' && (
+ <LemonBanner type="error">Couldn't save the action: {saveResult.error}</LemonBanner>
+ )}
+ <Field name="name" label="What did your user do?">
+ <LemonInput placeholder="For example: Clicked sign up" data-attr="toolbar-extension-action-name" />
+ </Field>
+ {steps.map((step, index) => (
+ <Group key={index} name={['steps', index]}>
+ <LemonDivider className="my-1" />
+ <div className="flex flex-col gap-2">
+ <ActionStepEditor
+ step={step}
+ index={index}
+ inspecting={inspectingElement === index}
+ onInspect={() => inspectForStep(inspectingElement === index ? null : index)}
+ onEditSelector={() => setEditingSelector(index)}
+ onRemove={() =>
+ setActionFormValue(
+ 'steps',
+ steps.filter((_, i) => i !== index)
+ )
+ }
+ />
+ </div>
+ </Group>
+ ))}
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={() => setActionFormValue('steps', [...steps, {}])}
+ data-attr="toolbar-extension-action-add-step"
+ >
+ {steps.length === 0 ? 'Add an element' : 'Add another element'}
+ </LemonButton>
+ <LemonDivider className="my-1" />
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => selectAction(null)}
+ data-attr="toolbar-extension-action-cancel"
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="primary"
+ htmlType="submit"
+ loading={saving}
+ data-attr="toolbar-extension-action-save"
+ >
+ {isNew ? 'Create action' : 'Save action'}
+ </LemonButton>
+ </div>
+ </Form>
+ </>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionActionsList.tsx b/frontend/src/toolbar/extension/ExtensionActionsList.tsx
new file mode 100644
index 000000000000..c68927a672e0
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionActionsList.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { urls } from '~/toolbar/urls'
+
+import { extensionActionsLogic } from './extensionActionsLogic'
+import { ExtensionEntityList } from './ExtensionEntityList'
+import { extensionPanelLogic } from './extensionPanelLogic'
+
+export function ExtensionActionsList(): JSX.Element {
+ const { actionsState, filteredActions, searchTerm } = useValues(extensionActionsLogic)
+ const { setSearchTerm, selectAction, newAction } = useActions(extensionActionsLogic)
+ const { projectUrl } = useValues(extensionPanelLogic)
+ const saveResult = actionsState?.saveResult
+
+ return (
+ <ExtensionEntityList
+ noun="action"
+ pluralNoun="actions"
+ items={actionsState ? filteredActions : null}
+ loading={!!actionsState?.allActionsLoading}
+ searchTerm={searchTerm}
+ onSearch={setSearchTerm}
+ onSelect={selectAction}
+ onCreate={() => newAction(false)}
+ saved={
+ saveResult?.status === 'saved'
+ ? { name: saveResult.name, url: projectUrl(urls.action(saveResult.actionId)) }
+ : null
+ }
+ viewAllUrl={projectUrl(urls.actions())}
+ emptyText="This project has no actions yet."
+ hint="The page highlights the elements your actions match. Pick an action to edit it."
+ dataAttrs={{
+ search: 'toolbar-extension-actions-search',
+ row: 'toolbar-extension-action-row',
+ create: 'toolbar-extension-new-action',
+ openSaved: 'toolbar-extension-open-saved-action',
+ }}
+ />
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionEntityList.tsx b/frontend/src/toolbar/extension/ExtensionEntityList.tsx
new file mode 100644
index 000000000000..f11738399ec9
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionEntityList.tsx
@@ -0,0 +1,114 @@
+import { IconPlus } from '@posthog/icons'
+
+import { IconOpenInNew } 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 { Link } from 'lib/lemon-ui/Link'
+
+import { ExtensionToolLoading } from './ExtensionToolLoading'
+
+interface ExtensionEntityListProps {
+ /** For example "action", used in the search, empty state and saved copy. */
+ noun: string
+ pluralNoun: string
+ items: { id: number; name: string | null }[] | null
+ loading: boolean
+ searchTerm: string
+ onSearch: (searchTerm: string) => void
+ onSelect: (id: number) => void
+ onCreate: () => void
+ /** The item the page just saved, with its page in PostHog. */
+ saved: { name: string | null; url: string } | null
+ viewAllUrl: string
+ emptyText: string
+ /** Shown above the search, for example a warning about the page. */
+ notice?: JSX.Element | false
+ hint?: string
+ dataAttrs: { search: string; row: string; create: string; openSaved: string }
+}
+
+/** The list a tool opens with: search, pick an item to edit it, or make a new one. */
+export function ExtensionEntityList({
+ noun,
+ pluralNoun,
+ items,
+ loading,
+ searchTerm,
+ onSearch,
+ onSelect,
+ onCreate,
+ saved,
+ viewAllUrl,
+ emptyText,
+ notice,
+ hint,
+ dataAttrs,
+}: ExtensionEntityListProps): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2">
+ {notice}
+ {saved && (
+ <LemonBanner
+ type="success"
+ action={{
+ children: 'Open in PostHog',
+ to: saved.url,
+ targetBlank: true,
+ 'data-attr': dataAttrs.openSaved,
+ }}
+ >
+ Saved {saved.name ? `"${saved.name}"` : `the ${noun}`}.
+ </LemonBanner>
+ )}
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder={`Search ${pluralNoun}`}
+ value={searchTerm}
+ onChange={onSearch}
+ data-attr={dataAttrs.search}
+ />
+ {hint && <div className="text-xs text-secondary">{hint}</div>}
+ {!items || (loading && items.length === 0) ? (
+ <ExtensionToolLoading />
+ ) : items.length === 0 ? (
+ <div className="text-secondary text-xs p-2">
+ {searchTerm ? `No ${pluralNoun} match your search.` : emptyText}
+ </div>
+ ) : (
+ <ol className="flex flex-col gap-px m-0 p-0 list-none">
+ {items.map((item, index) => (
+ <li key={item.id}>
+ <LemonButton
+ fullWidth
+ size="small"
+ onClick={() => onSelect(item.id)}
+ data-attr={dataAttrs.row}
+ >
+ <span className="inline-block min-w-6 text-secondary">{index + 1}.</span>
+ <span className="truncate">
+ {item.name || <span className="italic text-secondary">Untitled</span>}
+ </span>
+ </LemonButton>
+ </li>
+ ))}
+ </ol>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Link to={viewAllUrl} target="_blank" className="text-xs">
+ View all {pluralNoun} <IconOpenInNew />
+ </Link>
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={onCreate}
+ data-attr={dataAttrs.create}
+ >
+ New {noun}
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionFlagRow.tsx b/frontend/src/toolbar/extension/ExtensionFlagRow.tsx
new file mode 100644
index 000000000000..eddb0b7598d7
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionFlagRow.tsx
@@ -0,0 +1,113 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+
+import { IconOpenInNew } from 'lib/lemon-ui/icons'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
+import { Link } from 'lib/lemon-ui/Link'
+
+import { urls } from '~/toolbar/urls'
+
+import { extensionFlagsLogic } from './extensionFlagsLogic'
+import { extensionPanelLogic } from './extensionPanelLogic'
+import type { FlagInfo } from './pageToolbarBridge'
+
+export function ExtensionFlagRow({ flag }: { flag: FlagInfo }): JSX.Element {
+ const { draftPayloads, flagsState, mutationDisabledReason } = useValues(extensionFlagsLogic)
+ const { setFlagOverride, removeFlagOverride, openPayloadEditor, closePayloadEditor, setDraftPayload, savePayload } =
+ useActions(extensionFlagsLogic)
+ const { projectUrl } = useValues(extensionPanelLogic)
+ const { key, id, value, currentValue, hasOverride, variants, payloadOverride } = flag
+ const draftPayload = draftPayloads[key]
+ const payloadError = flagsState?.payloadErrors[key] ?? null
+
+ // Matches the floating toolbar: choosing the value PostHog evaluates removes the override instead.
+ const choose = (newValue: string | boolean): void => {
+ if (newValue === value && hasOverride) {
+ removeFlagOverride(key)
+ } else {
+ setFlagOverride(key, newValue)
+ }
+ }
+
+ return (
+ <div className={clsx('flex flex-col gap-1 rounded px-2 py-1', hasOverride && 'bg-fill-primary')}>
+ <div className="flex items-center gap-2">
+ <Link
+ className="flex-1 min-w-0 truncate font-medium"
+ to={projectUrl(id ? urls.featureFlag(id) : urls.featureFlags())}
+ target="_blank"
+ subtle
+ >
+ <span translate="no">{key}</span> <IconOpenInNew />
+ </Link>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() =>
+ openPayloadEditor(key, payloadOverride !== null ? JSON.stringify(payloadOverride, null, 2) : '')
+ }
+ disabledReason={
+ mutationDisabledReason ?? (currentValue ? null : 'Turn the flag on to edit its payload')
+ }
+ data-attr="toolbar-extension-flag-edit-payload"
+ >
+ Edit payload
+ </LemonButton>
+ <LemonSwitch
+ checked={!!currentValue}
+ disabledReason={mutationDisabledReason}
+ onChange={(checked) => choose(variants.length > 0 && checked ? variants[0].key : checked)}
+ data-attr="toolbar-extension-flag-toggle"
+ />
+ </div>
+ {currentValue && variants.length > 0 ? (
+ <LemonRadio
+ className="pl-4"
+ value={typeof currentValue === 'string' ? currentValue : undefined}
+ options={variants.map((variant) => ({
+ label: `${variant.key}${variant.name ? ` - ${variant.name}` : ''}${
+ variant.rolloutPercentage !== null ? ` (${variant.rolloutPercentage}%)` : ''
+ }`,
+ value: variant.key,
+ disabledReason: mutationDisabledReason ?? undefined,
+ }))}
+ onChange={choose}
+ />
+ ) : null}
+ {draftPayload !== undefined ? (
+ <div className="flex items-start gap-2">
+ <LemonTextArea
+ className={clsx('flex-1 font-mono text-xs', payloadError && 'border-danger')}
+ value={draftPayload}
+ onChange={(draft) => setDraftPayload(key, draft)}
+ placeholder='For example: "A string", 2500, {"key": "value"}'
+ minRows={2}
+ />
+ <div className="flex flex-col gap-1">
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ center
+ disabledReason={mutationDisabledReason}
+ onClick={() => savePayload(key)}
+ data-attr="toolbar-extension-flag-save-payload"
+ >
+ Save
+ </LemonButton>
+ <LemonButton size="xsmall" center onClick={() => closePayloadEditor(key)}>
+ Cancel
+ </LemonButton>
+ </div>
+ </div>
+ ) : payloadOverride !== null ? (
+ <div className="truncate font-mono text-xs text-secondary" translate="no">
+ {JSON.stringify(payloadOverride)}
+ </div>
+ ) : null}
+ {payloadError ? <div className="text-xs text-danger">{payloadError}</div> : null}
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionFlagsMenu.tsx b/frontend/src/toolbar/extension/ExtensionFlagsMenu.tsx
new file mode 100644
index 000000000000..e2d143eb4eb6
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionFlagsMenu.tsx
@@ -0,0 +1,132 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPerson, IconRefresh } from '@posthog/icons'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+
+import { ExtensionFlagRow } from './ExtensionFlagRow'
+import { extensionFlagsLogic } from './extensionFlagsLogic'
+import { ExtensionToolLoading } from './ExtensionToolLoading'
+import { NoPagePosthogBanner } from './NoPagePosthogBanner'
+
+export function ExtensionFlagsMenu(): JSX.Element {
+ const { flagsState, filteredFlags, searchTerm, mutationDisabledReason, impersonationOpen, draftDistinctId } =
+ useValues(extensionFlagsLogic)
+ const {
+ setSearchTerm,
+ clearOverrides,
+ reloadFlags,
+ setImpersonationOpen,
+ setDraftDistinctId,
+ impersonate,
+ clearImpersonation,
+ } = useActions(extensionFlagsLogic)
+
+ if (!flagsState) {
+ return <ExtensionToolLoading />
+ }
+ const { available, loading, countFlagsOverridden, impersonatedDistinctId, mutationError } = flagsState
+ const submitDistinctId = (): void => {
+ if (draftDistinctId.trim()) {
+ impersonate(draftDistinctId.trim())
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ {!available && (
+ <NoPagePosthogBanner consequence="the toolbar can't override its flags. The list shows the values PostHog evaluates for you." />
+ )}
+ {mutationError && (
+ <LemonBanner type="error">
+ Couldn't change the flags on this page: {mutationError} Reload the page and try again.
+ </LemonBanner>
+ )}
+ <div className="flex items-center gap-1">
+ <LemonInput
+ className="flex-1 min-w-0"
+ type="search"
+ size="small"
+ placeholder="Search flags"
+ value={searchTerm}
+ onChange={setSearchTerm}
+ data-attr="toolbar-extension-flags-search"
+ />
+ <LemonButton
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Load the flags again"
+ onClick={reloadFlags}
+ data-attr="toolbar-extension-flags-reload"
+ />
+ <LemonButton
+ size="small"
+ icon={<IconPerson />}
+ type={impersonatedDistinctId ? 'primary' : 'secondary'}
+ tooltip="See the flags of another person, by distinct ID"
+ disabledReason={available ? null : 'This page has no posthog-js to override'}
+ onClick={() => setImpersonationOpen(!impersonationOpen)}
+ data-attr="toolbar-extension-flags-impersonate"
+ />
+ </div>
+ {impersonatedDistinctId ? (
+ <div className="flex items-center gap-2 text-xs">
+ <span className="flex-1 truncate">
+ Viewing as <strong translate="no">{impersonatedDistinctId}</strong>
+ </span>
+ <LemonButton size="xsmall" type="secondary" onClick={clearImpersonation}>
+ Clear
+ </LemonButton>
+ </div>
+ ) : impersonationOpen ? (
+ <div className="flex items-center gap-1">
+ <LemonInput
+ className="flex-1 min-w-0"
+ size="small"
+ placeholder="Distinct ID"
+ value={draftDistinctId}
+ onChange={setDraftDistinctId}
+ onPressEnter={submitDistinctId}
+ />
+ <LemonButton
+ size="small"
+ type="secondary"
+ disabledReason={draftDistinctId.trim() ? null : 'Enter a distinct ID'}
+ onClick={submitDistinctId}
+ >
+ Load
+ </LemonButton>
+ </div>
+ ) : null}
+ {filteredFlags.length > 0 ? (
+ <div className="flex flex-col gap-px">
+ {filteredFlags.map((flag) => (
+ <ExtensionFlagRow key={flag.key} flag={flag} />
+ ))}
+ </div>
+ ) : loading ? (
+ <ExtensionToolLoading />
+ ) : (
+ <div className="p-2 text-xs text-secondary">
+ {searchTerm ? 'No flags match your search.' : 'This project has no feature flags.'}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-xs text-secondary">Overrides apply only to this browser.</span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ disabledReason={
+ countFlagsOverridden === 0 ? 'No overrides to clear' : (mutationDisabledReason ?? null)
+ }
+ onClick={clearOverrides}
+ data-attr="toolbar-extension-flags-clear-overrides"
+ >
+ Clear overrides
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx b/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx
index 22d4b50d2dbd..1e980a10390f 100644
--- a/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx
+++ b/frontend/src/toolbar/extension/ExtensionInspectedElement.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconX } from '@posthog/icons'
+import { IconPlus, IconX } from '@posthog/icons'
import { ElementClickStats } from 'lib/components/heatmaps/ElementClickStats'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -9,12 +9,14 @@ import { Link } from 'lib/lemon-ui/Link'
import { SelectorQualityWarning } from '~/toolbar/elements/SelectorQualityWarning'
import { urls } from '~/toolbar/urls'
+import { extensionActionsLogic } from './extensionActionsLogic'
import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'
import { extensionPanelLogic } from './extensionPanelLogic'
export function ExtensionInspectedElement(): JSX.Element | null {
const { inspect, heatmap } = useValues(extensionPageToolbarConnectionLogic)
const { sendCommand } = useActions(extensionPageToolbarConnectionLogic)
+ const { newAction } = useActions(extensionActionsLogic)
const { projectUrl } = useValues(extensionPanelLogic)
const element = inspect?.element
if (!element) {
@@ -75,6 +77,17 @@ export function ExtensionInspectedElement(): JSX.Element | null {
))
)}
</div>
+ {inspect.isSelected && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={() => newAction(true)}
+ data-attr="toolbar-extension-create-action-from-element"
+ >
+ Create action from this element
+ </LemonButton>
+ )}
</div>
)
}
diff --git a/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx b/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx
index 2c98824a57ce..3c4d02b5b2eb 100644
--- a/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx
+++ b/frontend/src/toolbar/extension/ExtensionPageToolbarTools.tsx
@@ -1,4 +1,5 @@
import { useActions, useMountedLogic, useValues } from 'kea'
+import { useMemo } from 'react'
import { IconExternal, IconX } from '@posthog/icons'
@@ -6,7 +7,12 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { SelectorCountContext, SelectorMatchCounter } from '~/toolbar/actions/SelectorCountContext'
+
+import { ExtensionActionEditor } from './ExtensionActionEditor'
+import { ExtensionActionsList } from './ExtensionActionsList'
import { ExtensionFeatureList } from './ExtensionFeatureList'
+import { ExtensionFlagsMenu } from './ExtensionFlagsMenu'
import { ExtensionHeatmapMenu } from './ExtensionHeatmapMenu'
import { ExtensionInspectedElement } from './ExtensionInspectedElement'
import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'
@@ -19,6 +25,8 @@ type PanelTool = PageToolDefinition & { mode: PageToolMode }
const PANEL_TOOLS = PAGE_TOOLS.filter((tool): tool is PanelTool => !!tool.mode)
function ToolBody({ mode }: { mode: PageToolMode }): JSX.Element {
+ const { selectedActionId } = useValues(extensionPageToolbarConnectionLogic)
+
switch (mode) {
case 'inspect':
return (
@@ -32,6 +40,10 @@ function ToolBody({ mode }: { mode: PageToolMode }): JSX.Element {
)
case 'heatmap':
return <ExtensionHeatmapMenu />
+ case 'actions':
+ return selectedActionId !== null ? <ExtensionActionEditor /> : <ExtensionActionsList />
+ case 'flags':
+ return <ExtensionFlagsMenu />
}
}
@@ -65,66 +77,73 @@ function ToolHeader({ tool }: { tool: PanelTool }): JSX.Element {
export function ExtensionPageToolbarTools({ origin }: { origin: string }): JSX.Element {
useMountedLogic(extensionPageToolbarConnectionLogic)
- const { mode, connectionStatus } = useValues(extensionPageToolbarConnectionLogic)
- const { setMode, connectPage } = useActions(extensionPageToolbarConnectionLogic)
+ const { mode, connectionStatus, selectorCounter } = useValues(extensionPageToolbarConnectionLogic)
+ const { setMode, connectPage, requestSelectorCount } = useActions(extensionPageToolbarConnectionLogic)
const disabledReason = usePageToolDisabledReason()
const activeTool = PANEL_TOOLS.find((tool) => tool.mode === mode)
+ // The page counts selector matches for every editor in the panel.
+ const counter = useMemo<SelectorMatchCounter>(
+ () => ({ count: selectorCounter.count, request: requestSelectorCount }),
+ [selectorCounter, requestSelectorCount]
+ )
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}
+ <SelectorCountContext.Provider value={counter}>
+ <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>
- </span>
- </LemonButton>
- ))}
- </div>
- <ExtensionFeatureList origin={origin} />
- </>
- )}
- </div>
+ </LemonButton>
+ ))}
+ </div>
+ <ExtensionFeatureList origin={origin} />
+ </>
+ )}
+ </div>
+ </SelectorCountContext.Provider>
)
}
diff --git a/frontend/src/toolbar/extension/ExtensionToolLoading.tsx b/frontend/src/toolbar/extension/ExtensionToolLoading.tsx
new file mode 100644
index 000000000000..64b8ae8ee12b
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionToolLoading.tsx
@@ -0,0 +1,9 @@
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+export function ExtensionToolLoading(): JSX.Element {
+ return (
+ <div className="flex justify-center p-4">
+ <Spinner className="text-2xl" />
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/NoPagePosthogBanner.tsx b/frontend/src/toolbar/extension/NoPagePosthogBanner.tsx
new file mode 100644
index 000000000000..86c06d001327
--- /dev/null
+++ b/frontend/src/toolbar/extension/NoPagePosthogBanner.tsx
@@ -0,0 +1,10 @@
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+
+/** `consequence` finishes the sentence, for example "the debugger can't see its events." */
+export function NoPagePosthogBanner({ consequence }: { consequence: string }): JSX.Element {
+ return (
+ <LemonBanner type="info">
+ This page doesn't load posthog-js as <code>window.posthog</code>, so {consequence}
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/toolbar/extension/README.md b/frontend/src/toolbar/extension/README.md
index 5ae61db520ec..574eb2d633f3 100644
--- a/frontend/src/toolbar/extension/README.md
+++ b/frontend/src/toolbar/extension/README.md
@@ -60,6 +60,8 @@ The page tools run the floating toolbar's own logics in the content script, and
- `elementsLogic` for Inspect.
- `heatmapToolbarMenuLogic`, `heatmapDataLogic` and `heatmapCaptureLogic` for the heatmap.
+- `actionsLogic` and `actionsTabLogic` for actions.
+- `flagsToolbarLogic` for feature flags.
The panel shows their controls. It sends each command to the tool it belongs to, and gets their state back through a port.
@@ -87,6 +89,10 @@ flowchart LR
- **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.
+ For flag overrides the page agent calls posthog-js and reports the flag state back. A change it doesn't answer fails after 5 seconds.
+- **Forms.** The panel edits its own copy of the action form, so typing doesn't wait for the page, and sends the form after a short pause.
+ It sends the form right away before any command that changes it on the page, and takes the page's copy only when the page changed the form itself, for example when the user picks an element.
+ The page counts the matches of the selectors the panel shows, and counts again when the page changes.
- **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.
@@ -100,5 +106,9 @@ Use a site in the project's authorized URLs. Do these steps in Chrome and in Fir
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.
+5. In Inspect, select an element and click **Create action from this element**. Name the action, check the match count, and save it.
+6. Click **Actions**, open an action, add an element with **Select Element**, and save.
+7. Click **Flags**. Turn a flag on, pick a variant, save a payload, and turn a multivariate flag off. The page reacts to each change. Click **Clear overrides**.
+8. Open a page that doesn't load posthog-js as `window.posthog`. **Flags** says that it can't override flags there.
+9. Switch to a tab with another site, then back. The panel shows the state of each tab.
+10. Switch the project in the panel. The panel connects the toolbar to the new project.
diff --git a/frontend/src/toolbar/extension/extensionActionsLogic.ts b/frontend/src/toolbar/extension/extensionActionsLogic.ts
new file mode 100644
index 000000000000..b4207e1b5289
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionActionsLogic.ts
@@ -0,0 +1,239 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
+import { subscriptions } from 'kea-subscriptions'
+
+import type { ActionForm } from '~/toolbar/types'
+
+import type { PageActionsCommand } from './extensionPageActionsLogic'
+import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'
+import { capturePageToolUsed } from './extensionTelemetry'
+import { PageFormSync } from './pageFormSync'
+import type { PageToolbarActionsState, PageToolbarState } from './pageToolbarBridge'
+
+const EMPTY_ACTION_FORM = { name: null, steps: [{}] } as ActionForm
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionActionsLogicValues {
+ pageToolbarState: PageToolbarState | null // extensionPageToolbarConnectionLogic
+ actionForm: ActionForm
+ actionFormAllErrors: Record<string, any>
+ actionFormChanged: boolean
+ actionFormErrors: DeepPartialMap<ActionForm, ValidationErrorType>
+ actionFormHasErrors: boolean
+ actionFormManualErrors: Record<string, any>
+ actionFormTouched: boolean
+ actionFormTouches: Record<string, boolean>
+ actionFormValidationErrors: DeepPartialMap<ActionForm, ValidationErrorType>
+ actionsState: PageToolbarActionsState | null
+ editingSelector: number | null
+ filteredActions: PageToolbarActionsState['actions']
+ isActionFormSubmitting: boolean
+ isActionFormValid: boolean
+ saveRequested: boolean
+ saving: boolean
+ searchTerm: string
+ showActionFormErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionActionsLogicActions {
+ sendCommand: (message: import('./pageToolbarBridge').PageToolbarCommand) => {
+ message: import('./pageToolbarBridge').PageToolbarCommand
+ } // extensionPageToolbarConnectionLogic
+ applySelector: (
+ index: number,
+ selector: string
+ ) => {
+ index: number
+ selector: string
+ }
+ inspectForStep: (index: number | null) => {
+ index: number | null
+ }
+ newAction: (fromSelectedElement: boolean) => {
+ fromSelectedElement: boolean
+ }
+ resetActionForm: (values?: ActionForm) => {
+ values?: ActionForm
+ }
+ selectAction: (id: number | null) => {
+ id: number | null
+ }
+ sendActionsCommand: (command: PageActionsCommand) => {
+ command: PageActionsCommand
+ }
+ setActionFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setActionFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setActionFormValues: (values: DeepPartial<ActionForm>) => {
+ values: DeepPartial<ActionForm>
+ }
+ setEditingSelector: (index: number | null) => {
+ index: number | null
+ }
+ setSaveRequested: (saveRequested: boolean) => {
+ saveRequested: boolean
+ }
+ setSearchTerm: (searchTerm: string) => {
+ searchTerm: string
+ }
+ submitActionForm: () => {
+ value: boolean
+ }
+ submitActionFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitActionFormRequest: (actionForm: ActionForm) => {
+ actionForm: ActionForm
+ }
+ submitActionFormSuccess: (actionForm: ActionForm) => {
+ actionForm: ActionForm
+ }
+ touchActionFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionActionsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ actionsState: (pageToolbarState: PageToolbarState | null) => PageToolbarActionsState | null
+ filteredActions: (
+ actionsState: PageToolbarActionsState | null,
+ searchTerm: string
+ ) => PageToolbarActionsState['actions']
+ saving: (actionsState: PageToolbarActionsState | null, saveRequested: boolean) => boolean
+ }
+}
+
+export type extensionActionsLogicType = MakeLogicType<
+ extensionActionsLogicValues,
+ extensionActionsLogicActions,
+ Record<string, any>,
+ extensionActionsLogicMeta
+>
+
+/** The panel side of the actions tool. The page runs the toolbar's actions logics, the panel edits its own copy of the form. */
+export const extensionActionsLogic = kea<extensionActionsLogicType>([
+ path(['toolbar', 'extension', 'extensionActionsLogic']),
+ connect(() => ({
+ values: [extensionPageToolbarConnectionLogic, ['pageToolbarState']],
+ actions: [extensionPageToolbarConnectionLogic, ['sendCommand']],
+ })),
+ actions({
+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),
+ sendActionsCommand: (command: PageActionsCommand) => ({ command }),
+ selectAction: (id: number | null) => ({ id }),
+ newAction: (fromSelectedElement: boolean) => ({ fromSelectedElement }),
+ inspectForStep: (index: number | null) => ({ index }),
+ setEditingSelector: (index: number | null) => ({ index }),
+ applySelector: (index: number, selector: string) => ({ index, selector }),
+ setSaveRequested: (saveRequested: boolean) => ({ saveRequested }),
+ }),
+ forms(({ actions }) => ({
+ actionForm: {
+ defaults: EMPTY_ACTION_FORM,
+ errors: ({ name }) => ({
+ name: !name || !name.length ? 'Must name this action' : undefined,
+ }),
+ submit: () => {
+ actions.sendActionsCommand({ type: 'save-action' })
+ capturePageToolUsed('save-action')
+ },
+ showErrorsOnTouch: true,
+ },
+ })),
+ reducers({
+ searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
+ editingSelector: [null as number | null, { setEditingSelector: (_, { index }) => index }],
+ // The page takes a moment to report that it started saving, so the button waits from the click.
+ saveRequested: [
+ false,
+ {
+ submitActionForm: () => true,
+ // kea-forms fails the submit without calling submit when validation fails.
+ submitActionFormFailure: () => false,
+ setSaveRequested: (_, { saveRequested }) => saveRequested,
+ },
+ ],
+ }),
+ selectors({
+ actionsState: [
+ (s) => [s.pageToolbarState],
+ (pageToolbarState: PageToolbarState | null): PageToolbarActionsState | null =>
+ pageToolbarState?.actions ?? null,
+ ],
+ filteredActions: [
+ (s) => [s.actionsState, s.searchTerm],
+ (actionsState: PageToolbarActionsState | null, searchTerm: string): PageToolbarActionsState['actions'] =>
+ (actionsState?.actions ?? []).filter(({ name }) =>
+ (name ?? '').toLowerCase().includes(searchTerm.trim().toLowerCase())
+ ),
+ ],
+ saving: [
+ (s) => [s.actionsState, s.saveRequested],
+ (actionsState: PageToolbarActionsState | null, saveRequested: boolean): boolean =>
+ saveRequested || !!actionsState?.saving,
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ sendActionsCommand: ({ command }) => {
+ // Every command can make the page change the form, so the page gets the user's edits first.
+ if (command.type !== 'set-action-form') {
+ cache.formSync.flush()
+ }
+ actions.sendCommand({ tool: 'actions', command })
+ },
+ setActionFormValue: () => cache.formSync.schedule(),
+ setActionFormValues: () => cache.formSync.schedule(),
+ selectAction: ({ id }) => actions.sendActionsCommand({ type: 'select-action', id }),
+ newAction: ({ fromSelectedElement }) => {
+ actions.sendActionsCommand({ type: 'new-action', fromSelectedElement })
+ if (fromSelectedElement) {
+ capturePageToolUsed('create-action')
+ }
+ },
+ inspectForStep: ({ index }) => actions.sendActionsCommand({ type: 'inspect-for-action-step', index }),
+ applySelector: ({ index, selector }) => {
+ actions.setEditingSelector(null)
+ const steps = [...(values.actionForm.steps ?? [])]
+ if (steps[index]) {
+ steps[index] = { ...steps[index], selector }
+ actions.setActionFormValue('steps', steps)
+ }
+ },
+ })),
+ afterMount(({ actions, values, cache }) => {
+ cache.formSync = new PageFormSync(() =>
+ actions.sendCommand({ tool: 'actions', command: { type: 'set-action-form', form: values.actionForm } })
+ )
+ cache.disposables.add(() => () => cache.formSync.cancel(), 'formSync')
+ }),
+ // Runs after afterMount above, which creates the form sync the first call reads.
+ subscriptions(({ actions, values, cache }) => ({
+ actionsState: (page: PageToolbarActionsState | null) => {
+ if (!page) {
+ return
+ }
+ if (cache.formSync.adopt(page.selectedActionId, page.formRevision)) {
+ actions.setEditingSelector(null)
+ actions.setSaveRequested(false)
+ actions.resetActionForm(page.actionForm)
+ } else if (values.saveRequested && !page.saving && page.saveResult) {
+ actions.setSaveRequested(false)
+ }
+ },
+ })),
+])
diff --git a/frontend/src/toolbar/extension/extensionFlagsLogic.ts b/frontend/src/toolbar/extension/extensionFlagsLogic.ts
new file mode 100644
index 000000000000..d54d6ac1dcc4
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionFlagsLogic.ts
@@ -0,0 +1,247 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+
+import type { PageFlagsCommand } from './extensionPageFlagsLogic'
+import { extensionPageToolbarConnectionLogic } from './extensionPageToolbarConnectionLogic'
+import { capturePageToolUsed } from './extensionTelemetry'
+import type { FlagInfo, PageToolbarFlagsState, PageToolbarState } from './pageToolbarBridge'
+
+export type FlagValue = string | boolean
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionFlagsLogicValues {
+ pageToolbarState: PageToolbarState | null // extensionPageToolbarConnectionLogic
+ draftDistinctId: string
+ draftPayloads: Record<string, string>
+ filteredFlags: FlagInfo[]
+ flagsState: PageToolbarFlagsState | null
+ impersonationOpen: boolean
+ mutationDisabledReason: string | null
+ savingPayloadKey: string | null
+ searchTerm: string
+ sentAtRevision: number | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionFlagsLogicActions {
+ receivePatch: (patch: Partial<PageToolbarState>) => {
+ patch: Partial<PageToolbarState>
+ } // extensionPageToolbarConnectionLogic
+ receiveState: (state: PageToolbarState | null) => {
+ state: PageToolbarState | null
+ } // extensionPageToolbarConnectionLogic
+ sendCommand: (message: import('./pageToolbarBridge').PageToolbarCommand) => {
+ message: import('./pageToolbarBridge').PageToolbarCommand
+ } // extensionPageToolbarConnectionLogic
+ clearImpersonation: () => {
+ value: true
+ }
+ clearOverrides: () => {
+ value: true
+ }
+ closePayloadEditor: (flagKey: string) => {
+ flagKey: string
+ }
+ impersonate: (distinctId: string) => {
+ distinctId: string
+ }
+ openPayloadEditor: (
+ flagKey: string,
+ draftPayload: string
+ ) => {
+ draftPayload: string
+ flagKey: string
+ }
+ reloadFlags: () => {
+ value: true
+ }
+ removeFlagOverride: (flagKey: string) => {
+ flagKey: string
+ }
+ savePayload: (flagKey: string) => {
+ flagKey: string
+ }
+ sendFlagsMutation: (
+ command: PageFlagsCommand,
+ revision: number
+ ) => {
+ command: PageFlagsCommand
+ revision: number
+ }
+ setDraftDistinctId: (draftDistinctId: string) => {
+ draftDistinctId: string
+ }
+ setDraftPayload: (
+ flagKey: string,
+ draftPayload: string
+ ) => {
+ draftPayload: string
+ flagKey: string
+ }
+ setFlagOverride: (
+ flagKey: string,
+ value: FlagValue
+ ) => {
+ flagKey: string
+ value: FlagValue
+ }
+ setImpersonationOpen: (open: boolean) => {
+ open: boolean
+ }
+ setSearchTerm: (searchTerm: string) => {
+ searchTerm: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionFlagsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ flagsState: (pageToolbarState: PageToolbarState | null) => PageToolbarFlagsState | null
+ filteredFlags: (flagsState: PageToolbarFlagsState | null, searchTerm: string) => FlagInfo[]
+ mutationDisabledReason: (
+ flagsState: PageToolbarFlagsState | null,
+ sentAtRevision: number | null
+ ) => string | null
+ }
+}
+
+export type extensionFlagsLogicType = MakeLogicType<
+ extensionFlagsLogicValues,
+ extensionFlagsLogicActions,
+ Record<string, any>,
+ extensionFlagsLogicMeta
+>
+
+/** The panel side of the flags tool. The page runs the toolbar's flags logic, which applies the overrides. */
+export const extensionFlagsLogic = kea<extensionFlagsLogicType>([
+ path(['toolbar', 'extension', 'extensionFlagsLogic']),
+ connect(() => ({
+ values: [extensionPageToolbarConnectionLogic, ['pageToolbarState']],
+ actions: [extensionPageToolbarConnectionLogic, ['sendCommand', 'receiveState', 'receivePatch']],
+ })),
+ actions({
+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),
+ sendFlagsMutation: (command: PageFlagsCommand, revision: number) => ({ command, revision }),
+ setFlagOverride: (flagKey: string, value: FlagValue) => ({ flagKey, value }),
+ removeFlagOverride: (flagKey: string) => ({ flagKey }),
+ clearOverrides: true,
+ reloadFlags: true,
+ openPayloadEditor: (flagKey: string, draftPayload: string) => ({ flagKey, draftPayload }),
+ closePayloadEditor: (flagKey: string) => ({ flagKey }),
+ setDraftPayload: (flagKey: string, draftPayload: string) => ({ flagKey, draftPayload }),
+ savePayload: (flagKey: string) => ({ flagKey }),
+ setImpersonationOpen: (open: boolean) => ({ open }),
+ setDraftDistinctId: (draftDistinctId: string) => ({ draftDistinctId }),
+ impersonate: (distinctId: string) => ({ distinctId }),
+ clearImpersonation: true,
+ }),
+ reducers({
+ searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
+ draftPayloads: [
+ {} as Record<string, string>,
+ {
+ openPayloadEditor: (state, { flagKey, draftPayload }) => ({ ...state, [flagKey]: draftPayload }),
+ setDraftPayload: (state, { flagKey, draftPayload }) => ({ ...state, [flagKey]: draftPayload }),
+ closePayloadEditor: (state, { flagKey }) => {
+ const { [flagKey]: _, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ impersonationOpen: [false, { setImpersonationOpen: (_, { open }) => open, clearImpersonation: () => false }],
+ draftDistinctId: [
+ '',
+ { setDraftDistinctId: (_, { draftDistinctId }) => draftDistinctId, impersonate: () => '' },
+ ],
+ // The page's revision when the panel sent a change. It blocks a second change until the page answers the
+ // first, so two overrides can't race in the page. The page times out a change it can't apply.
+ sentAtRevision: [
+ null as number | null,
+ {
+ sendFlagsMutation: (_, { revision }) => revision,
+ receiveState: () => null,
+ receivePatch: (sent, { patch }) =>
+ sent !== null && patch.flags && patch.flags.mutationRevision > sent ? null : sent,
+ },
+ ],
+ // The page checks the JSON, so the editor stays open until the page accepts the payload.
+ savingPayloadKey: [
+ null as string | null,
+ { savePayload: (_, { flagKey }) => flagKey, closePayloadEditor: () => null, receiveState: () => null },
+ ],
+ }),
+ selectors({
+ flagsState: [
+ (s) => [s.pageToolbarState],
+ (pageToolbarState: PageToolbarState | null): PageToolbarFlagsState | null =>
+ pageToolbarState?.flags ?? null,
+ ],
+ filteredFlags: [
+ (s) => [s.flagsState, s.searchTerm],
+ (flagsState: PageToolbarFlagsState | null, searchTerm: string): FlagInfo[] =>
+ (flagsState?.flags ?? []).filter(({ key }) =>
+ key.toLowerCase().includes(searchTerm.trim().toLowerCase())
+ ),
+ ],
+ mutationDisabledReason: [
+ (s) => [s.flagsState, s.sentAtRevision],
+ (flagsState: PageToolbarFlagsState | null, sentAtRevision: number | null): string | null =>
+ !flagsState?.available
+ ? 'This page has no posthog-js to override'
+ : sentAtRevision !== null || flagsState.mutationPending
+ ? 'Applying the last change…'
+ : null,
+ ],
+ }),
+ listeners(({ actions, values }) => {
+ const sendMutation = (command: PageFlagsCommand): void =>
+ actions.sendFlagsMutation(command, values.flagsState?.mutationRevision ?? 0)
+ return {
+ sendFlagsMutation: ({ command }) => {
+ actions.sendCommand({ tool: 'flags', command })
+ },
+ setFlagOverride: ({ flagKey, value }) => {
+ if (!values.mutationDisabledReason) {
+ sendMutation({ type: 'set-flag-override', flagKey, value })
+ capturePageToolUsed('override-flag')
+ }
+ },
+ removeFlagOverride: ({ flagKey }) => {
+ if (!values.mutationDisabledReason) {
+ sendMutation({ type: 'remove-flag-override', flagKey })
+ }
+ },
+ clearOverrides: () => {
+ if (!values.mutationDisabledReason) {
+ sendMutation({ type: 'clear-flag-overrides' })
+ capturePageToolUsed('clear-flag-overrides')
+ }
+ },
+ reloadFlags: () => {
+ actions.sendCommand({ tool: 'flags', command: { type: 'reload-flags' } })
+ },
+ savePayload: ({ flagKey }) => {
+ if (values.mutationDisabledReason) {
+ return
+ }
+ sendMutation({ type: 'save-flag-payload', flagKey, draftPayload: values.draftPayloads[flagKey] ?? '' })
+ capturePageToolUsed('override-flag', { payload: true })
+ },
+ receivePatch: ({ patch }) => {
+ const flagKey = values.savingPayloadKey
+ if (flagKey && patch.flags && values.sentAtRevision === null && !patch.flags.payloadErrors[flagKey]) {
+ actions.closePayloadEditor(flagKey)
+ }
+ },
+ impersonate: ({ distinctId }) => {
+ // The page loads the person's flags from PostHog before it overrides anything, so this doesn't wait.
+ actions.sendCommand({ tool: 'flags', command: { type: 'impersonate-flags', distinctId } })
+ capturePageToolUsed('impersonate-flags')
+ },
+ clearImpersonation: () => {
+ if (!values.mutationDisabledReason) {
+ sendMutation({ type: 'clear-flag-impersonation' })
+ }
+ },
+ }
+ }),
+])
diff --git a/frontend/src/toolbar/extension/extensionPageActionsLogic.ts b/frontend/src/toolbar/extension/extensionPageActionsLogic.ts
new file mode 100644
index 000000000000..4c69acbbecf2
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionPageActionsLogic.ts
@@ -0,0 +1,199 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+
+import { actionsLogic } from '~/toolbar/actions/actionsLogic'
+import { actionsTabLogic } from '~/toolbar/actions/actionsTabLogic'
+
+import type { ActionType, ElementType } from '../../types'
+import type { ActionForm } from '../types'
+import type { ActionSaveResult, PageToolbarActionsState } from './pageToolbarBridge'
+
+export type PageActionsCommand =
+ | { type: 'select-action'; id: number | null }
+ | { type: 'new-action'; fromSelectedElement: boolean }
+ | { type: 'set-action-form'; form: ActionForm }
+ | { type: 'inspect-for-action-step'; index: number | null }
+ | { type: 'save-action' }
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageActionsLogicValues {
+ allActionsLoading: boolean // actionsLogic
+ sortedActions: ActionType[] // actionsLogic
+ actionForm: ActionForm // actionsTabLogic
+ actionFormElementsChains: Record<number, ElementType[]> // actionsTabLogic
+ inspectingElement: number | null // actionsTabLogic
+ isActionFormSubmitting: boolean // actionsTabLogic
+ actionsList: PageToolbarActionsState['actions']
+ formRevision: number
+ pageState: PageToolbarActionsState
+ saveResult: ActionSaveResult | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageActionsLogicActions {
+ actionCreatedSuccess: (action: ActionType) => {
+ action: ActionType
+ } // actionsTabLogic
+ inspectElementSelected: (
+ element: HTMLElement,
+ index: number | null
+ ) => {
+ element: HTMLElement
+ index: number | null
+ } // actionsTabLogic
+ newAction: (element?: HTMLElement | undefined) => {
+ element: HTMLElement | null
+ } // actionsTabLogic
+ selectAction: (id: number | null) => {
+ id: number | null
+ } // actionsTabLogic
+ submitActionFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ } // actionsTabLogic
+ handleCommand: (command: PageActionsCommand) => {
+ command: PageActionsCommand
+ }
+ setSaveResult: (saveResult: ActionSaveResult | null) => {
+ saveResult: ActionSaveResult | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageActionsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ actionsList: (sortedActions: ActionType[]) => PageToolbarActionsState['actions']
+ pageState: (
+ allActionsLoading: boolean,
+ actionsList: {
+ id: number
+ name: string | null
+ }[],
+ selectedActionId: number | 'new' | null,
+ actionForm: ActionForm,
+ formRevision: number,
+ actionFormElementsChains: Record<number, ElementType[]>,
+ inspectingElement: number | null,
+ isActionFormSubmitting: boolean,
+ saveResult: ActionSaveResult | null
+ ) => PageToolbarActionsState
+ }
+}
+
+export type extensionPageActionsLogicType = MakeLogicType<
+ extensionPageActionsLogicValues,
+ extensionPageActionsLogicActions,
+ Record<string, any>,
+ extensionPageActionsLogicMeta
+>
+
+export const extensionPageActionsLogic = kea<extensionPageActionsLogicType>([
+ path(['toolbar', 'extension', 'extensionPageActionsLogic']),
+ connect(() => ({
+ values: [
+ actionsLogic,
+ ['sortedActions', 'allActionsLoading'],
+ actionsTabLogic,
+ ['actionForm', 'actionFormElementsChains', 'inspectingElement', 'isActionFormSubmitting'],
+ ],
+ actions: [
+ actionsTabLogic,
+ ['actionCreatedSuccess', 'submitActionFormFailure', 'selectAction', 'newAction', 'inspectElementSelected'],
+ ],
+ })),
+ actions({
+ handleCommand: (command: PageActionsCommand) => ({ command }),
+ setSaveResult: (saveResult: ActionSaveResult | null) => ({ saveResult }),
+ }),
+ reducers({
+ saveResult: [
+ null as ActionSaveResult | null,
+ {
+ setSaveResult: (_, { saveResult }) => saveResult,
+ actionCreatedSuccess: (_, { action }) => ({
+ status: 'saved' as const,
+ actionId: action.id,
+ name: action.name ?? null,
+ }),
+ submitActionFormFailure: (_, { error }) => ({
+ status: 'failed' as const,
+ error: error?.message || 'Unknown error',
+ }),
+ selectAction: () => null,
+ newAction: () => null,
+ },
+ ],
+ // The panel edits its own copy of the form, and takes the page's copy only when the page changed it.
+ formRevision: [
+ 0,
+ {
+ selectAction: (revision) => revision + 1,
+ newAction: (revision) => revision + 1,
+ inspectElementSelected: (revision) => revision + 1,
+ },
+ ],
+ }),
+ selectors({
+ actionsList: [
+ (s) => [s.sortedActions],
+ (sortedActions: ActionType[]): PageToolbarActionsState['actions'] =>
+ sortedActions.map(({ id, name }) => ({ id, name: name ?? null })),
+ ],
+ pageState: [
+ (s) => [
+ s.allActionsLoading,
+ s.actionsList,
+ // kea-typegen drops the 'new' literal when it copies a connected value's type, so read the selector.
+ actionsTabLogic.selectors.selectedActionId,
+ s.actionForm,
+ s.formRevision,
+ s.actionFormElementsChains,
+ s.inspectingElement,
+ s.isActionFormSubmitting,
+ s.saveResult,
+ ],
+ (
+ allActionsLoading: boolean,
+ actionsList: PageToolbarActionsState['actions'],
+ selectedActionId: number | 'new' | null,
+ actionForm: ActionForm,
+ formRevision: number,
+ actionFormElementsChains: Record<number, ElementType[]>,
+ inspectingElement: number | null,
+ isActionFormSubmitting: boolean,
+ saveResult: ActionSaveResult | null
+ ): PageToolbarActionsState => ({
+ allActionsLoading,
+ actions: actionsList,
+ selectedActionId,
+ actionForm,
+ formRevision,
+ actionFormElementsChains,
+ inspectingElement,
+ saving: isActionFormSubmitting,
+ saveResult,
+ }),
+ ],
+ }),
+ listeners(({ actions }) => ({
+ handleCommand: ({ command }) => {
+ switch (command.type) {
+ case 'select-action':
+ actionsTabLogic.actions.selectAction(command.id)
+ return
+ case 'set-action-form':
+ actionsTabLogic.actions.setActionFormValues(command.form)
+ return
+ case 'inspect-for-action-step':
+ actionsTabLogic.actions.inspectForElementWithIndex(command.index)
+ return
+ case 'save-action':
+ actions.setSaveResult(null)
+ actionsTabLogic.actions.submitActionForm()
+ return
+ }
+ },
+ })),
+])
diff --git a/frontend/src/toolbar/extension/extensionPageFlagsLogic.ts b/frontend/src/toolbar/extension/extensionPageFlagsLogic.ts
new file mode 100644
index 000000000000..6cc2495f5ea1
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionPageFlagsLogic.ts
@@ -0,0 +1,210 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import type { PostHog } from 'posthog-js'
+
+import { flagsToolbarLogic, flagsToolbarLogicValues } from '~/toolbar/flags/flagsToolbarLogic'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+
+import type { FeatureFlagType } from '../../types'
+import type { PageFlagMutationStatus } from './pagePosthogBridge'
+import type { FlagInfo, PageToolbarFlagsState } from './pageToolbarBridge'
+
+export type PageFlagsCommand =
+ | { type: 'set-flag-override'; flagKey: string; value: string | boolean }
+ | { type: 'remove-flag-override'; flagKey: string }
+ | { type: 'save-flag-payload'; flagKey: string; draftPayload: string }
+ | { type: 'clear-flag-overrides' }
+ | { type: 'reload-flags' }
+ | { type: 'impersonate-flags'; distinctId: string }
+ | { type: 'clear-flag-impersonation' }
+
+type FilteredFlag = flagsToolbarLogicValues['filteredFlags'][number]
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageFlagsLogicValues {
+ countFlagsOverridden: number // flagsToolbarLogic
+ filteredFlags: {
+ currentValue: boolean | string
+ feature_flag: FeatureFlagType
+ hasOverride: boolean
+ hasVariants: boolean
+ payloadOverride: any
+ value: boolean | string
+ }[] // flagsToolbarLogic
+ impersonatedDistinctId: string | null // flagsToolbarLogic
+ payloadErrors: Record<string, string | null> // flagsToolbarLogic
+ userFlagsLoading: boolean // flagsToolbarLogic
+ posthog: PostHog | null // toolbarConfigLogic
+ flagMutationStatus: PageFlagMutationStatus
+ flags: FlagInfo[]
+ pageState: PageToolbarFlagsState
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageFlagsLogicActions {
+ handleCommand: (command: PageFlagsCommand) => {
+ command: PageFlagsCommand
+ }
+ openFlags: () => {
+ value: true
+ }
+ setFlagMutationStatus: (status: PageFlagMutationStatus) => {
+ status: PageFlagMutationStatus
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPageFlagsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ flags: (
+ filteredFlags: {
+ currentValue: boolean | string
+ feature_flag: FeatureFlagType
+ hasOverride: boolean
+ hasVariants: boolean
+ payloadOverride: any
+ value: boolean | string
+ }[]
+ ) => FlagInfo[]
+ pageState: (
+ posthog: PostHog | null,
+ userFlagsLoading: boolean,
+ flags: FlagInfo[],
+ countFlagsOverridden: number,
+ impersonatedDistinctId: string | null,
+ payloadErrors: Record<string, string | null>,
+ flagMutationStatus: PageFlagMutationStatus
+ ) => PageToolbarFlagsState
+ }
+}
+
+export type extensionPageFlagsLogicType = MakeLogicType<
+ extensionPageFlagsLogicValues,
+ extensionPageFlagsLogicActions,
+ Record<string, any>,
+ extensionPageFlagsLogicMeta
+>
+
+export const extensionPageFlagsLogic = kea<extensionPageFlagsLogicType>([
+ path(['toolbar', 'extension', 'extensionPageFlagsLogic']),
+ connect(() => ({
+ values: [
+ flagsToolbarLogic,
+ ['filteredFlags', 'userFlagsLoading', 'countFlagsOverridden', 'impersonatedDistinctId', 'payloadErrors'],
+ toolbarConfigLogic,
+ ['posthog'],
+ ],
+ })),
+ actions({
+ openFlags: true,
+ handleCommand: (command: PageFlagsCommand) => ({ command }),
+ setFlagMutationStatus: (status: PageFlagMutationStatus) => ({ status }),
+ }),
+ reducers({
+ flagMutationStatus: [
+ { pending: false, error: null, revision: 0 } as PageFlagMutationStatus,
+ { setFlagMutationStatus: (_, { status }) => status },
+ ],
+ }),
+ selectors({
+ flags: [
+ (s) => [s.filteredFlags],
+ (filteredFlags: FilteredFlag[]): FlagInfo[] =>
+ filteredFlags.map(({ feature_flag, value, currentValue, hasOverride, payloadOverride }) => ({
+ key: feature_flag.key,
+ id: feature_flag.id ?? null,
+ value,
+ currentValue,
+ hasOverride,
+ variants: (feature_flag.filters?.multivariate?.variants ?? []).map((variant) => ({
+ key: variant.key,
+ name: variant.name ?? null,
+ rolloutPercentage: variant.rollout_percentage ?? null,
+ })),
+ payloadOverride: payloadOverride ?? null,
+ })),
+ ],
+ pageState: [
+ (s) => [
+ s.posthog,
+ s.userFlagsLoading,
+ s.flags,
+ s.countFlagsOverridden,
+ s.impersonatedDistinctId,
+ s.payloadErrors,
+ s.flagMutationStatus,
+ ],
+ (
+ posthog: PostHog | null,
+ userFlagsLoading: boolean,
+ flags: FlagInfo[],
+ countFlagsOverridden: number,
+ impersonatedDistinctId: string | null,
+ payloadErrors: Record<string, string | null>,
+ flagMutationStatus: PageFlagMutationStatus
+ ): PageToolbarFlagsState => ({
+ available: !!posthog,
+ loading: userFlagsLoading,
+ flags,
+ countFlagsOverridden,
+ impersonatedDistinctId,
+ payloadErrors,
+ mutationPending: flagMutationStatus.pending,
+ mutationError: flagMutationStatus.error,
+ mutationRevision: flagMutationStatus.revision,
+ }),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ openFlags: () => {
+ const posthog: PostHog | null = values.posthog
+ const flags = flagsToolbarLogic.actions
+ if (posthog && !cache.subscribed) {
+ cache.subscribed = true
+ posthog.onFeatureFlags(flags.setFeatureFlagValueFromPostHogClient)
+ const variants = posthog.featureFlags.getFlagVariants()
+ flags.setFeatureFlagValueFromPostHogClient(Object.keys(variants), variants)
+ }
+ flags.getUserFlags()
+ flags.checkLocalOverrides()
+ },
+ setFlagMutationStatus: () => {
+ // The page agent reports the overrides the page applied, which can differ from the ones the logic sent.
+ flagsToolbarLogic.actions.checkLocalOverrides()
+ },
+ handleCommand: ({ command }) => {
+ const flags = flagsToolbarLogic.actions
+ switch (command.type) {
+ case 'set-flag-override':
+ flags.setOverriddenUserFlag(command.flagKey, command.value)
+ return
+ case 'remove-flag-override':
+ flags.deleteOverriddenUserFlag(command.flagKey)
+ return
+ case 'save-flag-payload':
+ flags.setDraftPayload(command.flagKey, command.draftPayload)
+ flags.savePayloadOverride(command.flagKey)
+ if (values.payloadErrors[command.flagKey]) {
+ // Invalid JSON never reaches the page's posthog-js, so the change ends here with its error.
+ actions.setFlagMutationStatus({
+ ...values.flagMutationStatus,
+ revision: values.flagMutationStatus.revision + 1,
+ })
+ }
+ return
+ case 'clear-flag-overrides':
+ flags.clearAllOverrides()
+ return
+ case 'reload-flags':
+ flags.getUserFlags()
+ flags.checkLocalOverrides()
+ return
+ case 'impersonate-flags':
+ flags.loadFlagsForDistinctId(command.distinctId)
+ return
+ case 'clear-flag-impersonation':
+ flags.clearImpersonation()
+ return
+ }
+ },
+ })),
+])
diff --git a/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts b/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts
index 46c60f1c8040..f625497ad31b 100644
--- a/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts
+++ b/frontend/src/toolbar/extension/extensionPageToolbarConnectionLogic.ts
@@ -11,6 +11,7 @@ import {
selectors,
} from 'kea'
+import type { SelectorMatchCounter } from '~/toolbar/actions/SelectorCountContext'
import { urls } from '~/toolbar/urls'
import { extensionAuthLogic } from './extensionAuthLogic'
@@ -28,6 +29,9 @@ import type { PageToolbarHeatmapState, PageToolbarInspectState, PageToolbarToken
export type PageToolbarConnectionStatus = 'idle' | 'connecting' | 'connected' | 'failed'
+// The panel asks about the selectors its open form shows, so a short list covers it.
+const MAX_REQUESTED_SELECTORS = 20
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageToolbarConnectionLogicValues {
tokens: PageToolbarTokens | null // extensionAuthLogic
@@ -41,6 +45,9 @@ export interface extensionPageToolbarConnectionLogicValues {
inspect: PageToolbarInspectState | null
mode: PageToolbarMode
pageToolbarState: PageToolbarState | null
+ requestedSelectors: string[]
+ selectedActionId: number | 'new' | null
+ selectorCounter: Pick<SelectorMatchCounter, 'count'>
wantedMode: PageToolbarMode
wildcardHrefDraft: string | null
}
@@ -79,6 +86,9 @@ export interface extensionPageToolbarConnectionLogicActions {
receiveState: (state: PageToolbarState | null) => {
state: PageToolbarState | null
}
+ requestSelectorCount: (selector: string) => {
+ selector: string
+ }
sendCommand: (message: PageToolbarCommand) => {
message: PageToolbarCommand
}
@@ -99,6 +109,8 @@ export interface extensionPageToolbarConnectionLogicMeta {
mode: (pageToolbarState: PageToolbarState | null, wantedMode: PageToolbarMode) => PageToolbarMode
inspect: (pageToolbarState: PageToolbarState | null) => PageToolbarInspectState | null
heatmap: (pageToolbarState: PageToolbarState | null) => PageToolbarHeatmapState | null
+ selectedActionId: (pageToolbarState: PageToolbarState | null) => number | 'new' | null
+ selectorCounter: (pageToolbarState: PageToolbarState | null) => Pick<SelectorMatchCounter, 'count'>
}
}
@@ -129,6 +141,7 @@ export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConne
setMode: (mode: PageToolbarMode) => ({ mode }),
setWildcardHref: (href: string) => ({ href }),
openHeatmapInPostHog: (shortId: string) => ({ shortId }),
+ requestSelectorCount: (selector: string) => ({ selector }),
}),
reducers({
connectionStatus: [
@@ -163,6 +176,13 @@ export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConne
receivePatch: (mode, { patch }) => patch.mode ?? mode,
},
],
+ requestedSelectors: [
+ [] as string[],
+ {
+ requestSelectorCount: (selectors, { selector }) =>
+ selectors.includes(selector) ? selectors : [...selectors, selector].slice(-MAX_REQUESTED_SELECTORS),
+ },
+ ],
}),
selectors({
mode: [
@@ -178,11 +198,29 @@ export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConne
(s) => [s.pageToolbarState],
(pageToolbarState: PageToolbarState | null) => pageToolbarState?.heatmap ?? null,
],
+ selectedActionId: [
+ (s) => [s.pageToolbarState],
+ (pageToolbarState: PageToolbarState | null) => pageToolbarState?.actions.selectedActionId ?? null,
+ ],
+ selectorCounter: [
+ (s) => [s.pageToolbarState],
+ (pageToolbarState: PageToolbarState | null): Pick<SelectorMatchCounter, 'count'> => ({
+ count: (selector) => pageToolbarState?.selectorCounts[selector],
+ }),
+ ],
}),
listeners(({ actions, values, cache }) => {
const post = (message: PageToolbarRequest): void => {
cache.port?.postMessage(message)
}
+ const sendSelectors = (): void => {
+ if (values.requestedSelectors.length > 0) {
+ actions.sendCommand({
+ tool: 'selectors',
+ command: { type: 'count-selectors', selectors: values.requestedSelectors },
+ })
+ }
+ }
return {
connectPage: async (_, breakpoint) => {
cache.port?.disconnect()
@@ -232,6 +270,8 @@ export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConne
if (values.wantedMode !== 'none') {
actions.sendCommand({ tool: 'session', command: { type: 'set-mode', mode: values.wantedMode } })
}
+ // A fresh content script knows nothing about the selectors the open form counts.
+ sendSelectors()
actions.setConnectionStatus('connected')
},
setWildcardHref: ({ href }) => {
@@ -264,6 +304,10 @@ export const extensionPageToolbarConnectionLogic = kea<extensionPageToolbarConne
actions.connectPage()
}
},
+ requestSelectorCount: async (_, breakpoint) => {
+ await breakpoint(50)
+ sendSelectors()
+ },
openHeatmapInPostHog: ({ shortId }) => {
void openTab(values.projectUrl(urls.heatmap(shortId)))
},
diff --git a/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts b/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts
index 5479dd7f49a8..8cc152a0539b 100644
--- a/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts
+++ b/frontend/src/toolbar/extension/extensionPageToolbarLogic.ts
@@ -1,5 +1,8 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { querySelectorAllDeep } from 'query-selector-shadow-dom'
+import { actionsLogic } from '~/toolbar/actions/actionsLogic'
+import { actionsTabLogic } from '~/toolbar/actions/actionsTabLogic'
import { elementsLogic } from '~/toolbar/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'
import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'
@@ -7,6 +10,8 @@ import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import type { ElementWithMetadata } from '~/toolbar/types'
import type { FragileSelectorResult } from '../utils/selectorQuality'
+import { extensionPageActionsLogic } from './extensionPageActionsLogic'
+import { extensionPageFlagsLogic } from './extensionPageFlagsLogic'
import { extensionPageHeatmapLogic } from './extensionPageHeatmapLogic'
import type {
InspectedElementInfo,
@@ -26,6 +31,30 @@ export type PageSessionCommand =
export type PageInspectCommand = { type: 'clear-selected-element' }
+export type PageSelectorsCommand = { type: 'count-selectors'; selectors: string[] }
+
+type PanelMenuMode = Extract<PageToolbarMode, 'flags'>
+
+const PANEL_MENU_MODES: PanelMenuMode[] = ['flags']
+
+// The panel asks about the selectors its open form shows, so a short list covers it.
+const MAX_COUNTED_SELECTORS = 20
+
+// Recounts the selectors once the page stops changing for this long.
+const SELECTOR_RECOUNT_DEBOUNCE_MS = 300
+
+function countMatches(selectors: string[]): Record<string, number | null> {
+ return Object.fromEntries(
+ selectors.map((selector) => {
+ try {
+ return [selector, querySelectorAllDeep(selector).length]
+ } catch {
+ return [selector, null]
+ }
+ })
+ )
+}
+
function inspectedElementInfo(meta: ElementWithMetadata | null): InspectedElementInfo | null {
if (!meta) {
return null
@@ -48,6 +77,7 @@ function inspectedElementInfo(meta: ElementWithMetadata | null): InspectedElemen
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageToolbarLogicValues {
+ buttonActionsVisible: boolean // actionsTabLogic
activeMeta:
| (ElementWithMetadata & {
selectorQuality: FragileSelectorResult | null
@@ -55,9 +85,13 @@ export interface extensionPageToolbarLogicValues {
| null // elementsLogic
activeMetaIsSelected: boolean // elementsLogic
inspectEnabled: boolean // elementsLogic
+ selectedElement: HTMLElement | null // elementsLogic
heatmapEnabled: boolean // heatmapToolbarMenuLogic
+ countedSelectors: string[]
inspectState: PageToolbarInspectState
mode: PageToolbarMode
+ openMenu: PanelMenuMode | null
+ selectorCounts: Record<string, number | null>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -65,6 +99,12 @@ export interface extensionPageToolbarLogicActions {
handleCommand: (message: PageToolbarCommand) => {
message: PageToolbarCommand
}
+ recountSelectors: () => {
+ value: true
+ }
+ setCountedSelectors: (selectors: string[]) => {
+ selectors: string[]
+ }
setMode: (mode: PageToolbarMode) => {
mode: PageToolbarMode
}
@@ -73,7 +113,12 @@ export interface extensionPageToolbarLogicActions {
// 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
+ mode: (
+ buttonActionsVisible: boolean,
+ openMenu: 'flags' | null,
+ inspectEnabled: boolean,
+ heatmapEnabled: boolean
+ ) => PageToolbarMode
inspectState: (
activeMeta:
| (ElementWithMetadata & {
@@ -98,21 +143,57 @@ export const extensionPageToolbarLogic = kea<extensionPageToolbarLogicType>([
connect(() => ({
values: [
elementsLogic,
- ['inspectEnabled', 'activeMeta', 'activeMetaIsSelected'],
+ ['inspectEnabled', 'activeMeta', 'activeMetaIsSelected', 'selectedElement'],
heatmapToolbarMenuLogic,
['heatmapEnabled'],
+ actionsTabLogic,
+ ['buttonActionsVisible'],
],
- logic: [extensionPageHeatmapLogic],
+ logic: [extensionPageHeatmapLogic, extensionPageActionsLogic, extensionPageFlagsLogic],
})),
actions({
handleCommand: (message: PageToolbarCommand) => ({ message }),
setMode: (mode: PageToolbarMode) => ({ mode }),
+ setCountedSelectors: (selectors: string[]) => ({ selectors }),
+ recountSelectors: true,
+ }),
+ reducers({
+ // The panel-only menus. The other modes live in the toolbar logics that draw on the page.
+ openMenu: [
+ null as PanelMenuMode | null,
+ {
+ setMode: (_, { mode }) =>
+ PANEL_MENU_MODES.includes(mode as PanelMenuMode) ? (mode as PanelMenuMode) : null,
+ },
+ ],
+ countedSelectors: [[] as string[], { setCountedSelectors: (_, { selectors }) => selectors }],
+ selectorCounts: [
+ {} as Record<string, number | null>,
+ {
+ setCountedSelectors: (_, { selectors }) => countMatches(selectors),
+ recountSelectors: (counts) => countMatches(Object.keys(counts)),
+ },
+ ],
}),
selectors({
mode: [
- (s) => [s.inspectEnabled, s.heatmapEnabled],
- (inspectEnabled: boolean, heatmapEnabled: boolean): PageToolbarMode =>
- inspectEnabled ? 'inspect' : heatmapEnabled ? 'heatmap' : 'none',
+ (s) => [s.buttonActionsVisible, s.openMenu, s.inspectEnabled, s.heatmapEnabled],
+ (
+ buttonActionsVisible: boolean,
+ openMenu: PanelMenuMode | null,
+ inspectEnabled: boolean,
+ heatmapEnabled: boolean
+ ): PageToolbarMode =>
+ // Actions come first, because picking an element for a step turns inspect on too.
+ buttonActionsVisible
+ ? 'actions'
+ : openMenu
+ ? openMenu
+ : inspectEnabled
+ ? 'inspect'
+ : heatmapEnabled
+ ? 'heatmap'
+ : 'none',
],
inspectState: [
(s) => [s.activeMeta, s.activeMetaIsSelected],
@@ -122,15 +203,29 @@ export const extensionPageToolbarLogic = kea<extensionPageToolbarLogicType>([
}),
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values, cache }) => ({
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()
+ actionsTabLogic.actions.inspectForElementWithIndex(null)
+ actionsTabLogic.actions.hideButtonActions()
+ // Each tool loads its data the first time it opens, and keeps it while the page tools run.
+ const firstOpen = !cache.openedModes.has(mode)
+ cache.openedModes.add(mode)
if (mode === 'inspect') {
elementsLogic.actions.enableInspect()
} else if (mode === 'heatmap') {
heatmapToolbarMenuLogic.actions.enableHeatmap()
+ } else if (mode === 'actions') {
+ actionsTabLogic.actions.showButtonActions()
+ if (firstOpen) {
+ actionsLogic.actions.getActions()
+ }
+ } else if (mode === 'flags') {
+ if (firstOpen) {
+ extensionPageFlagsLogic.actions.openFlags()
+ }
}
},
handleCommand: ({ message }) => {
@@ -146,19 +241,52 @@ export const extensionPageToolbarLogic = kea<extensionPageToolbarLogicType>([
}
},
inspect: () => elementsLogic.actions.setSelectedElement(null),
+ selectors: (command) => actions.setCountedSelectors(command.selectors.slice(-MAX_COUNTED_SELECTORS)),
heatmap: (command) => extensionPageHeatmapLogic.actions.handleCommand(command),
+ actions: (command) => {
+ if (command.type === 'new-action') {
+ // Switching modes clears the selection, so read the element first.
+ const element = command.fromSelectedElement ? values.selectedElement : null
+ actions.setMode('actions')
+ actionsTabLogic.actions.newAction(element ?? undefined)
+ return
+ }
+ extensionPageActionsLogic.actions.handleCommand(command)
+ },
+ flags: (command) => extensionPageFlagsLogic.actions.handleCommand(command),
}
;(handlers[message.tool] as (command: PageToolbarCommand['command']) => void)(message.command)
},
})),
+ afterMount(({ actions, values, cache }) => {
+ cache.openedModes = new Set<PageToolbarMode>()
+ cache.disposables.add(() => {
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ const observer = new MutationObserver(() => {
+ if (values.countedSelectors.length === 0) {
+ return
+ }
+ clearTimeout(timeout)
+ timeout = setTimeout(actions.recountSelectors, SELECTOR_RECOUNT_DEBOUNCE_MS)
+ })
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true })
+ return () => {
+ clearTimeout(timeout)
+ observer.disconnect()
+ }
+ }, 'selectorRecount')
+ }),
])
/** 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
+ const { mode, inspectState, selectorCounts } = extensionPageToolbarLogic.values
return {
mode,
inspect: inspectState,
+ selectorCounts,
heatmap: extensionPageHeatmapLogic.values.pageState,
+ actions: extensionPageActionsLogic.values.pageState,
+ flags: extensionPageFlagsLogic.values.pageState,
}
}
diff --git a/frontend/src/toolbar/extension/extensionPageTools.tsx b/frontend/src/toolbar/extension/extensionPageTools.tsx
index 98aaee45bcde..201b14ea32ae 100644
--- a/frontend/src/toolbar/extension/extensionPageTools.tsx
+++ b/frontend/src/toolbar/extension/extensionPageTools.tsx
@@ -39,12 +39,14 @@ export const PAGE_TOOLS: PageToolDefinition[] = [
gate: AvailableFeature.TOOLBAR_HEATMAPS,
},
{
+ mode: 'actions',
label: 'Actions',
description: 'Create and edit actions from elements on the page',
icon: <IconBolt />,
feature: { key: 'actions', path: urls.actions() },
},
{
+ mode: 'flags',
label: 'Feature flags',
description: 'Override feature flags on this page',
icon: <IconToggle />,
diff --git a/frontend/src/toolbar/extension/extensionTelemetry.ts b/frontend/src/toolbar/extension/extensionTelemetry.ts
index 26c800a4bfa3..dcdba1a3b535 100644
--- a/frontend/src/toolbar/extension/extensionTelemetry.ts
+++ b/frontend/src/toolbar/extension/extensionTelemetry.ts
@@ -1,7 +1,17 @@
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
// pinned: sent as the `tool` property of `toolbar extension page tool used`
-type PageToolKey = 'heatmap' | 'inspect' | 'save-heatmap'
+type PageToolKey =
+ | 'heatmap'
+ | 'inspect'
+ | 'save-heatmap'
+ | 'actions'
+ | 'create-action'
+ | 'save-action'
+ | 'flags'
+ | 'override-flag'
+ | 'clear-flag-overrides'
+ | 'impersonate-flags'
export function capturePageToolUsed(tool: PageToolKey, properties?: Record<string, unknown>): void {
// pinned: analytics event name
diff --git a/frontend/src/toolbar/extension/pageAgent.ts b/frontend/src/toolbar/extension/pageAgent.ts
index 15e09549c95b..5df2509b4642 100644
--- a/frontend/src/toolbar/extension/pageAgent.ts
+++ b/frontend/src/toolbar/extension/pageAgent.ts
@@ -2,9 +2,10 @@ import {
PAGE_AGENT_REPLY_SOURCE,
PageAgentReply,
PageAgentReplyMessage,
+ PageAgentRequest,
isPageAgentRequestMessage,
} from './pageAgentProtocol'
-import type { PageAnalyticsInfo } from './pageToolbarBridge'
+import type { PageAnalyticsInfo, PageFeatureFlagsSnapshot } from './pageToolbarBridge'
interface PagePosthog {
__loaded?: boolean
@@ -14,6 +15,14 @@ interface PagePosthog {
scroll_root_selector?: string | string[]
}
heatmaps?: { isEnabled?: boolean }
+ featureFlags?: {
+ overrideFeatureFlags?: (overrides: unknown) => void
+ reloadFeatureFlags?: () => void
+ getFlagVariants?: () => Record<string, string | boolean>
+ }
+ get_property?: (key: string) => unknown
+ getGroups?: () => Record<string, string>
+ onFeatureFlags?: (callback: () => void) => unknown
}
// The panel injects this file again on each connection, so a second run in the same page must do nothing.
@@ -40,12 +49,24 @@ function pagePosthog(): PagePosthog | null {
: null
}
+function featureFlagsSnapshot(posthog: PagePosthog): PageFeatureFlagsSnapshot {
+ return {
+ overrides: read(
+ () => posthog.get_property?.('$override_feature_flags') as Record<string, string | boolean>,
+ {}
+ ),
+ variants: read(() => posthog.featureFlags?.getFlagVariants?.(), {}),
+ groups: read(() => posthog.getGroups?.(), {}),
+ }
+}
+
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,
+ featureFlags: featureFlagsSnapshot(posthog),
}
}
@@ -57,21 +78,69 @@ function reply(message: PageAgentReply): void {
}
function install(): void {
+ let flagsSubscribed = false
+
+ const subscribeToFlags = (posthog: PagePosthog): void => {
+ if (!flagsSubscribed && posthog.onFeatureFlags) {
+ flagsSubscribed = true
+ posthog.onFeatureFlags(() => reply({ kind: 'feature-flags', featureFlags: featureFlagsSnapshot(posthog) }))
+ }
+ }
+
+ const run = (posthog: PagePosthog, id: number, request: PageAgentRequest): void => {
+ switch (request.method) {
+ case 'read-analytics':
+ reply({ kind: 'analytics', id, info: analyticsInfo(posthog) })
+ return
+ case 'override-flags':
+ case 'reload-flags':
+ try {
+ subscribeToFlags(posthog)
+ if (request.method === 'override-flags') {
+ posthog.featureFlags?.overrideFeatureFlags?.(
+ request.flags === false ? false : { flags: request.flags, payloads: request.payloads }
+ )
+ } else {
+ posthog.featureFlags?.reloadFeatureFlags?.()
+ }
+ reply({ kind: 'result', id, ok: true, featureFlags: featureFlagsSnapshot(posthog) })
+ } catch (error) {
+ reply({
+ kind: 'result',
+ id,
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ })
+ }
+ return
+ }
+ }
+
window.addEventListener('message', (event) => {
if (event.source !== window || !isPageAgentRequestMessage(event.data)) {
return
}
+ const { id, request } = event.data
const posthog = pagePosthog()
- reply({ kind: 'analytics', id: event.data.id, info: posthog ? analyticsInfo(posthog) : null })
+ if (posthog) {
+ run(posthog, id, request)
+ } else if (request.method === 'read-analytics') {
+ reply({ kind: 'analytics', id, info: null })
+ } else {
+ reply({ kind: 'result', id, ok: false, error: 'The page has no posthog-js' })
+ }
})
- if (pagePosthog()) {
+ const posthog = pagePosthog()
+ if (posthog) {
+ subscribeToFlags(posthog)
return
}
const startedAt = Date.now()
const interval = setInterval(() => {
const loaded = pagePosthog()
if (loaded) {
+ subscribeToFlags(loaded)
reply({ kind: 'analytics', id: null, info: analyticsInfo(loaded) })
}
if (loaded || Date.now() - startedAt > POSTHOG_CHECK_DURATION_MS) {
diff --git a/frontend/src/toolbar/extension/pageAgentProtocol.ts b/frontend/src/toolbar/extension/pageAgentProtocol.ts
index a13c8aad0e1e..3deb55d2b9be 100644
--- a/frontend/src/toolbar/extension/pageAgentProtocol.ts
+++ b/frontend/src/toolbar/extension/pageAgentProtocol.ts
@@ -1,4 +1,4 @@
-import type { PageAnalyticsInfo } from './pageToolbarBridge'
+import type { PageAnalyticsInfo, PageFeatureFlagsSnapshot } 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.
@@ -7,10 +7,17 @@ import type { PageAnalyticsInfo } from './pageToolbarBridge'
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 type PageAgentRequest =
+ | { method: 'read-analytics' }
+ | { method: 'override-flags'; flags: Record<string, string | boolean> | false; payloads?: Record<string, unknown> }
+ | { method: 'reload-flags' }
+
+export type PageAgentReply =
+ /** `id` is null when the page agent reports by itself that posthog-js appeared on the page. */
+ | { kind: 'analytics'; id: number | null; info: PageAnalyticsInfo | null }
+ | { kind: 'result'; id: number; ok: true; featureFlags: PageFeatureFlagsSnapshot }
+ | { kind: 'result'; id: number; ok: false; error: string }
+ | { kind: 'feature-flags'; featureFlags: PageFeatureFlagsSnapshot }
export interface PageAgentRequestMessage {
source: typeof PAGE_AGENT_REQUEST_SOURCE
diff --git a/frontend/src/toolbar/extension/pageFormSync.ts b/frontend/src/toolbar/extension/pageFormSync.ts
new file mode 100644
index 000000000000..0814238853f4
--- /dev/null
+++ b/frontend/src/toolbar/extension/pageFormSync.ts
@@ -0,0 +1,52 @@
+// Waits this long after the last keystroke before the page gets the form, so typing doesn't flood the port.
+const FORM_SYNC_DEBOUNCE_MS = 150
+
+/**
+ * Keeps the panel's copy of a form that the page owns. The panel sends edits after a pause in typing, and takes the
+ * page's copy only when the page changed the form itself, for example when the user picks an element on the page.
+ */
+export class PageFormSync {
+ private adopted: { selectedId: number | 'new' | null; revision: number } | null = null
+ private timeout: ReturnType<typeof setTimeout> | null = null
+
+ constructor(private readonly sendForm: () => void) {}
+
+ /** True once for each form the page reports, which the panel then resets its copy to. */
+ adopt(selectedId: number | 'new' | null, revision: number): boolean {
+ if (this.adopted?.selectedId === selectedId && this.adopted.revision === revision) {
+ return false
+ }
+ this.adopted = { selectedId, revision }
+ // A pending edit belongs to the form the page just replaced.
+ this.cancel()
+ return true
+ }
+
+ schedule(): void {
+ this.cancel()
+ this.timeout = setTimeout(() => {
+ this.timeout = null
+ this.sendForm()
+ }, FORM_SYNC_DEBOUNCE_MS)
+ }
+
+ /**
+ * Sends a pending edit now. Call it before a command that makes the page change the form, so the page has every
+ * edit. With no pending edit the page already has the panel's form, and sending it again could overwrite a change
+ * the page made that the panel has not adopted yet.
+ */
+ flush(): void {
+ if (this.timeout === null) {
+ return
+ }
+ this.cancel()
+ this.sendForm()
+ }
+
+ cancel(): void {
+ if (this.timeout !== null) {
+ clearTimeout(this.timeout)
+ this.timeout = null
+ }
+ }
+}
diff --git a/frontend/src/toolbar/extension/pagePosthogBridge.test.ts b/frontend/src/toolbar/extension/pagePosthogBridge.test.ts
new file mode 100644
index 000000000000..ad39e96cac5d
--- /dev/null
+++ b/frontend/src/toolbar/extension/pagePosthogBridge.test.ts
@@ -0,0 +1,81 @@
+import { PAGE_AGENT_REPLY_SOURCE, PageAgentReply, PageAgentRequestMessage } from './pageAgentProtocol'
+import { PageFlagMutationStatus, PagePosthogBridge } from './pagePosthogBridge'
+import type { PageAnalyticsInfo } from './pageToolbarBridge'
+
+const INFO: PageAnalyticsInfo = {
+ version: '1.300.0',
+ scrollPropertiesDisabled: false,
+ scrollRootSelector: null,
+ heatmapsEnabled: true,
+ featureFlags: { overrides: {}, variants: { 'launch-banner': false }, groups: {} },
+}
+
+function reply(message: PageAgentReply): void {
+ window.dispatchEvent(
+ new MessageEvent('message', { data: { source: PAGE_AGENT_REPLY_SOURCE, reply: message }, source: window })
+ )
+}
+
+describe('PagePosthogBridge', () => {
+ let bridge: PagePosthogBridge
+ let statuses: PageFlagMutationStatus[]
+ let requests: PageAgentRequestMessage[]
+
+ beforeEach(() => {
+ statuses = []
+ requests = []
+ jest.spyOn(window, 'postMessage').mockImplementation((message: unknown) => {
+ requests.push(message as PageAgentRequestMessage)
+ })
+ bridge = new PagePosthogBridge(INFO, (status) => statuses.push(status))
+ })
+
+ afterEach(() => {
+ bridge.dispose()
+ jest.restoreAllMocks()
+ })
+
+ it('reports a new override synchronously, before the page agent answers', () => {
+ bridge.posthog.featureFlags.overrideFeatureFlags({ flags: { 'launch-banner': true } })
+
+ expect(bridge.posthog.get_property('$override_feature_flags')).toEqual({ 'launch-banner': true })
+ expect(requests).toMatchObject([{ request: { method: 'override-flags', flags: { 'launch-banner': true } } }])
+ expect(statuses.at(-1)).toEqual({ pending: true, error: null, revision: 0 })
+ })
+
+ it.each([
+ ['a reply to its own request ends the mutation', true, { pending: false, error: null, revision: 1 }],
+ ['a reply to an unknown request is ignored', false, { pending: true, error: null, revision: 0 }],
+ ])('%s', (_, ownRequest, expectedStatus) => {
+ bridge.posthog.featureFlags.overrideFeatureFlags({ flags: { 'launch-banner': true } })
+ const id = ownRequest ? requests[0].id : requests[0].id + 100
+
+ reply({
+ kind: 'result',
+ id,
+ ok: true,
+ featureFlags: { ...INFO.featureFlags, overrides: { 'launch-banner': true } },
+ })
+
+ expect(statuses.at(-1)).toEqual(expectedStatus)
+ })
+
+ it("fails a change the page agent never answers, so the panel's controls come back", () => {
+ jest.useFakeTimers()
+ bridge.posthog.featureFlags.overrideFeatureFlags({ flags: { 'launch-banner': true } })
+
+ jest.runOnlyPendingTimers()
+
+ expect(statuses.at(-1)).toEqual({ pending: false, error: "The page didn't answer.", revision: 1 })
+ jest.useRealTimers()
+ })
+
+ it('keeps the error the page agent reports', () => {
+ bridge.posthog.featureFlags.overrideFeatureFlags(false)
+
+ reply({ kind: 'result', id: requests[0].id, ok: false, error: 'The page has no posthog-js' })
+
+ expect(statuses.at(-1)).toEqual({ pending: false, error: 'The page has no posthog-js', revision: 1 })
+ expect(bridge.posthog.get_property('$override_feature_flags')).toEqual({})
+ })
+})
diff --git a/frontend/src/toolbar/extension/pagePosthogBridge.ts b/frontend/src/toolbar/extension/pagePosthogBridge.ts
index 4d6804d22840..2dd7b9a41ba2 100644
--- a/frontend/src/toolbar/extension/pagePosthogBridge.ts
+++ b/frontend/src/toolbar/extension/pagePosthogBridge.ts
@@ -7,10 +7,19 @@ import {
PageAgentRequestMessage,
isPageAgentReplyMessage,
} from './pageAgentProtocol'
-import type { PageAnalyticsInfo } from './pageToolbarBridge'
+import type { PageAnalyticsInfo, PageFeatureFlagsSnapshot } from './pageToolbarBridge'
-// The page agent answers in milliseconds. Past this, the page most likely reloaded or has no agent.
+export interface PageFlagMutationStatus {
+ pending: boolean
+ error: string | null
+ revision: number
+}
+
+type FeatureFlagsCallback = (flags: string[], variants: Record<string, string | boolean>) => void
+
+// The page agent answers in milliseconds. Past these, the page most likely reloaded or has no agent.
const ANALYTICS_TIMEOUT_MS = 1000
+const MUTATION_TIMEOUT_MS = 5000
let nextRequestId = 1
@@ -60,13 +69,39 @@ export function onPagePosthogAppeared(handler: () => void): void {
})
}
-/** Stands in for the page's posthog-js in the content script, with the settings the page agent read from it. */
+/**
+ * Stands in for the page's posthog-js in the content script. The toolbar's logics read posthog-js synchronously, so
+ * this keeps a copy of the page's flag state and updates it as soon as it sends a change, before the page agent answers.
+ */
export class PagePosthogBridge {
+ private featureFlags: PageFeatureFlagsSnapshot
+ private pendingMutations = new Map<number, ReturnType<typeof setTimeout>>()
+ private featureFlagsCallbacks: FeatureFlagsCallback[] = []
+ private mutationStatus: PageFlagMutationStatus = { pending: false, error: null, revision: 0 }
+ private removeListener: () => void
/** The parts of posthog-js that the toolbar's logics read. */
readonly posthog: PostHog
- constructor(info: PageAnalyticsInfo) {
- this.posthog = {
+ constructor(
+ private readonly info: PageAnalyticsInfo,
+ private readonly onChange: (status: PageFlagMutationStatus) => void
+ ) {
+ this.featureFlags = info.featureFlags
+ this.removeListener = onPageAgentReply((reply) => this.handleReply(reply))
+ this.posthog = this.buildPosthog()
+ }
+
+ dispose(): void {
+ this.removeListener()
+ for (const timeout of this.pendingMutations.values()) {
+ clearTimeout(timeout)
+ }
+ this.pendingMutations.clear()
+ }
+
+ private buildPosthog(): PostHog {
+ const { info } = this
+ return {
version: info.version ?? undefined,
config: {
disable_scroll_properties: info.scrollPropertiesDisabled,
@@ -75,8 +110,90 @@ export class PagePosthogBridge {
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 },
+ featureFlags: {
+ overrideFeatureFlags: (
+ overrides: { flags?: Record<string, string | boolean>; payloads?: Record<string, unknown> } | false
+ ) => this.overrideFeatureFlags(overrides),
+ reloadFeatureFlags: () => this.sendMutation({ method: 'reload-flags' }),
+ getFlagVariants: () => this.featureFlags.variants,
+ },
+ get_property: (key: string) =>
+ key === '$override_feature_flags' ? this.featureFlags.overrides : undefined,
+ getGroups: () => this.featureFlags.groups,
+ onFeatureFlags: (callback: FeatureFlagsCallback) => {
+ this.featureFlagsCallbacks.push(callback)
+ return () => {
+ this.featureFlagsCallbacks = this.featureFlagsCallbacks.filter((c) => c !== callback)
+ }
+ },
} as unknown as PostHog
}
+
+ private overrideFeatureFlags(
+ overrides: { flags?: Record<string, string | boolean>; payloads?: Record<string, unknown> } | false
+ ): void {
+ const flags = overrides === false ? false : (overrides.flags ?? {})
+ this.featureFlags = { ...this.featureFlags, overrides: flags === false ? {} : flags }
+ this.sendMutation(
+ overrides === false
+ ? { method: 'override-flags', flags: false }
+ : { method: 'override-flags', flags: overrides.flags ?? {}, payloads: overrides.payloads }
+ )
+ }
+
+ /** A flag change shows as pending until the page agent answers, or fails when it doesn't answer in time. */
+ private sendMutation(request: PageAgentRequest): void {
+ const id = postToPageAgent(request)
+ this.pendingMutations.set(
+ id,
+ setTimeout(() => this.finishMutation(id, "The page didn't answer."), MUTATION_TIMEOUT_MS)
+ )
+ this.setMutationStatus({ pending: true })
+ }
+
+ private finishMutation(id: number, error: string | null): void {
+ const timeout = this.pendingMutations.get(id)
+ if (timeout === undefined) {
+ return
+ }
+ clearTimeout(timeout)
+ this.pendingMutations.delete(id)
+ this.setMutationStatus({
+ pending: this.pendingMutations.size > 0,
+ error,
+ revision: this.mutationStatus.revision + 1,
+ })
+ }
+
+ private handleReply(reply: PageAgentReply): void {
+ if (reply.kind === 'feature-flags') {
+ this.setFeatureFlags(reply.featureFlags)
+ this.onChange(this.mutationStatus)
+ return
+ }
+ if (reply.kind !== 'result') {
+ return
+ }
+ if (!this.pendingMutations.has(reply.id)) {
+ return
+ }
+ if (reply.ok) {
+ this.setFeatureFlags(reply.featureFlags)
+ }
+ this.finishMutation(reply.id, reply.ok ? null : reply.error)
+ }
+
+ private setFeatureFlags(featureFlags: PageFeatureFlagsSnapshot): void {
+ this.featureFlags = featureFlags
+ for (const callback of this.featureFlagsCallbacks) {
+ callback(Object.keys(featureFlags.variants), featureFlags.variants)
+ }
+ }
+
+ private setMutationStatus(patch: Partial<PageFlagMutationStatus>): void {
+ this.mutationStatus = { ...this.mutationStatus, ...patch }
+ this.onChange(this.mutationStatus)
+ }
}
function scrollRoot(selector: string | string[] | null): Element | null {
diff --git a/frontend/src/toolbar/extension/pageToolbarBridge.ts b/frontend/src/toolbar/extension/pageToolbarBridge.ts
index a219971e43fc..eb50ae94a271 100644
--- a/frontend/src/toolbar/extension/pageToolbarBridge.ts
+++ b/frontend/src/toolbar/extension/pageToolbarBridge.ts
@@ -5,10 +5,13 @@ import type {
ScrollDepthPosthogJsError,
} from 'lib/components/heatmaps/types'
-import type { ActionStepType } from '~/types'
+import type { ActionForm } from '~/toolbar/types'
+import type { ActionStepType, ElementType } from '~/types'
+import type { PageActionsCommand } from './extensionPageActionsLogic'
+import type { PageFlagsCommand } from './extensionPageFlagsLogic'
import type { PageHeatmapCommand } from './extensionPageHeatmapLogic'
-import type { PageInspectCommand, PageSessionCommand } from './extensionPageToolbarLogic'
+import type { PageInspectCommand, PageSessionCommand, PageSelectorsCommand } from './extensionPageToolbarLogic'
/**
* The content script runs the toolbar's own logics in the page, signed in with the extension's OAuth tokens. The panel
@@ -18,7 +21,7 @@ import type { PageInspectCommand, PageSessionCommand } from './extensionPageTool
// 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'
+export type PageToolbarMode = 'none' | 'heatmap' | 'inspect' | 'actions' | 'flags'
/** What the content script reads from the page's posthog-js through the page agent. */
export interface PageAnalyticsInfo {
@@ -28,6 +31,13 @@ export interface PageAnalyticsInfo {
scrollRootSelector: string | string[] | null
/** Null when the posthog-js version has no heatmaps module. */
heatmapsEnabled: boolean | null
+ featureFlags: PageFeatureFlagsSnapshot
+}
+
+export interface PageFeatureFlagsSnapshot {
+ overrides: Record<string, string | boolean>
+ variants: Record<string, string | boolean>
+ groups: Record<string, string>
}
export interface PageToolbarTokens {
@@ -45,7 +55,10 @@ export interface PageToolbarSession extends PageToolbarTokens {
export interface PageToolCommands {
session: PageSessionCommand
inspect: PageInspectCommand
+ selectors: PageSelectorsCommand
heatmap: PageHeatmapCommand
+ actions: PageActionsCommand
+ flags: PageFlagsCommand
}
export type PageToolName = keyof PageToolCommands
@@ -111,10 +124,57 @@ export type HeatmapSaveResult =
| { status: 'saved'; shortId: string; savedWidths: number; totalWidths: number }
| { status: 'failed'; error: string }
+export type ActionSaveResult =
+ | { status: 'saved'; actionId: number; name: string | null }
+ | { status: 'failed'; error: string }
+
+export interface PageToolbarActionsState {
+ allActionsLoading: boolean
+ actions: { id: number; name: string | null }[]
+ selectedActionId: number | 'new' | null
+ actionForm: ActionForm
+ /** Goes up when the page changes the form itself, for example when the user picks an element for a step. */
+ formRevision: number
+ actionFormElementsChains: Record<number, ElementType[]>
+ inspectingElement: number | null
+ saving: boolean
+ saveResult: ActionSaveResult | null
+}
+
+export interface FlagInfo {
+ key: string
+ id: number | null
+ /** The value PostHog evaluates for the signed-in user. Choosing it again removes the override. */
+ value: string | boolean
+ currentValue: string | boolean
+ hasOverride: boolean
+ variants: { key: string; name: string | null; rolloutPercentage: number | null }[]
+ payloadOverride: unknown
+}
+
+export interface PageToolbarFlagsState {
+ /** False when the page has no `window.posthog`, so overrides can't reach it. */
+ available: boolean
+ loading: boolean
+ flags: FlagInfo[]
+ countFlagsOverridden: number
+ impersonatedDistinctId: string | null
+ payloadErrors: Record<string, string | null>
+ /** True from the moment the page sends an override until the page's posthog-js applies it or the wait times out. */
+ mutationPending: boolean
+ mutationError: string | null
+ /** Goes up when the page finishes applying an override, whether it worked or not. */
+ mutationRevision: number
+}
+
export interface PageToolbarState {
mode: PageToolbarMode
inspect: PageToolbarInspectState
+ /** Matches on the page for the selectors the panel asked about. `null` marks an invalid selector. */
+ selectorCounts: Record<string, number | null>
heatmap: PageToolbarHeatmapState
+ actions: PageToolbarActionsState
+ flags: PageToolbarFlagsState
}
export type PageToolbarMessage =
diff --git a/frontend/src/toolbar/extension/pageToolbarHost.tsx b/frontend/src/toolbar/extension/pageToolbarHost.tsx
index 2bbbc6f1d70e..1b1a017f7ceb 100644
--- a/frontend/src/toolbar/extension/pageToolbarHost.tsx
+++ b/frontend/src/toolbar/extension/pageToolbarHost.tsx
@@ -6,6 +6,7 @@ import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { ToolbarProps } from '~/types'
import { ExtensionPort, extensionFileUrl, onPageToolbarConnect } from './extensionBrowser'
+import { extensionPageFlagsLogic } from './extensionPageFlagsLogic'
import { extensionPageToolbarLogic, getPageToolbarState } from './extensionPageToolbarLogic'
import { PagePosthogBridge, onPagePosthogAppeared, requestPageAnalytics } from './pagePosthogBridge'
import {
@@ -115,7 +116,11 @@ export class PageToolbarHost {
}
this.stop()
const pageAnalytics = await requestPageAnalytics()
- this.posthogBridge = pageAnalytics ? new PagePosthogBridge(pageAnalytics) : null
+ this.posthogBridge = pageAnalytics
+ ? new PagePosthogBridge(pageAnalytics, (status) =>
+ extensionPageFlagsLogic.findMounted()?.actions.setFlagMutationStatus(status)
+ )
+ : null
const props: ToolbarProps = {
source: 'extension',
uiHost: session.uiHost,
@@ -155,6 +160,7 @@ export class PageToolbarHost {
this.overlayRoot = null
this.unmountLogics?.()
this.unmountLogics = null
+ this.posthogBridge?.dispose()
this.posthogBridge = null
this.uiHost = null
this.lastState = null
diff --git a/frontend/src/toolbar/extension/panel.tsx b/frontend/src/toolbar/extension/panel.tsx
index 1dda9ed21bcc..b1a92b34d8b3 100644
--- a/frontend/src/toolbar/extension/panel.tsx
+++ b/frontend/src/toolbar/extension/panel.tsx
@@ -1,6 +1,7 @@
import '~/styles'
import { resetContext } from 'kea'
+import { disposablesPlugin } from 'kea-disposables'
import { loadersPlugin } from 'kea-loaders'
import { subscriptionsPlugin } from 'kea-subscriptions'
import { createRoot } from 'react-dom/client'
@@ -9,7 +10,7 @@ import { extensionAuthLogic } from './extensionAuthLogic'
import { ExtensionPanel } from './ExtensionPanel'
import { extensionPanelLogic } from './extensionPanelLogic'
-resetContext({ plugins: [loadersPlugin, subscriptionsPlugin] })
+resetContext({ plugins: [disposablesPlugin, loadersPlugin, subscriptionsPlugin] })
extensionPanelLogic.mount()
extensionAuthLogic.mount()