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(conversations): make ticket sidebar panels customizable widgets (#130074)

Christian Raffertya03e8cb6bfee
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 6a49fdc5a0a6..66f618ab1a58 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -55968,6 +55968,25 @@
"required": ["type"],
"type": "object"
},
+ "TicketSidebarConfiguration": {
+ "additionalProperties": false,
+ "properties": {
+ "hidden": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "order": {
+ "description": "Widget keys in display order. Typed as strings so a layout naming a removed widget still validates.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
"TikTokAdsDefaultSources": {
"enum": ["tiktok"],
"type": "string"
@@ -57762,6 +57781,9 @@
"sql_editor": {
"$ref": "#/definitions/SQLEditorConfiguration"
},
+ "ticket_sidebar": {
+ "$ref": "#/definitions/TicketSidebarConfiguration"
+ },
"version": {
"description": "Schema version of this configuration blob, for future format migrations.",
"type": "integer"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 0fa03849bb08..e48869cd2905 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -9573,6 +9573,12 @@ export interface AnalyticsListDisplayConfiguration {
default_sort?: '-last_viewed_at' | '-created_at'
}
+export interface TicketSidebarConfiguration {
+ /** Widget keys in display order. Typed as strings so a layout naming a removed widget still validates. */
+ order?: string[]
+ hidden?: string[]
+}
+
export interface UserUIConfiguration {
/**
* Schema version of this configuration blob, for future format migrations.
@@ -9581,6 +9587,7 @@ export interface UserUIConfiguration {
version: number
sql_editor?: SQLEditorConfiguration
analytics_list?: AnalyticsListDisplayConfiguration
+ ticket_sidebar?: TicketSidebarConfiguration
[key: string]: unknown
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 16ef0c1692aa..0537e99d89c6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3085,6 +3085,18 @@ importers:
products/conversations:
dependencies:
+ '@dnd-kit/core':
+ specifier: '*'
+ '@dnd-kit/modifiers':
+ specifier: '*'
+ '@dnd-kit/sortable':
+ specifier: '*'
+ '@dnd-kit/utilities':
+ specifier: '*'
+ version: 3.2.1([email protected])
'@posthog/brand':
specifier: 'catalog:'
version: 0.17.0([email protected])
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 13ee223862d3..8362f983f434 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -2898,6 +2898,7 @@ class TestUserUIConfigurationValidation(SimpleTestCase):
("unknown_analytics_list_sort", {"version": 1, "analytics_list": {"default_sort": "name"}}),
("unknown_analytics_list_key", {"version": 1, "analytics_list": {"columns": ["owner"]}}),
("non_boolean_hide_insights", {"version": 1, "analytics_list": {"hide_insights": "nope"}}),
+ ("non_list_ticket_sidebar_order", {"version": 1, "ticket_sidebar": {"order": "activity"}}),
]
)
def test_invalid_ui_configuration_is_rejected(self, _name, value):
@@ -2915,6 +2916,14 @@ class TestUserUIConfigurationValidation(SimpleTestCase):
"analytics_list",
{"version": 1, "analytics_list": {"hide_insights": True, "default_sort": "-created_at"}},
),
+ (
+ # A layout can name a widget that a later release removed. Rejecting it would block every later save.
+ "ticket_sidebar_with_removed_widget",
+ {
+ "version": 1,
+ "ticket_sidebar": {"order": ["removed_widget", "activity"], "hidden": ["removed_widget"]},
+ },
+ ),
(
# Sidebar settings an older client stored. Rejecting them would block every later save.
"stored_sidebar_settings",
diff --git a/posthog/schema.py b/posthog/schema.py
index 165ebfaa8e1d..a4b3121dc3ba 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -3511,6 +3511,19 @@ class Branching(BaseModel):
type: SurveyQuestionBranchingType
+class TicketSidebarConfiguration(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ hidden: list[str] | None = None
+ order: list[str] | None = Field(
+ default=None,
+ description=(
+ "Widget keys in display order. Typed as strings so a layout naming a removed widget still validates."
+ ),
+ )
+
+
class TimelineEntry(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -3570,6 +3583,7 @@ class UserBasicType(BaseModel):
class UserUIConfiguration(BaseModel):
analytics_list: AnalyticsListDisplayConfiguration | None = None
sql_editor: SQLEditorConfiguration | None = None
+ ticket_sidebar: TicketSidebarConfiguration | None = None
version: int = Field(
...,
description=("Schema version of this configuration blob, for future format migrations."),
diff --git a/products/conversations/frontend/components/SupportTicketSidebarWidgets/SupportTicketSidebarWidgets.tsx b/products/conversations/frontend/components/SupportTicketSidebarWidgets/SupportTicketSidebarWidgets.tsx
new file mode 100644
index 000000000000..928154764ac9
--- /dev/null
+++ b/products/conversations/frontend/components/SupportTicketSidebarWidgets/SupportTicketSidebarWidgets.tsx
@@ -0,0 +1,88 @@
+import { useValues } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { AIPanel } from '../../scenes/ticket/AIPanel'
+import { ExceptionsPanel } from '../../scenes/ticket/ExceptionsPanel'
+import { PreviousTicketsPanel } from '../../scenes/ticket/PreviousTicketsPanel'
+import { RecentEventsPanel } from '../../scenes/ticket/RecentEventsPanel'
+import { RelatedGroupsPanel } from '../../scenes/ticket/RelatedGroupsPanel'
+import { SessionRecordingPanel } from '../../scenes/ticket/SessionRecordingPanel'
+import { StaffActionsPanel } from '../../scenes/ticket/StaffActionsPanel'
+import { supportTicketSceneLogic } from '../../scenes/ticket/supportTicketSceneLogic'
+import { TicketActivityPanel } from '../../scenes/ticket/TicketActivityPanel'
+import { TicketSidebarWidgetSlots } from '../TicketSidebarWidgets/ticketSidebarLayout'
+import { TicketSidebarWidgets } from '../TicketSidebarWidgets/TicketSidebarWidgets'
+
+const WIDGET_TICKET_ONLY = 'Only shows on tickets from the in-app widget.'
+
+export function SupportTicketSidebarWidgets({ ticketId }: { ticketId: string }): JSX.Element {
+ const { ticket, person, eventsQuery, exceptionsQuery, previousTickets, previousTicketsLoading } = useValues(
+ supportTicketSceneLogic({ id: ticketId })
+ )
+ const { user } = useValues(userLogic)
+ const { currentTeam } = useValues(teamLogic)
+ const aiSuggestionsEnabled = !!currentTeam?.conversations_settings?.ai_suggestions_enabled
+ const isWidgetTicket = ticket?.channel_source === 'widget'
+
+ const slots: TicketSidebarWidgetSlots = {
+ related_groups: {
+ content:
+ person?.uuid || ticket?.organization_id ? (
+ <RelatedGroupsPanel
+ personUuid={person?.uuid}
+ organizationId={ticket?.organization_id}
+ organizationIdSource={ticket?.organization_id_source}
+ />
+ ) : null,
+ unavailableReason: 'This ticket has no linked person or organization.',
+ },
+ ...(user?.is_staff ? { staff_actions: { content: ticket ? <StaffActionsPanel /> : null } } : {}),
+ ai_triage: {
+ content: aiSuggestionsEnabled && ticket ? <AIPanel aiTriage={ticket.ai_triage} /> : null,
+ unavailableReason: 'AI suggestions are off for this project.',
+ },
+ session_recording: {
+ content: isWidgetTicket ? (
+ <SessionRecordingPanel sessionContext={ticket?.session_context} distinctId={ticket?.distinct_id} />
+ ) : null,
+ unavailableReason: WIDGET_TICKET_ONLY,
+ },
+ recent_events: {
+ content: isWidgetTicket ? (
+ <RecentEventsPanel
+ eventsQuery={eventsQuery}
+ distinctId={ticket?.distinct_id}
+ sessionId={ticket?.session_id}
+ />
+ ) : null,
+ unavailableReason: WIDGET_TICKET_ONLY,
+ },
+ exceptions: {
+ content: isWidgetTicket ? (
+ <ExceptionsPanel
+ exceptionsQuery={exceptionsQuery}
+ sessionId={ticket?.session_id}
+ distinctId={ticket?.distinct_id}
+ />
+ ) : null,
+ unavailableReason: WIDGET_TICKET_ONLY,
+ },
+ previous_tickets: {
+ content: isWidgetTicket ? (
+ <PreviousTicketsPanel
+ previousTickets={previousTickets}
+ previousTicketsLoading={previousTicketsLoading}
+ personDistinctIds={person?.distinct_ids}
+ />
+ ) : null,
+ unavailableReason: WIDGET_TICKET_ONLY,
+ },
+ activity: {
+ content: ticket?.id ? <TicketActivityPanel ticketId={ticket.id} /> : null,
+ },
+ }
+
+ return <TicketSidebarWidgets slots={slots} />
+}
diff --git a/products/conversations/frontend/components/TicketSidebarWidgetEditorRow/TicketSidebarWidgetEditorRow.tsx b/products/conversations/frontend/components/TicketSidebarWidgetEditorRow/TicketSidebarWidgetEditorRow.tsx
new file mode 100644
index 000000000000..5ead7aa55a42
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgetEditorRow/TicketSidebarWidgetEditorRow.tsx
@@ -0,0 +1,55 @@
+import { useSortable } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { SortableDragIcon } from 'lib/lemon-ui/icons'
+
+import { TicketSidebarWidgetKey, ticketSidebarWidget } from '../TicketSidebarWidgets/ticketSidebarLayout'
+
+interface TicketSidebarWidgetEditorRowProps {
+ widgetKey: TicketSidebarWidgetKey
+ unavailableReason?: string
+ onHide: () => void
+}
+
+export function TicketSidebarWidgetEditorRow({
+ widgetKey,
+ unavailableReason,
+ onHide,
+}: TicketSidebarWidgetEditorRowProps): JSX.Element {
+ const { setNodeRef, attributes, listeners, transform, transition } = useSortable({ id: widgetKey })
+ const { title, description } = ticketSidebarWidget(widgetKey)
+
+ return (
+ <div
+ ref={setNodeRef}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ transform: CSS.Transform.toString(transform), transition }}
+ className="flex items-start gap-2 rounded border bg-surface-primary p-2"
+ data-attr={`ticket-sidebar-widget-row-${widgetKey}`}
+ >
+ <span
+ {...attributes}
+ {...listeners}
+ aria-label={`Move ${title}`}
+ className="cursor-grab text-secondary pt-0.5 shrink-0"
+ >
+ <SortableDragIcon />
+ </span>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-semibold truncate">{title}</div>
+ <div className="text-xs text-secondary">{description}</div>
+ {unavailableReason && <div className="text-xs text-muted-alt mt-1">{unavailableReason}</div>}
+ </div>
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ onClick={onHide}
+ tooltip={`Hide ${title}`}
+ data-attr="ticket-sidebar-widget-hide"
+ />
+ </div>
+ )
+}
diff --git a/products/conversations/frontend/components/TicketSidebarWidgets/TicketSidebarWidgets.tsx b/products/conversations/frontend/components/TicketSidebarWidgets/TicketSidebarWidgets.tsx
new file mode 100644
index 000000000000..e5c56abc4f1d
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgets/TicketSidebarWidgets.tsx
@@ -0,0 +1,45 @@
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
+
+import { IconPencil } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { TicketSidebarWidgetsEditor } from '../TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor'
+import { TicketSidebarWidgetSlots } from './ticketSidebarLayout'
+import { ticketSidebarWidgetsLogic } from './ticketSidebarWidgetsLogic'
+
+export function TicketSidebarWidgets({ slots }: { slots: TicketSidebarWidgetSlots }): JSX.Element {
+ const { layout, isEditing } = useValues(ticketSidebarWidgetsLogic)
+ const { startEditing } = useActions(ticketSidebarWidgetsLogic)
+
+ if (isEditing) {
+ return <TicketSidebarWidgetsEditor slots={slots} />
+ }
+
+ const shown = layout.visible.flatMap((key) => {
+ const content = slots[key]?.content
+ return content ? [{ key, content }] : []
+ })
+
+ return (
+ <>
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold m-0">Widgets</h3>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconPencil />}
+ onClick={startEditing}
+ data-attr="ticket-sidebar-widgets-edit"
+ >
+ Edit widgets
+ </LemonButton>
+ </div>
+ {shown.length === 0 ? (
+ <div className="text-xs text-secondary">No widgets to show on this ticket.</div>
+ ) : (
+ shown.map(({ key, content }) => <Fragment key={key}>{content}</Fragment>)
+ )}
+ </>
+ )
+}
diff --git a/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarLayout.ts b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarLayout.ts
new file mode 100644
index 000000000000..2e0c62cfe178
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarLayout.ts
@@ -0,0 +1,111 @@
+import { TicketSidebarConfiguration } from '~/queries/schema/schema-general'
+
+// pinned: widget keys are stored in each user's saved layout on their account. Renaming one resets it.
+export type TicketSidebarWidgetKey =
+ | 'related_groups'
+ | 'staff_actions'
+ | 'ai_triage'
+ | 'session_recording'
+ | 'recent_events'
+ | 'exceptions'
+ | 'previous_tickets'
+ | 'activity'
+
+export interface TicketSidebarWidgetDefinition {
+ key: TicketSidebarWidgetKey
+ title: string
+ description: string
+}
+
+/** The order here is the default layout, and where a widget lands when a saved layout predates it. */
+export const TICKET_SIDEBAR_WIDGETS: TicketSidebarWidgetDefinition[] = [
+ {
+ key: 'related_groups',
+ title: 'Related groups',
+ description: 'Groups the customer belongs to, with revenue.',
+ },
+ {
+ key: 'staff_actions',
+ title: 'Staff actions',
+ description: 'Log in as the customer. Only visible to staff.',
+ },
+ {
+ key: 'ai_triage',
+ title: 'AI triage',
+ description: 'What the AI found when it triaged the ticket.',
+ },
+ {
+ key: 'session_recording',
+ title: 'Session recording',
+ description: 'The recording of the session the ticket came from.',
+ },
+ {
+ key: 'recent_events',
+ title: 'Recent events',
+ description: 'Events from around the time the ticket was created.',
+ },
+ {
+ key: 'exceptions',
+ title: 'Exceptions',
+ description: 'Exceptions from the session the ticket came from.',
+ },
+ {
+ key: 'previous_tickets',
+ title: 'Previous tickets',
+ description: 'Other tickets from the same customer.',
+ },
+ {
+ key: 'activity',
+ title: 'Ticket activity history',
+ description: 'Changes made to this ticket.',
+ },
+]
+
+const WIDGETS_BY_KEY = new Map(TICKET_SIDEBAR_WIDGETS.map((widget) => [widget.key, widget]))
+
+export function ticketSidebarWidget(key: TicketSidebarWidgetKey): TicketSidebarWidgetDefinition {
+ return WIDGETS_BY_KEY.get(key) as TicketSidebarWidgetDefinition
+}
+
+function isTicketSidebarWidgetKey(key: unknown): key is TicketSidebarWidgetKey {
+ return typeof key === 'string' && WIDGETS_BY_KEY.has(key as TicketSidebarWidgetKey)
+}
+
+export interface TicketSidebarLayout {
+ visible: TicketSidebarWidgetKey[]
+ hidden: TicketSidebarWidgetKey[]
+}
+
+export function resolveTicketSidebarLayout(stored: TicketSidebarConfiguration | null | undefined): TicketSidebarLayout {
+ const order = Array.from(new Set((stored?.order ?? []).filter(isTicketSidebarWidgetKey)))
+ // A widget added after the layout was saved shows up instead of staying hidden forever.
+ for (const { key } of TICKET_SIDEBAR_WIDGETS) {
+ if (!order.includes(key)) {
+ order.push(key)
+ }
+ }
+ const hidden = new Set((stored?.hidden ?? []).filter(isTicketSidebarWidgetKey))
+ return {
+ visible: order.filter((key) => !hidden.has(key)),
+ hidden: order.filter((key) => hidden.has(key)),
+ }
+}
+
+export const DEFAULT_TICKET_SIDEBAR_LAYOUT: TicketSidebarLayout = resolveTicketSidebarLayout(null)
+
+export function storeTicketSidebarLayout(layout: TicketSidebarLayout): Required<TicketSidebarConfiguration> {
+ return { order: [...layout.visible, ...layout.hidden], hidden: [...layout.hidden] }
+}
+
+export function ticketSidebarLayoutsEqual(a: TicketSidebarLayout, b: TicketSidebarLayout): boolean {
+ return a.visible.join() === b.visible.join() && a.hidden.join() === b.hidden.join()
+}
+
+export interface TicketSidebarWidgetSlot {
+ /** null when the widget has nothing to show on this ticket. */
+ content: JSX.Element | null
+ unavailableReason?: string
+}
+
+/** A widget the current user may not see (such as staff actions) has no slot, so the editor leaves it out too. */
+export type TicketSidebarWidgetSlots = Partial<Record<TicketSidebarWidgetKey, TicketSidebarWidgetSlot>>
diff --git a/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.test.ts b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.test.ts
new file mode 100644
index 000000000000..1c8b221962ca
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.test.ts
@@ -0,0 +1,108 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { TicketSidebarConfiguration, UserUIConfiguration } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { UserType } from '~/types'
+
+import { TICKET_SIDEBAR_WIDGETS, resolveTicketSidebarLayout } from './ticketSidebarLayout'
+import { ticketSidebarWidgetsLogic } from './ticketSidebarWidgetsLogic'
+
+const ALL_KEYS = TICKET_SIDEBAR_WIDGETS.map((widget) => widget.key)
+
+describe('ticketSidebarWidgetsLogic', () => {
+ let mountedLogic: ReturnType<typeof ticketSidebarWidgetsLogic.build> | undefined
+ let patchedUser: Partial<UserType> | null
+
+ function setUp(uiConfiguration: UserUIConfiguration | null): ReturnType<typeof ticketSidebarWidgetsLogic.build> {
+ initKeaTests()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, ui_configuration: uiConfiguration })
+ mountedLogic = ticketSidebarWidgetsLogic()
+ mountedLogic.mount()
+ return mountedLogic
+ }
+
+ beforeEach(() => {
+ patchedUser = null
+ useMocks({
+ patch: {
+ '/api/users/@me/': async ({ request }) => {
+ patchedUser = (await request.json()) as Partial<UserType>
+ return [200, { ...MOCK_DEFAULT_USER, ...patchedUser }]
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ mountedLogic?.unmount()
+ mountedLogic = undefined
+ })
+
+ test.each([
+ ['no saved layout shows every widget in default order', null, ALL_KEYS, []],
+ [
+ 'a widget missing from an older saved layout still shows',
+ { order: ['activity', 'ai_triage'], hidden: ['ai_triage'] },
+ ['activity', ...ALL_KEYS.filter((key) => key !== 'activity' && key !== 'ai_triage')],
+ ['ai_triage'],
+ ],
+ [
+ 'unknown and repeated keys are ignored',
+ { order: ['removed_widget', 'exceptions', 'exceptions'], hidden: ['removed_widget'] },
+ ['exceptions', ...ALL_KEYS.filter((key) => key !== 'exceptions')],
+ [],
+ ],
+ ])('resolving a stored layout: %s', (_name, stored, visible, hidden) => {
+ expect(resolveTicketSidebarLayout(stored as TicketSidebarConfiguration | null)).toEqual({ visible, hidden })
+ })
+
+ it('shows edits only once saved to the account, and drops them on cancel', async () => {
+ const logic = setUp(null)
+
+ logic.actions.startEditing()
+ logic.actions.hideWidget('ai_triage')
+ logic.actions.moveWidget(logic.values.layout.visible.indexOf('activity'), 0)
+ logic.actions.cancelEditing()
+
+ await expectLogic(logic).toMatchValues({ isEditing: false, userLayout: null })
+ expect(logic.values.layout.visible).toEqual(ALL_KEYS)
+ expect(patchedUser).toBeNull()
+
+ await expectLogic(logic, () => {
+ logic.actions.startEditing()
+ logic.actions.hideWidget('ai_triage')
+ logic.actions.moveWidget(logic.values.layout.visible.indexOf('activity'), 0)
+ logic.actions.saveLayout()
+ }).toFinishAllListeners()
+
+ const visible = ['activity', ...ALL_KEYS.filter((key) => key !== 'activity' && key !== 'ai_triage')]
+ expect(patchedUser?.ui_configuration).toEqual({
+ version: 1,
+ ticket_sidebar: { order: [...visible, 'ai_triage'], hidden: ['ai_triage'] },
+ })
+ expect(logic.values.isEditing).toBe(false)
+ expect(logic.values.layout).toEqual({ visible, hidden: ['ai_triage'] })
+ })
+
+ it('saving the default clears the stored layout and keeps the other UI settings', async () => {
+ const logic = setUp({
+ version: 1,
+ sql_editor: { vim_mode_enabled: true },
+ ticket_sidebar: { hidden: ['exceptions'] },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.startEditing()
+ logic.actions.resetDraftToDefault()
+ logic.actions.saveLayout()
+ }).toFinishAllListeners()
+
+ expect(patchedUser?.ui_configuration).toEqual({ version: 1, sql_editor: { vim_mode_enabled: true } })
+ expect(logic.values.userLayout).toBeNull()
+ })
+})
diff --git a/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.ts b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.ts
new file mode 100644
index 000000000000..b42631f30172
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgets/ticketSidebarWidgetsLogic.ts
@@ -0,0 +1,180 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { UI_CONFIGURATION_VERSION, uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
+import { TicketSidebarConfiguration, UserUIConfiguration } from '~/queries/schema/schema-general'
+
+import {
+ DEFAULT_TICKET_SIDEBAR_LAYOUT,
+ TicketSidebarLayout,
+ TicketSidebarWidgetKey,
+ resolveTicketSidebarLayout,
+ storeTicketSidebarLayout,
+ ticketSidebarLayoutsEqual,
+} from './ticketSidebarLayout'
+
+// pinned: analytics event names. Renaming them breaks insights built on them.
+const EDIT_STARTED_EVENT = 'support ticket sidebar edit started'
+const EDIT_CANCELED_EVENT = 'support ticket sidebar edit canceled'
+const LAYOUT_SAVED_EVENT = 'support ticket sidebar layout saved'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface ticketSidebarWidgetsLogicValues {
+ uiConfiguration: UserUIConfiguration | null // uiCustomizationLogic
+ draft: TicketSidebarLayout | null
+ draftMatchesDefault: boolean
+ isEditing: boolean
+ layout: TicketSidebarLayout
+ userLayout: TicketSidebarConfiguration | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface ticketSidebarWidgetsLogicActions {
+ updateUiConfiguration: (
+ configuration: UserUIConfiguration,
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
+ ) => {
+ configuration: UserUIConfiguration
+ failureCallback: (() => void) | undefined
+ successCallback: (() => void) | undefined
+ } // uiCustomizationLogic
+ cancelEditing: () => {
+ value: true
+ }
+ hideWidget: (key: TicketSidebarWidgetKey) => {
+ key: TicketSidebarWidgetKey
+ }
+ moveWidget: (
+ fromIndex: number,
+ toIndex: number
+ ) => {
+ fromIndex: number
+ toIndex: number
+ }
+ resetDraftToDefault: () => {
+ value: true
+ }
+ saveLayout: () => {
+ value: true
+ }
+ setDraft: (draft: TicketSidebarLayout | null) => {
+ draft: TicketSidebarLayout | null
+ }
+ showWidget: (key: TicketSidebarWidgetKey) => {
+ key: TicketSidebarWidgetKey
+ }
+ startEditing: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface ticketSidebarWidgetsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ userLayout: (uiConfiguration: UserUIConfiguration | null) => TicketSidebarConfiguration | null
+ isEditing: (draft: TicketSidebarLayout | null) => boolean
+ layout: (
+ draft: TicketSidebarLayout | null,
+ userLayout: TicketSidebarConfiguration | null
+ ) => TicketSidebarLayout
+ draftMatchesDefault: (draft: TicketSidebarLayout | null) => boolean
+ }
+}
+
+export type ticketSidebarWidgetsLogicType = MakeLogicType<
+ ticketSidebarWidgetsLogicValues,
+ ticketSidebarWidgetsLogicActions,
+ Record<string, any>,
+ ticketSidebarWidgetsLogicMeta
+>
+
+export const ticketSidebarWidgetsLogic = kea<ticketSidebarWidgetsLogicType>([
+ path(['products', 'conversations', 'frontend', 'components', 'TicketSidebarWidgets', 'ticketSidebarWidgetsLogic']),
+ connect(() => ({
+ values: [uiCustomizationLogic, ['uiConfiguration']],
+ actions: [uiCustomizationLogic, ['updateUiConfiguration']],
+ })),
+ actions({
+ startEditing: true,
+ cancelEditing: true,
+ setDraft: (draft: TicketSidebarLayout | null) => ({ draft }),
+ moveWidget: (fromIndex: number, toIndex: number) => ({ fromIndex, toIndex }),
+ hideWidget: (key: TicketSidebarWidgetKey) => ({ key }),
+ showWidget: (key: TicketSidebarWidgetKey) => ({ key }),
+ resetDraftToDefault: true,
+ saveLayout: true,
+ }),
+ reducers({
+ draft: [
+ null as TicketSidebarLayout | null,
+ {
+ setDraft: (_, { draft }) => draft,
+ cancelEditing: () => null,
+ moveWidget: (state, { fromIndex, toIndex }) => {
+ const inRange = (index: number): boolean => index >= 0 && index < (state?.visible.length ?? 0)
+ if (!state || fromIndex === toIndex || !inRange(fromIndex) || !inRange(toIndex)) {
+ return state
+ }
+ const visible = [...state.visible]
+ const [moved] = visible.splice(fromIndex, 1)
+ visible.splice(toIndex, 0, moved)
+ return { ...state, visible }
+ },
+ hideWidget: (state, { key }) =>
+ state && state.visible.includes(key)
+ ? { visible: state.visible.filter((k) => k !== key), hidden: [...state.hidden, key] }
+ : state,
+ showWidget: (state, { key }) =>
+ state && state.hidden.includes(key)
+ ? { visible: [...state.visible, key], hidden: state.hidden.filter((k) => k !== key) }
+ : state,
+ },
+ ],
+ }),
+ selectors({
+ userLayout: [
+ (s) => [s.uiConfiguration],
+ (uiConfiguration: UserUIConfiguration | null): TicketSidebarConfiguration | null =>
+ uiConfiguration?.ticket_sidebar ?? null,
+ ],
+ isEditing: [(s) => [s.draft], (draft: TicketSidebarLayout | null): boolean => draft !== null],
+ layout: [
+ (s) => [s.draft, s.userLayout],
+ (draft: TicketSidebarLayout | null, userLayout: TicketSidebarConfiguration | null): TicketSidebarLayout =>
+ draft ?? resolveTicketSidebarLayout(userLayout),
+ ],
+ draftMatchesDefault: [
+ (s) => [s.draft],
+ (draft: TicketSidebarLayout | null): boolean =>
+ !!draft && ticketSidebarLayoutsEqual(draft, DEFAULT_TICKET_SIDEBAR_LAYOUT),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ startEditing: () => {
+ actions.setDraft(values.layout)
+ posthog.capture(EDIT_STARTED_EVENT, { has_saved_layout: values.userLayout !== null })
+ },
+ cancelEditing: () => {
+ posthog.capture(EDIT_CANCELED_EVENT)
+ },
+ resetDraftToDefault: () => {
+ actions.setDraft(DEFAULT_TICKET_SIDEBAR_LAYOUT)
+ },
+ saveLayout: () => {
+ const { draft, draftMatchesDefault, uiConfiguration } = values
+ if (!draft) {
+ return
+ }
+ posthog.capture(LAYOUT_SAVED_EVENT, { visible_widgets: draft.visible, hidden_widgets: draft.hidden })
+ // The server replaces ui_configuration wholesale, so every other key is carried over.
+ // Saving the default stores nothing, so the user keeps getting later changes to the default order.
+ actions.updateUiConfiguration({
+ version: UI_CONFIGURATION_VERSION,
+ ...uiConfiguration,
+ ticket_sidebar: draftMatchesDefault ? undefined : storeTicketSidebarLayout(draft),
+ })
+ actions.setDraft(null)
+ },
+ })),
+])
diff --git a/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.stories.tsx b/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.stories.tsx
new file mode 100644
index 000000000000..c818c295e52a
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.stories.tsx
@@ -0,0 +1,35 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { TicketSidebarWidgetSlots } from '../TicketSidebarWidgets/ticketSidebarLayout'
+import { TicketSidebarWidgetsEditor } from './TicketSidebarWidgetsEditor'
+
+const meta: Meta<typeof TicketSidebarWidgetsEditor> = {
+ title: 'Scenes-App/Support/TicketSidebarWidgetsEditor',
+ component: TicketSidebarWidgetsEditor,
+ parameters: { layout: 'padded', viewMode: 'story', testOptions: { snapshotBrowsers: [] } },
+}
+export default meta
+
+type Story = StoryObj<typeof TicketSidebarWidgetsEditor>
+
+const placeholder = <div />
+
+// No staff_actions slot, as for a non-staff user. AI triage has nothing to show on this ticket.
+const slots: TicketSidebarWidgetSlots = {
+ related_groups: { content: placeholder },
+ ai_triage: { content: null, unavailableReason: 'AI suggestions are off for this project.' },
+ session_recording: { content: placeholder },
+ recent_events: { content: placeholder },
+ exceptions: { content: placeholder },
+ previous_tickets: { content: placeholder },
+ activity: { content: placeholder },
+}
+
+export const NarrowSidebar: Story = {
+ render: () => (
+ // The sidebar's minimum width next to the chat.
+ <div className="w-[300px]">
+ <TicketSidebarWidgetsEditor slots={slots} />
+ </div>
+ ),
+}
diff --git a/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.tsx b/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.tsx
new file mode 100644
index 000000000000..fb6e011e1e72
--- /dev/null
+++ b/products/conversations/frontend/components/TicketSidebarWidgetsEditor/TicketSidebarWidgetsEditor.tsx
@@ -0,0 +1,110 @@
+import { DndContext, DragEndEvent } from '@dnd-kit/core'
+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
+import { useActions, useValues } from 'kea'
+
+import { IconPlus } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonMenu } from '@posthog/lemon-ui'
+
+import { TicketSidebarWidgetEditorRow } from '../TicketSidebarWidgetEditorRow/TicketSidebarWidgetEditorRow'
+import {
+ TicketSidebarWidgetKey,
+ TicketSidebarWidgetSlots,
+ ticketSidebarWidget,
+} from '../TicketSidebarWidgets/ticketSidebarLayout'
+import { ticketSidebarWidgetsLogic } from '../TicketSidebarWidgets/ticketSidebarWidgetsLogic'
+
+export function TicketSidebarWidgetsEditor({ slots }: { slots: TicketSidebarWidgetSlots }): JSX.Element {
+ const { layout, draftMatchesDefault } = useValues(ticketSidebarWidgetsLogic)
+ const { moveWidget, hideWidget, showWidget, cancelEditing, saveLayout, resetDraftToDefault } =
+ useActions(ticketSidebarWidgetsLogic)
+
+ // A widget this user can't see, such as staff actions, keeps its place in the layout but is left out here.
+ const canSee = (key: TicketSidebarWidgetKey): boolean => key in slots
+ const visible = layout.visible.filter(canSee)
+ const addable = layout.hidden.filter(canSee)
+
+ const onDragEnd = ({ active, over }: DragEndEvent): void => {
+ if (!over || active.id === over.id) {
+ return
+ }
+ const fromIndex = layout.visible.indexOf(active.id as TicketSidebarWidgetKey)
+ const toIndex = layout.visible.indexOf(over.id as TicketSidebarWidgetKey)
+ if (fromIndex >= 0 && toIndex >= 0) {
+ moveWidget(fromIndex, toIndex)
+ }
+ }
+
+ return (
+ <LemonCard hoverEffect={false} className="p-3 flex flex-col gap-3">
+ <div>
+ <h3 className="text-sm font-semibold m-0">Edit widgets</h3>
+ <p className="text-xs text-secondary m-0 mt-1">
+ Drag widgets to reorder them. A hidden widget doesn't show on any ticket.
+ </p>
+ </div>
+
+ {visible.length === 0 ? (
+ <div className="text-xs text-secondary">All widgets are hidden. Add one to show it on tickets.</div>
+ ) : (
+ <DndContext onDragEnd={onDragEnd} modifiers={[restrictToVerticalAxis, restrictToParentElement]}>
+ <SortableContext items={visible} strategy={verticalListSortingStrategy}>
+ <div className="flex flex-col gap-2">
+ {visible.map((key) => (
+ <TicketSidebarWidgetEditorRow
+ key={key}
+ widgetKey={key}
+ unavailableReason={slots[key]?.content ? undefined : slots[key]?.unavailableReason}
+ onHide={() => hideWidget(key)}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
+
+ <LemonMenu
+ placement="bottom-start"
+ items={addable.map((key) => ({
+ label: ticketSidebarWidget(key).title,
+ onClick: () => showWidget(key),
+ }))}
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ disabledReason={addable.length === 0 ? 'All widgets are already shown' : undefined}
+ data-attr="ticket-sidebar-widgets-add"
+ >
+ Add widget
+ </LemonButton>
+ </LemonMenu>
+
+ <div className="flex flex-wrap items-center justify-between gap-2 pt-3 border-t">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={resetDraftToDefault}
+ disabledReason={draftMatchesDefault ? 'This is already the default layout' : undefined}
+ data-attr="ticket-sidebar-widgets-reset"
+ >
+ Reset to default
+ </LemonButton>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonButton type="secondary" size="small" onClick={cancelEditing}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={saveLayout}
+ data-attr="ticket-sidebar-widgets-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
index f44a2947e90d..5bc1cea02813 100644
--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
@@ -37,6 +37,7 @@ import { SupportMarkdown } from '../../components/Editor'
import { IdentityBadge } from '../../components/IdentityBadge/IdentityBadge'
import { MacroPicker } from '../../components/Macros/MacroPicker'
import { SlaDisplay } from '../../components/SlaDisplay/SlaDisplay'
+import { SupportTicketSidebarWidgets } from '../../components/SupportTicketSidebarWidgets/SupportTicketSidebarWidgets'
import { TicketTags } from '../../components/TicketTags'
import {
type Ticket,
@@ -45,18 +46,10 @@ import {
priorityOptions,
statusOptionsWithoutAll,
} from '../../types'
-import { AIPanel } from './AIPanel'
-import { ExceptionsPanel } from './ExceptionsPanel'
-import { PreviousTicketsPanel } from './PreviousTicketsPanel'
-import { RecentEventsPanel } from './RecentEventsPanel'
-import { RelatedGroupsPanel } from './RelatedGroupsPanel'
-import { SessionRecordingPanel } from './SessionRecordingPanel'
-import { StaffActionsPanel } from './StaffActionsPanel'
import { supportTicketSceneLogic } from './supportTicketSceneLogic'
import { SupportTicketSceneMenuBar } from './SupportTicketSceneMenuBar'
import { useDiscussionTimelineExtras } from './ThreadDiscussions'
import { reportTimelineExtras } from './ThreadReports'
-import { TicketActivityPanel } from './TicketActivityPanel'
// The list's filters / saved view ride along in the ticket page's query string
// (the ticket row carries them through on navigation). Rebuild the list URL from
@@ -107,7 +100,6 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
const logic = supportTicketSceneLogic({ id: ticketId || 'new' })
const {
ticket,
- person,
ticketLoading,
status,
priority,
@@ -119,11 +111,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
messageSending,
hasMoreMessages,
olderMessagesLoading,
- eventsQuery,
- previousTickets,
- previousTicketsLoading,
linkedReports,
- exceptionsQuery,
chatPanelWidth,
hasUnsavedChanges,
unsavedTicketChanges,
@@ -670,54 +658,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
</div>
</LemonCard>
- {/* Related Groups Panel */}
- {(person?.uuid || ticket?.organization_id) && (
- <RelatedGroupsPanel
- personUuid={person?.uuid}
- organizationId={ticket?.organization_id}
- organizationIdSource={ticket?.organization_id_source}
- />
- )}
-
- {/* Staff Actions Panel */}
- {user?.is_staff && ticket && <StaffActionsPanel />}
-
- {/* AI Triage Panel */}
- {aiSuggestionsEnabled && ticket && <AIPanel aiTriage={ticket.ai_triage} />}
-
- {ticket?.channel_source === 'widget' && (
- <>
- {/* Session Recording Panel */}
- <SessionRecordingPanel
- sessionContext={ticket?.session_context}
- distinctId={ticket?.distinct_id}
- />
-
- {/* Recent Events Panel */}
- <RecentEventsPanel
- eventsQuery={eventsQuery}
- distinctId={ticket?.distinct_id}
- sessionId={ticket?.session_id}
- />
-
- {/* Exceptions Panel */}
- <ExceptionsPanel
- exceptionsQuery={exceptionsQuery}
- sessionId={ticket?.session_id}
- distinctId={ticket?.distinct_id}
- />
-
- {/* Previous Tickets Panel */}
- <PreviousTicketsPanel
- previousTickets={previousTickets}
- previousTicketsLoading={previousTicketsLoading}
- personDistinctIds={person?.distinct_ids}
- />
- </>
- )}
-
- {/* Activity History Panel */}
- {ticket?.id && <TicketActivityPanel ticketId={ticket.id} />}
+ <SupportTicketSidebarWidgets ticketId={ticketId || 'new'} />
</div>
</div>
</SceneContent>
diff --git a/products/conversations/package.json b/products/conversations/package.json
index bd333ec00235..dcb8f3fac6a5 100644
--- a/products/conversations/package.json
+++ b/products/conversations/package.json
@@ -20,6 +20,10 @@
"kea-test-utils": "catalog:"
},
"peerDependencies": {
+ "@dnd-kit/core": "*",
+ "@dnd-kit/modifiers": "*",
+ "@dnd-kit/sortable": "*",
+ "@dnd-kit/utilities": "*",
"@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
"@posthog/lemon-ui": "*",