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(posthog-ai): add slash commands to the runner composer (#105792)

Vojta Bartošc71fb56c1b4c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cfb25b6b15e3..39ba707170df 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5556,10 +5556,6 @@ snapshots:
hash: v1.k794b7964.31e41069d269db8708235ebe4532f1d192bbaa665684020f6fdb4027aa8acd46.ZUY6P6E0RJdx4a7g6MNz26VSupyhqYn89k6oTj8xmEM
marketing-analytics-dashboard-breakdown-table--narrow-comparison--light:
hash: v1.k794b7964.aeb0d17c3166922193e00df2ff2b294a46046f5f0dafb448eb378b03f45de07a.6g_f5vb1BIZzlbnBa0ii0axbN9XzPruR7CZfbKiDGK4
- marketing-analytics-dashboard-metric-cards--interactive--dark:
- hash: v1.k794b7964.4c13e857435c2bee42eea33c6f86ab2d46f0d3c1c9d997f32bcdc57cf1e7dafc.J9JahhAU6VQmtGCK8icH17WJvkELlNa7DkbabJ2wtRU
- marketing-analytics-dashboard-metric-cards--interactive--light:
- hash: v1.k794b7964.ae261dc53797e4fa4d00cd299f8d48d6e2c1281786d5048a36582ed229bec412.jGf_7LuJ55QW0GvghJfa-eid3j8lLV2NLhJGymTVmXU
marketing-analytics-dashboard-metric-cards--loading--dark:
hash: v1.k794b7964.51ad00cd8818358b38d57bdd5d694ea98446dbdef7727db1e6f89320dacb1ff9.XLLDF_4xHonffqOBzexuguHLaGw8rSq4xMKSN5cSZmU
marketing-analytics-dashboard-metric-cards--loading--light:
@@ -6520,10 +6516,18 @@ snapshots:
hash: v1.k794b7964.de4a523033a10250834aa0917403e6ec61e3d3cdd99300830676e6ba81869e5b.AD54AJl9xbBHB2tql3MqC62FAcU85AgoIV4-aEgzV3s
products-posthog-ai-composer--sticky--light:
hash: v1.k794b7964.91c7a1b9be80ab39efcb23561be33d7431da793f1e254a9dc4341515603767b6.zTpu8qftYG9C2ZtNdxPVN6GAx47a4kCDE6JGUOd-UJ8
+ products-posthog-ai-composer--with-app-slash-commands-only--dark:
+ hash: v1.k794b7964.1746781bf166d66c89ef64b238bbb24cfd6f8e44ccf56b22dee2a5d16774f89f.VEXWdeXl4iFJnb8jQTOHCgBq9Nsmn5gtf6K8h64Iv6w
+ products-posthog-ai-composer--with-app-slash-commands-only--light:
+ hash: v1.k794b7964.f0d2a1b103dade108a3479870bacf7f1f74135b8a4eadf8401f5317c28c70728.G6kvvbgci3XUpRdR60eaQtXvYmZtk1ixIXB2701o1kg
products-posthog-ai-composer--with-header-and-footer--dark:
hash: v1.k794b7964.22ac7c8b09740244c64d667b8632b8ab2b024a2e8a1483fe532dd8de77471785.QFjXKbpbw8aoCIy5zHmNw1sbnhwOQYwCs5nmwOthF8Y
products-posthog-ai-composer--with-header-and-footer--light:
hash: v1.k794b7964.5d937bb4b6cd8476bd83663f71e73e604a69a61fb9f657a90597551f88e2bb9d.VookPDeBGmEcZsM07uyiIAYxtBNUAF4YB4Yg19vFcis
+ products-posthog-ai-composer--with-slash-commands--dark:
+ hash: v1.k794b7964.78e3a4fed21f357586eec5d1cfe2238b2f345381bdf3fb8aa8625f8047eb86e8.M5ZXnj4_M25eKQxkxZkvfqVEylkTelICACI2FQxw1xk
+ products-posthog-ai-composer--with-slash-commands--light:
+ hash: v1.k794b7964.6b8e440643d6eb0eb60c9a885df9f83ac28d3b3453a5c2f6de6482a0f338aa11.3Q0FXWPH9ccU3rvUz5NsKDwW1TYNyc0Id46_MQU30lg
products-posthog-ai-composer--with-up-next-queue--dark:
hash: v1.k794b7964.e893edaa31202a96439233ff254af446b1ae72107ca4d187a0ab27abc87db8ac.ClRtYW3AIl8tt8UNlaLx_52ymgYxs4FUUHPusEIzAs8
products-posthog-ai-composer--with-up-next-queue--light:
@@ -6625,17 +6629,17 @@ snapshots:
products-posthog-ai-runalertactivity--connection-lost-narrow--light:
hash: v1.k794b7964.8555bf34acfd36c149b40599f32ca9aba1e2e746b94e43abea582710b3c2dd3f.a8iigoMwFpLemT0mLL8QoBjdFHkg_IZ1uvvSireyP9U
products-posthog-ai-startup-chat--queued-sidebar--dark:
- hash: v1.k794b7964.b00472829dd4a536ce873322691bcbf252f3079eb37d0614c7fa9baf9e0b3272.DObEcDsp_ZwITHJgw5jyv6_t4h1oDp1U2jI0wTthlWU
+ hash: v1.k794b7964.64511ab3090bb1c47555f2f66169395314cb6dedfee2bb2cf127bf4022405470.opaLkUHD-RjeY3_kb_5H4veCE0s8Dt-aRo1H5WZPNeU
products-posthog-ai-startup-chat--queued-sidebar--light:
- hash: v1.k794b7964.ceb503685717e53ea184aa8db4d0ea628e0dfa54e8b1d40f60d0673237e70d88.gvHsmMSxj7yMkUJ5iNSBtcZu_dsjRF_i4KDcmt45iLg
+ hash: v1.k794b7964.e91fc770dfa66746faefb69b53ec2fb74580d620a246c3dcee4fd2d253d9aa89.irPFIkEUZ4AoypYJvAZ59uZvjIXUOFn4C9HyXHQ0GyA
products-posthog-ai-startup-chat--queued-wide--dark:
hash: v1.k794b7964.fba7548a6b2f99684156a97ebcb24427e2d09d340b8db7415d7a1adb08f23f08.PDnSLZW8eyRMhNNz8YZ4LuM0MlTtnL_FiZb4SDaTetM
products-posthog-ai-startup-chat--queued-wide--light:
hash: v1.k794b7964.d910e03de15c10ca08b56a953b274b2ac7ccd3f9ad9a6df8203abe522d2c2ebf.fVoRoJVneYM2oa3LCr5Q8Jn0-H2BkPh_GotYHvj-Q7U
products-posthog-ai-startup-chat--sidebar--dark:
- hash: v1.k794b7964.6d96696bb96a440ce1fa7b776edc81f103b6812009d0a850bcda00634acf485f.dm_X4B9rkIjkeWEqyEbies8fE9rJzn6jP1Rwjfl1Txs
+ hash: v1.k794b7964.9df1a431eabd0d314ea291036288e31d351d785e5f511f64fcd255ba86c04c16.YtLvYRZ_hIFGA6PPEN-wZgi5tq85gR0OluUYChuz2KU
products-posthog-ai-startup-chat--sidebar--light:
- hash: v1.k794b7964.21eaee49f9429125b726ca537df2609832e2d31297b0e98d8264964866f293cb.u5AJc9X9898pYhh_P0fqkrmxDZRscEkFWYiCq68frv4
+ hash: v1.k794b7964.e1316b144028fa93a29a2486b18e01e22274d3102e903619af020206b72ad385.u3M3m5PjmzT0G_e7ydqErsz0iMq2LUZSBPu0h0EWA3Q
products-posthog-ai-taskassigneefiltermenu--non-staff--dark:
hash: v1.k794b7964.054d05f7ef960ff884a3a325564585e3fcd4aaddccafe7fe05576c4a1f300737.RK0f_iJ30LfZp1s3ONdVO_74aI7AQBYwwTR-lOGnfBY
products-posthog-ai-taskassigneefiltermenu--non-staff--light:
diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.ts
index dace0d1b1c57..43cf5a045b01 100644
--- a/frontend/src/lib/components/Support/supportLogic.ts
+++ b/frontend/src/lib/components/Support/supportLogic.ts
@@ -512,6 +512,9 @@ export const supportLogic = kea<supportLogicType>([
exception_event,
billing_issue,
target,
+ ai_conversation_id,
+ ai_trace_id,
+ ai_feedback_rating,
}: Partial<SupportFormFields> & { target?: 'modal' | 'sidePanel' }) => {
kind = kind ?? 'support'
actions.resetSendSupportRequest({
@@ -521,6 +524,10 @@ export const supportLogic = kea<supportLogicType>([
message: message ?? values.sendSupportRequest.message ?? '',
exception_event,
billing_issue: billing_issue ?? false,
+ // Carried through so a PostHog AI handover still attributes the ticket it files.
+ ai_conversation_id,
+ ai_trace_id,
+ ai_feedback_rating,
})
if (isEmailFormOpen === 'true' || isEmailFormOpen === true) {
diff --git a/products/posthog_ai/frontend/components/composer/CommandResultCard.tsx b/products/posthog_ai/frontend/components/composer/CommandResultCard.tsx
new file mode 100644
index 000000000000..4b4d8fea209a
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/CommandResultCard.tsx
@@ -0,0 +1,40 @@
+import { IconX } from '@posthog/icons'
+import { LemonButton, Spinner } from '@posthog/lemon-ui'
+
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+
+export interface CommandResultCardProps {
+ title: string
+ /** Null while the answer loads. */
+ body: string | null
+ onDismiss: () => void
+}
+
+/** The output of an app slash command (`/btw`, `/usage`). It stays out of the conversation. */
+export function CommandResultCard({ title, body, onDismiss }: CommandResultCardProps): JSX.Element {
+ return (
+ <div
+ className="border border-primary rounded-lg bg-surface-primary px-3 py-2 mb-2 text-sm"
+ data-attr="sandbox-composer-command-result"
+ >
+ <div className="flex items-start gap-2">
+ <div className="font-semibold min-w-0 flex-1 break-words">{title}</div>
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ onClick={onDismiss}
+ tooltip="Dismiss"
+ data-attr="sandbox-composer-command-result-dismiss"
+ />
+ </div>
+ {body === null ? (
+ <div className="flex items-center gap-2 text-muted mt-1">
+ <Spinner />
+ <span>Thinking…</span>
+ </div>
+ ) : (
+ <LemonMarkdown className="mt-1 max-h-60 overflow-y-auto">{body}</LemonMarkdown>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/composer/Composer.stories.tsx b/products/posthog_ai/frontend/components/composer/Composer.stories.tsx
index 53f53a669501..6b4a85f1b094 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.stories.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.stories.tsx
@@ -4,8 +4,11 @@ import { useState } from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+import { APP_COMMANDS, buildSlashCommands } from '../../utils/slashCommands'
import { QueuedMessageList } from '../QueuedMessageList'
+import { CommandResultCard } from './CommandResultCard'
import { Composer } from './Composer'
+import { ComposerCommandMenu } from './ComposerCommandMenu'
// The Composer primitives are logic-free and controlled, so the stories own the value/submit state and
// assemble the parts the same way a real surface (the tasks run viewer, PostHog AI) does.
@@ -151,3 +154,71 @@ export const WithUpNextQueue: Story = {
)
},
}
+
+const STORY_SLASH_COMMANDS = buildSlashCommands(APP_COMMANDS, [
+ { name: 'clear', description: 'Clear conversation history and free up context' },
+ { name: 'compact', description: 'Clear conversation history but keep a summary in context' },
+ // Kept verbose: the menu's width cap is only exercised by a description this long.
+ {
+ name: 'querying-posthog-data',
+ description:
+ 'Required reading before writing any HogQL/SQL or calling execute-sql against PostHog. Use whenever the user wants to search, find, or do complex aggregations over PostHog entities and query analytics data.',
+ hint: 'question',
+ },
+])
+
+/** Typing `/` opens the slash command menu, and a side question answer sits in the Banner slot. */
+export const WithSlashCommands: Story = {
+ args: { initialValue: '/', isThreadVisible: true },
+ render: ({ initialValue, placeholder, ...rootProps }) => {
+ const [value, setValue] = useState(initialValue)
+ const [showResult, setShowResult] = useState(true)
+ return (
+ <div className="w-180 mx-auto p-4 pt-96">
+ <Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}>
+ {showResult && (
+ <Composer.Banner>
+ <CommandResultCard
+ title="Which table holds the signup events?"
+ body="Signups are `user signed up` events in the `events` table."
+ onDismiss={() => setShowResult(false)}
+ />
+ </Composer.Banner>
+ )}
+ <Composer.Frame>
+ <ComposerCommandMenu commands={STORY_SLASH_COMMANDS}>
+ <Composer.Field>
+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>
+ <Composer.Textarea />
+ </Composer.Field>
+ </ComposerCommandMenu>
+ </Composer.Frame>
+ <Composer.Submit />
+ </Composer.Root>
+ </div>
+ )
+ },
+}
+
+/** Before the agent has advertised its own commands, the menu says so rather than looking complete. */
+export const WithAppSlashCommandsOnly: Story = {
+ args: { initialValue: '/', isThreadVisible: true },
+ render: ({ initialValue, placeholder, ...rootProps }) => {
+ const [value, setValue] = useState(initialValue)
+ return (
+ <div className="w-180 mx-auto p-4 pt-96">
+ <Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}>
+ <Composer.Frame>
+ <ComposerCommandMenu commands={buildSlashCommands(APP_COMMANDS, [])}>
+ <Composer.Field>
+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>
+ <Composer.Textarea />
+ </Composer.Field>
+ </ComposerCommandMenu>
+ </Composer.Frame>
+ <Composer.Submit />
+ </Composer.Root>
+ </div>
+ )
+ },
+}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerCommandMenu.tsx b/products/posthog_ai/frontend/components/composer/ComposerCommandMenu.tsx
new file mode 100644
index 000000000000..cd3b72cd912f
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/ComposerCommandMenu.tsx
@@ -0,0 +1,143 @@
+import { type ReactElement, useEffect, useMemo, useRef, useState } from 'react'
+
+import { LemonMenu, type LemonMenuItem, type LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+
+import { type SlashCommand, filterSlashCommands } from '../../utils/slashCommands'
+import { useComposerContext } from './Composer'
+
+// `matchWidth` sets only a min-width, so a row has to carry the cap that bounds the menu.
+// The scroll margin clears the enclosing button's padding for `scrollIntoView`.
+const ROW_CLASSES = 'w-full max-w-xl min-w-0 scroll-my-2'
+
+// About five rows. Capping the list rather than the popover leaves the section footer in view; the
+// selector matches LemonMenu's section markup, where the rows are the `<ul>` next to that footer.
+const MENU_LIST_CLASSES = '[&_section>ul]:max-h-52 [&_section>ul]:overflow-y-auto'
+
+export interface ComposerCommandMenuProps {
+ commands: SlashCommand[]
+ /** The element the menu anchors to, usually `Composer.Field`. It must forward a ref. */
+ children: ReactElement
+}
+
+/** Keeps the highlighted command in view: the list caps its height, so a long list scrolls. */
+function CommandMenuItemLabel({ command, active }: { command: SlashCommand; active: boolean }): JSX.Element {
+ const ref = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ if (active) {
+ ref.current?.scrollIntoView({ block: 'nearest' })
+ }
+ }, [active])
+ return (
+ <div className={ROW_CLASSES} ref={ref}>
+ <div className="font-mono truncate">
+ /{command.name}
+ {command.hint && <span className="text-muted"> {command.hint}</span>}
+ </div>
+ {command.description && <div className="text-muted text-xs truncate">{command.description}</div>}
+ </div>
+ )
+}
+
+/**
+ * Suggests slash commands while the draft is a lone `/name` token. Selecting a command writes `/name ` into
+ * the draft, so the user can add arguments and then send it. Logic-free: the caller passes the commands.
+ */
+export function ComposerCommandMenu({ commands, children }: ComposerCommandMenuProps): JSX.Element {
+ const { value, onChange, textAreaRef } = useComposerContext()
+ const filtered = useMemo(() => filterSlashCommands(commands, value), [commands, value])
+ const [activeIndex, setActiveIndex] = useState(0)
+ // Escape hides the menu for the draft it was pressed on. Typing re-opens it.
+ const [dismissedFor, setDismissedFor] = useState<string | null>(null)
+ const visible = filtered.length > 0 && dismissedFor !== value
+ // Only the app's own commands exist until the agent advertises its list over the stream.
+ const hasAgentCommands = commands.some((command) => command.source === 'agent')
+
+ useEffect(() => {
+ setActiveIndex(0)
+ }, [filtered])
+
+ // Dismissal is keyed on the draft it was pressed on, so a later edit re-opens the menu. Drop it once
+ // the draft moves on, otherwise deleting the draft and typing the same text again stays dismissed.
+ useEffect(() => {
+ setDismissedFor((dismissed) => (dismissed === null || dismissed === value ? dismissed : null))
+ }, [value])
+
+ const select = (command: SlashCommand | undefined): void => {
+ if (!command) {
+ return
+ }
+ onChange(`/${command.name} `)
+ textAreaRef.current?.focus()
+ }
+
+ useEffect(() => {
+ if (!visible) {
+ return
+ }
+ const handleKeyDown = (e: KeyboardEvent): void => {
+ if (e.target !== textAreaRef.current) {
+ return
+ }
+ if (e.key === 'ArrowDown') {
+ e.preventDefault()
+ setActiveIndex((index) => (index + 1) % filtered.length)
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault()
+ setActiveIndex((index) => (index - 1 + filtered.length) % filtered.length)
+ } else if ((e.key === 'Enter' && !e.shiftKey) || (e.key === 'Tab' && !e.shiftKey)) {
+ e.preventDefault()
+ e.stopPropagation()
+ select(filtered[activeIndex])
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ e.stopPropagation()
+ setDismissedFor(value)
+ }
+ }
+ // Capture phase, so Enter selects a command before the textarea submits the draft.
+ document.addEventListener('keydown', handleKeyDown, { capture: true })
+ return () => document.removeEventListener('keydown', handleKeyDown, { capture: true })
+ })
+
+ const items: LemonMenuItems = [
+ {
+ key: 'commands',
+ items: filtered.map(
+ (command, index): LemonMenuItem => ({
+ key: command.name,
+ label: <CommandMenuItemLabel command={command} active={index === activeIndex} />,
+ onClick: () => select(command),
+ active: index === activeIndex,
+ 'data-attr': `sandbox-composer-slash-command-${command.source}`,
+ })
+ ),
+ footer: (
+ <div className="border-t px-1 pt-1.5 pb-0.5 mt-1 text-xxs text-muted-alt font-medium select-none">
+ {!hasAgentCommands && <div className="mb-0.5">The agent adds its own commands once it starts</div>}
+ ↑↓ to navigate • ⏎ or Tab to select • Esc to close
+ </div>
+ ),
+ },
+ ]
+
+ return (
+ <LemonMenu
+ matchWidth
+ className={MENU_LIST_CLASSES}
+ items={items}
+ visible={visible}
+ closeOnClickInside={false}
+ // The textarea sits outside the floating menu, so a click that moves the caret counts as outside.
+ onClickOutside={(event) => {
+ if (event.target !== textAreaRef.current) {
+ setDismissedFor(value)
+ }
+ }}
+ placement="top-start"
+ fallbackPlacements={['bottom-start']}
+ focusBasedKeyboardNavigation={false}
+ >
+ {children}
+ </LemonMenu>
+ )
+}
diff --git a/products/posthog_ai/frontend/logics/runSlashCommandsLogic.test.ts b/products/posthog_ai/frontend/logics/runSlashCommandsLogic.test.ts
new file mode 100644
index 000000000000..fc3790130357
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runSlashCommandsLogic.test.ts
@@ -0,0 +1,225 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { initKeaTests } from '~/test/init'
+
+import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'
+
+import { captureCommandFeedback } from '../utils/feedbackEvents'
+import { runInteractionLogic, type RunInteractionLogicProps } from './runInteractionLogic'
+import { runSlashCommandsLogic } from './runSlashCommandsLogic'
+import { runStreamLogic } from './runStreamLogic'
+
+jest.mock('./runStreamLogic', () => {
+ const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')
+ return {
+ runStreamLogic: kea([
+ path(['test', 'runStreamLogicStub']),
+ props({}),
+ key((p: { streamKey: string }) => p.streamKey),
+ actions({ setStubCommands: (commands: unknown[]) => ({ commands }) }),
+ reducers({
+ availableCommands: [[], { setStubCommands: (_: unknown, { commands }: any) => commands }],
+ bootstrappedRunId: ['run-1', {}],
+ bootstrappedTaskId: ['task-1', {}],
+ contextUsage: [null, {}],
+ traceId: ['trace-1', {}],
+ }),
+ ]),
+ }
+})
+
+jest.mock('./runInteractionLogic', () => {
+ const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')
+ return {
+ runInteractionLogic: kea([
+ path(['test', 'runInteractionLogicStub']),
+ props({}),
+ key((p: { runId: string }) => p.runId),
+ actions({
+ setDraft: (draft: string) => ({ draft }),
+ setStubTerminal: (terminal: boolean) => ({ terminal }),
+ setStubConsent: (accepted: boolean) => ({ accepted }),
+ submitComposerForm: true,
+ resetComposerForm: true,
+ blockOnConsent: true,
+ }),
+ reducers({
+ composerForm: [
+ { draft: '' },
+ {
+ setDraft: (_: unknown, { draft }: { draft: string }) => ({ draft }),
+ resetComposerForm: () => ({ draft: '' }),
+ },
+ ],
+ isTerminal: [false, { setStubTerminal: (_: boolean, { terminal }: any) => terminal }],
+ dataProcessingAccepted: [true, { setStubConsent: (_: boolean, { accepted }: any) => accepted }],
+ }),
+ ]),
+ }
+})
+
+jest.mock('scenes/projectLogic', () => {
+ const { kea, path, reducers } = jest.requireActual('kea')
+ return { projectLogic: kea([path(['test', 'projectLogicStub']), reducers({ currentProjectId: [997, {}] })]) }
+})
+
+jest.mock('lib/components/Support/supportLogic', () => {
+ const { kea, actions, path } = jest.requireActual('kea')
+ return {
+ supportLogic: kea([
+ path(['test', 'supportLogicStub']),
+ actions({ openSupportForm: (values: unknown) => values }),
+ ]),
+ }
+})
+
+jest.mock('products/tasks/frontend/generated/api', () => ({ tasksRunsCommandCreate: jest.fn() }))
+jest.mock('../utils/feedbackEvents', () => ({ captureCommandFeedback: jest.fn() }))
+jest.mock('lib/lemon-ui/LemonToast', () => ({ lemonToast: { error: jest.fn(), success: jest.fn() } }))
+
+describe('runSlashCommandsLogic', () => {
+ const logicProps: RunInteractionLogicProps = { taskId: 'task-1', runId: 'run-1', currentRuntimeAdapter: 'claude' }
+ let logic: ReturnType<typeof runSlashCommandsLogic.build>
+ let interaction: ReturnType<typeof runInteractionLogic.build>
+
+ const setDraft = (draft: string): void => (interaction.actions as any).setDraft(draft)
+ let releasePendingSideQuestion: (() => void) | null = null
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ interaction = runInteractionLogic(logicProps)
+ interaction.mount()
+ ;(runStreamLogic({ streamKey: 'run-1' }).actions as any).setStubCommands([
+ { name: 'compact', description: 'Compact the conversation' },
+ { name: 'init', description: 'Initialize a CLAUDE.md file' },
+ ])
+ logic = runSlashCommandsLogic(logicProps)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ releasePendingSideQuestion?.()
+ releasePendingSideQuestion = null
+ })
+
+ it.each([
+ ['an agent command', '/compact'],
+ ['a hidden harness built-in', '/init'],
+ ['plain text', 'what changed?'],
+ ])('sends %s to the agent', async (_label, draft) => {
+ setDraft(draft)
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ await expectLogic(interaction).toDispatchActions(['submitComposerForm'])
+ expect(interaction.values.composerForm.draft).toEqual(draft)
+ })
+
+ it('runs an app command in the browser and clears the draft', async () => {
+ setDraft('/good nice work')
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ await expectLogic(interaction).toNotHaveDispatchedActions(['submitComposerForm'])
+ expect(interaction.values.composerForm.draft).toEqual('')
+ expect(captureCommandFeedback).toHaveBeenCalledWith(
+ 'task-1',
+ 'trace-1',
+ 'good',
+ { taskId: 'task-1', runId: 'run-1' },
+ 'nice work'
+ )
+ })
+
+ it('keeps the draft and shows an error when a required argument is missing', async () => {
+ setDraft('/feedback')
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ expect(interaction.values.composerForm.draft).toEqual('/feedback')
+ expect(lemonToast.error).toHaveBeenCalled()
+ expect(captureCommandFeedback).not.toHaveBeenCalled()
+ await expectLogic(interaction).toNotHaveDispatchedActions(['submitComposerForm'])
+ })
+
+ it('asks a side question out of band and shows the answer', async () => {
+ ;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({
+ jsonrpc: '2.0',
+ result: { answer: 'It is a funnel.' },
+ })
+ setDraft('/btw what is this?')
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {
+ jsonrpc: '2.0',
+ method: 'side_question',
+ params: { question: 'what is this?' },
+ })
+ expect(logic.values.commandResult).toEqual({ title: 'what is this?', body: 'It is a funnel.' })
+ })
+
+ it.each([
+ ['a finished run', () => (interaction.actions as any).setStubTerminal(true)],
+ [
+ 'a side question already in flight',
+ () => {
+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ releasePendingSideQuestion = () => resolve({ jsonrpc: '2.0', result: { answer: 'first' } })
+ })
+ )
+ setDraft('/btw first question')
+ logic.actions.submitComposer()
+ },
+ ],
+ // Both rejections are synchronous, so the second submit is not awaited: the in-flight case
+ // only rejects while its own request is still pending.
+ ])('keeps the draft and refuses a side question on %s', async (_label, setUp) => {
+ setUp()
+ setDraft('/btw what is this?')
+
+ logic.actions.submitComposer()
+
+ expect(interaction.values.composerForm.draft).toEqual('/btw what is this?')
+ expect(lemonToast.error).toHaveBeenCalled()
+ await expectLogic(interaction).toNotHaveDispatchedActions(['submitComposerForm'])
+ })
+
+ it('asks for consent instead of sending a side question when AI data processing is not approved', async () => {
+ ;(interaction.actions as any).setStubConsent(false)
+ setDraft('/btw what is this?')
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ await expectLogic(interaction).toDispatchActions(['blockOnConsent'])
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(interaction.values.composerForm.draft).toEqual('/btw what is this?')
+ })
+
+ it('attributes a /ticket handover to the run', async () => {
+ setDraft('/ticket the diff looks wrong')
+
+ await expectLogic(logic, () => logic.actions.submitComposer()).toFinishAllListeners()
+
+ expect(interaction.values.composerForm.draft).toEqual('')
+ await expectLogic(supportLogic).toDispatchActions([
+ (action: any) =>
+ action.type === supportLogic.actionTypes.openSupportForm &&
+ action.payload.ai_conversation_id === 'task-1' &&
+ action.payload.ai_trace_id === 'trace-1',
+ ])
+ })
+
+ it('offers /btw only on a live Claude run', async () => {
+ expect(logic.values.slashCommands.map((c) => c.name)).toContain('btw')
+
+ await expectLogic(logic, () => (interaction.actions as any).setStubTerminal(true)).toFinishAllListeners()
+
+ expect(logic.values.slashCommands.map((c) => c.name)).not.toContain('btw')
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/runSlashCommandsLogic.ts b/products/posthog_ai/frontend/logics/runSlashCommandsLogic.ts
new file mode 100644
index 000000000000..2cb3223ac9b2
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/runSlashCommandsLogic.ts
@@ -0,0 +1,349 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import posthog from 'posthog-js'
+
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
+
+import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'
+import { RuntimeAdapterEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import type { ContextUsage } from '../types/streamTypes'
+import type { AgentCommand } from '../types/wireTypes'
+import { captureCommandFeedback } from '../utils/feedbackEvents'
+import {
+ APP_COMMANDS,
+ type AppCommand,
+ type AppCommandName,
+ type SlashCommand,
+ buildSlashCommands,
+ getAppCommand,
+ parseSlashCommand,
+} from '../utils/slashCommands'
+import { runInteractionLogic, type RunInteractionLogicProps } from './runInteractionLogic'
+import { runStreamLogic } from './runStreamLogic'
+
+/** The output of `/btw` or `/usage`, shown above the composer until dismissed. `body` is null while loading. */
+export interface CommandResult {
+ title: string
+ body: string | null
+}
+
+export function formatUsageSummary(usage: ContextUsage | null): string {
+ const lines: string[] = []
+ const tokens = usage?.tokens
+ if (typeof tokens?.inputTokens === 'number') {
+ lines.push(`- Input tokens: ${humanFriendlyNumber(tokens.inputTokens)}`)
+ }
+ if (typeof tokens?.outputTokens === 'number') {
+ lines.push(`- Output tokens: ${humanFriendlyNumber(tokens.outputTokens)}`)
+ }
+ if (typeof tokens?.cachedReadTokens === 'number') {
+ lines.push(`- Cached tokens read: ${humanFriendlyNumber(tokens.cachedReadTokens)}`)
+ }
+ if (typeof tokens?.cachedWriteTokens === 'number') {
+ lines.push(`- Cached tokens written: ${humanFriendlyNumber(tokens.cachedWriteTokens)}`)
+ }
+ if (typeof usage?.used === 'number' && typeof usage.size === 'number' && usage.size > 0) {
+ const percentage = Math.min(100, Math.round((usage.used / usage.size) * 100))
+ lines.push(
+ `- Context window: ${humanFriendlyNumber(usage.used)} of ${humanFriendlyNumber(usage.size)} tokens (${percentage}%)`
+ )
+ }
+ if (typeof usage?.cost === 'number') {
+ lines.push(`- Cost: $${usage.cost.toFixed(2)}`)
+ }
+ return lines.length > 0
+ ? lines.join('\n')
+ : "This run hasn't reported usage yet. Try again after the agent replies."
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runSlashCommandsLogicValues {
+ currentProjectId: number | null // projectLogic
+ composerForm: {
+ draft: string
+ } // runInteractionLogic
+ dataProcessingAccepted: boolean // runInteractionLogic
+ isTerminal: boolean // runInteractionLogic
+ availableCommands: AgentCommand[] // runStreamLogic
+ bootstrappedRunId: string | null // runStreamLogic
+ bootstrappedTaskId: string | null // runStreamLogic
+ contextUsage: ContextUsage | null // runStreamLogic
+ traceId: string | null // runStreamLogic
+ appCommands: AppCommand[]
+ commandResult: CommandResult | null
+ slashCommands: SlashCommand[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runSlashCommandsLogicActions {
+ blockOnConsent: (source?: 'draft' | 'queue' | 'steer' | undefined) => {
+ source: 'draft' | 'queue' | 'steer'
+ } // runInteractionLogic
+ resetComposerForm: (
+ values?:
+ | {
+ draft: string
+ }
+ | undefined
+ ) => {
+ values?: {
+ draft: string
+ }
+ } // runInteractionLogic
+ submitComposerForm: () => {
+ value: boolean
+ } // runInteractionLogic
+ openSupportForm: (
+ values: Partial<import('lib/components/Support/supportLogic').SupportFormFields> & {
+ target?: 'modal' | 'sidePanel'
+ }
+ ) => Partial<import('lib/components/Support/supportLogic').SupportFormFields> & {
+ target?: 'modal' | 'sidePanel' | undefined
+ } // supportLogic
+ askSideQuestion: (question: string) => {
+ question: string
+ }
+ dismissCommandResult: () => {
+ value: true
+ }
+ runAppCommand: (
+ name: AppCommandName,
+ args: string
+ ) => {
+ args: string
+ name: AppCommandName
+ }
+ setCommandResult: (result: CommandResult | null) => {
+ result: CommandResult | null
+ }
+ submitComposer: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface runSlashCommandsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ appCommands: (isTerminal: boolean, arg: string | null | undefined) => AppCommand[]
+ slashCommands: (appCommands: AppCommand[], availableCommands: AgentCommand[]) => SlashCommand[]
+ }
+}
+
+export type runSlashCommandsLogicType = MakeLogicType<
+ runSlashCommandsLogicValues,
+ runSlashCommandsLogicActions,
+ RunInteractionLogicProps,
+ runSlashCommandsLogicMeta
+>
+
+/**
+ * Slash commands for a run's composer. App commands (`/btw`, `/good`, `/bad`, `/feedback`, `/usage`,
+ * `/ticket`) run here and never reach the agent. Every other command goes to the agent as prompt text
+ * through `runInteractionLogic`, which already handles `/clear` on a finished run.
+ */
+export const runSlashCommandsLogic: LogicWrapper<runSlashCommandsLogicType> = kea<runSlashCommandsLogicType>([
+ props({} as RunInteractionLogicProps),
+ // Same key as `runInteractionLogic`, so the two share one lifetime.
+ key((props) => props.interactionKey ?? props.runId),
+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runSlashCommandsLogic', key]),
+ connect((props: RunInteractionLogicProps) => ({
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ runStreamLogic({ streamKey: props.streamKey ?? props.runId }),
+ ['availableCommands', 'bootstrappedRunId', 'bootstrappedTaskId', 'contextUsage', 'traceId'],
+ runInteractionLogic(props),
+ ['composerForm', 'isTerminal', 'dataProcessingAccepted'],
+ ],
+ actions: [
+ supportLogic,
+ ['openSupportForm'],
+ runInteractionLogic(props),
+ ['resetComposerForm', 'submitComposerForm', 'blockOnConsent'],
+ ],
+ })),
+ actions({
+ submitComposer: true,
+ runAppCommand: (name: AppCommandName, args: string) => ({ name, args }),
+ askSideQuestion: (question: string) => ({ question }),
+ setCommandResult: (result: CommandResult | null) => ({ result }),
+ dismissCommandResult: true,
+ }),
+ reducers({
+ commandResult: [
+ null as CommandResult | null,
+ {
+ setCommandResult: (_, { result }) => result,
+ dismissCommandResult: () => null,
+ },
+ ],
+ }),
+ selectors({
+ appCommands: [
+ (s) => [s.isTerminal, (_, props: RunInteractionLogicProps) => props.currentRuntimeAdapter],
+ (isTerminal: boolean, runtimeAdapter: string | null | undefined): AppCommand[] =>
+ APP_COMMANDS.filter(
+ // A side question needs a live Claude session: the Codex and Pi harnesses don't answer one.
+ (command) =>
+ command.name !== 'btw' || (!isTerminal && runtimeAdapter === RuntimeAdapterEnumApi.Claude)
+ ),
+ ],
+ slashCommands: [
+ (s) => [s.appCommands, s.availableCommands],
+ (appCommands: AppCommand[], availableCommands: AgentCommand[]): SlashCommand[] =>
+ buildSlashCommands(appCommands, availableCommands),
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => {
+ /** Where a side question would go, or why it cannot run yet. Checked before the draft is cleared. */
+ const resolveSideQuestionTarget = ():
+ | { projectId: string; taskId: string; runId: string }
+ | { error: string } => {
+ if (cache.sideQuestionRequest) {
+ return { error: 'Wait for your last side question to finish first' }
+ }
+ const { bootstrappedRunId: runId, bootstrappedTaskId: taskId, currentProjectId } = values
+ if (!runId || !taskId || currentProjectId === null) {
+ return { error: 'Wait for the agent to start, then ask again' }
+ }
+ return { projectId: String(currentProjectId), taskId, runId }
+ }
+
+ return {
+ submitComposer: () => {
+ const parsed = parseSlashCommand(values.composerForm.draft)
+ const command = parsed ? values.slashCommands.find((c) => c.name === parsed.name) : undefined
+ if (parsed && command) {
+ // pinned: analytics event name — renaming breaks dashboards
+ posthog.capture('posthog_ai_slash_command_used', {
+ command: command.name,
+ command_source: command.source,
+ agent_runtime: 'sandbox',
+ })
+ }
+ const typedAppCommand = parsed ? getAppCommand(parsed.name) : undefined
+ if (typedAppCommand && !command) {
+ // The menu hides an app command this run cannot run, but nothing stops someone typing it.
+ // Passing it on would put the text in the transcript, or start a new run to answer it.
+ lemonToast.error(
+ typedAppCommand.unavailableError ?? `/${typedAppCommand.name} is not available here`
+ )
+ return
+ }
+ const appCommand = command?.source === 'app' ? typedAppCommand : undefined
+ if (!parsed || !appCommand) {
+ actions.submitComposerForm()
+ return
+ }
+ if (appCommand.requiredInputError && !parsed.args) {
+ lemonToast.error(appCommand.requiredInputError)
+ return
+ }
+ if (appCommand.name === 'btw') {
+ // A side question reaches the model, so it takes the same consent gate as an ordinary send.
+ if (!values.dataProcessingAccepted) {
+ actions.blockOnConsent()
+ return
+ }
+ // Checked here as well as in the listener, so a rejected question keeps the typed draft.
+ const target = resolveSideQuestionTarget()
+ if ('error' in target) {
+ lemonToast.error(target.error)
+ return
+ }
+ }
+ actions.runAppCommand(appCommand.name, parsed.args)
+ actions.resetComposerForm()
+ },
+ runAppCommand: ({ name, args }) => {
+ const taskId = values.bootstrappedTaskId ?? props.taskId
+ const run = { taskId, runId: values.bootstrappedRunId ?? props.runId }
+ switch (name) {
+ case 'good':
+ case 'bad':
+ case 'feedback':
+ captureCommandFeedback(taskId, values.traceId, name === 'feedback' ? null : name, run, args)
+ lemonToast.success('Thanks for the feedback')
+ return
+ case 'usage':
+ actions.setCommandResult({
+ title: 'Usage for this run',
+ body: formatUsageSummary(values.contextUsage),
+ })
+ return
+ case 'ticket': {
+ const taskUrl = taskId ? urls.absolute(urls.currentProject(urls.taskDetail(taskId))) : null
+ actions.openSupportForm({
+ kind: 'support',
+ target: 'sidePanel',
+ isEmailFormOpen: true,
+ message: [args, taskUrl ? `PostHog AI task: ${taskUrl}` : null]
+ .filter(Boolean)
+ .join('\n\n'),
+ // Attributes the ticket to this run, like the other PostHog AI ticket handovers.
+ ai_conversation_id: taskId ?? null,
+ ai_trace_id: values.traceId,
+ })
+ return
+ }
+ case 'btw':
+ actions.askSideQuestion(args)
+ return
+ }
+ },
+ askSideQuestion: async ({ question }) => {
+ const target = resolveSideQuestionTarget()
+ if ('error' in target) {
+ lemonToast.error(target.error)
+ return
+ }
+ const request = (cache.sideQuestionRequest = {})
+ actions.setCommandResult({ title: question, body: null })
+ const disposables = cache.disposables
+ try {
+ const response = await tasksRunsCommandCreate(target.projectId, target.taskId, target.runId, {
+ jsonrpc: '2.0',
+ method: 'side_question',
+ params: { question },
+ })
+ const answer = (response.result as { answer?: unknown } | undefined)?.answer
+ if (response.error || typeof answer !== 'string' || !answer) {
+ throw new Error('Side question produced no answer')
+ }
+ if (!disposables.isDisposed && values.commandResult?.title === question) {
+ actions.setCommandResult({ title: question, body: answer })
+ }
+ } catch (error) {
+ if (!disposables.isDisposed) {
+ if (values.commandResult?.title === question && values.commandResult.body === null) {
+ actions.dismissCommandResult()
+ }
+ lemonToast.error("Couldn't answer your side question. Try again.")
+ posthog.captureException(error)
+ }
+ } finally {
+ if (cache.sideQuestionRequest === request) {
+ cache.sideQuestionRequest = undefined
+ }
+ }
+ },
+ }
+ }),
+])
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 289cfb904031..7b69ffb8f732 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -449,6 +449,29 @@ describe('runStreamLogic', () => {
expect(logic.values.currentMode).toEqual('plan')
})
+ it('replaces availableCommands on each available_commands_update frame', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'available_commands_update',
+ availableCommands: [
+ { name: 'compact', description: 'Compact the conversation', input: null },
+ { name: 'querying-posthog-data', description: 'Query data', input: { hint: 'question' } },
+ { description: 'no name, dropped' },
+ ],
+ })
+ )
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'available_commands_update',
+ availableCommands: [{ name: '/clear', description: 'Clear history' }],
+ })
+ )
+ }).toFinishAllListeners()
+
+ expect(logic.values.availableCommands).toEqual([{ name: 'clear', description: 'Clear history' }])
+ })
+
it('sets currentProgress on a _posthog/progress frame and clears it on turn complete', async () => {
await expectLogic(logic, () => {
logic.actions.ingestAcpFrame(notification('_posthog/progress', { label: 'Querying events' }))
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index a8706c2ab9ac..5f295b84f743 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -54,6 +54,7 @@ import {
type PermissionRequestFrame,
type PosthogPermissionRequestParams,
type PosthogProgressParams,
+ type AgentCommand,
type PosthogUsageUpdateParams,
type SessionUpdateUsage,
type SseErrorFrameData,
@@ -62,10 +63,12 @@ import {
isNotificationFrame,
isPermissionRequestFrame,
isPosthogNotification,
+ isSessionUpdateAvailableCommands,
isSessionUpdateNotification,
isSessionUpdateUsage,
isSessionUpdateUserMessage,
isTaskRunStateFrame,
+ parseAvailableCommands,
} from '../types/wireTypes'
import { extractContextBlockLines } from '../utils/posthogContextBlock'
import { extractAgentToolName, getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'
@@ -1885,6 +1888,7 @@ export interface runStreamLogicValues {
currentProjectId: number | null // projectLogic
toolListeners: Record<string, ToolStreamSubscription> // toolStreamEventsLogic
user: UserType | null // userLogic
+ availableCommands: AgentCommand[]
awaitingOptimisticAttach: boolean
bootstrapError: StreamErrorEnvelope | null
bootstrapLoading: boolean
@@ -2140,6 +2144,9 @@ export interface runStreamLogicActions {
record: PermissionRequestRecord
replayedFromHistory: boolean
}
+ setAvailableCommands: (commands: AgentCommand[]) => {
+ commands: AgentCommand[]
+ }
setContextUsage: (usage: ContextUsage) => {
usage: ContextUsage
}
@@ -2473,6 +2480,8 @@ export const runStreamLogic = kea<runStreamLogicType>([
mergeRunArtifacts: (partial: Partial<RunArtifacts>) => ({ partial }),
/** Latest-wins context-usage snapshot fold (token/cost/breakdown or numeric aggregate). */
setContextUsage: (usage: ContextUsage) => ({ usage }),
+ /** Latest-wins agent slash-command list from `available_commands_update`. */
+ setAvailableCommands: (commands: AgentCommand[]) => ({ commands }),
/** Diagnostic `_posthog/sdk_session` plumbing — no UI. */
setSdkSession: (session: SdkSession) => ({ session }),
reset: true,
@@ -2839,6 +2848,14 @@ export const runStreamLogic = kea<runStreamLogicType>([
reset: () => null,
},
],
+ // Kept across a resume: the successor run re-advertises its list, and until then the old one holds.
+ availableCommands: [
+ [] as AgentCommand[],
+ {
+ setAvailableCommands: (_, { commands }) => commands,
+ reset: () => [],
+ },
+ ],
// Diagnostic resume plumbing — adapter/session identity for telemetry. No UI.
sdkSession: [
null as SdkSession | null,
@@ -4409,6 +4426,10 @@ export const runStreamLogic = kea<runStreamLogicType>([
}
return
}
+ if (isSessionUpdateAvailableCommands(update)) {
+ actions.setAvailableCommands(parseAvailableCommands(update.availableCommands))
+ return
+ }
if (!isKnownSessionUpdate(update)) {
return
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index 2cbc53522632..94013c0b2d61 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -10,11 +10,14 @@ import { userLogic } from 'scenes/userLogic'
import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'
import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
+import { runSlashCommandsLogic } from 'products/posthog_ai/frontend/logics/runSlashCommandsLogic'
import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
import { getRuntimeAdapterForModel, pickerModels } from 'products/posthog_ai/frontend/utils/composerModels'
import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
+import { CommandResultCard } from '../../../components/composer/CommandResultCard'
+import { ComposerCommandMenu } from '../../../components/composer/ComposerCommandMenu'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
@@ -44,11 +47,14 @@ export function TaskRunComposer({
defaultModel,
selectedEffort,
consentBlocked,
+ consentBlockedSource,
selectedMode,
composerActive,
steerPending,
cancellationState,
} = useValues(runInteractionLogic(logicProps))
+ const { slashCommands, commandResult } = useValues(runSlashCommandsLogic(logicProps))
+ const { submitComposer, dismissCommandResult } = useActions(runSlashCommandsLogic(logicProps))
const { catalogue } = useValues(modelCatalogueLogic)
const offeredModels = useMemo(() => pickerModels(catalogue, selectedModel), [catalogue, selectedModel])
const { user } = useValues(userLogic)
@@ -61,7 +67,6 @@ export function TaskRunComposer({
setComposerFormValues,
enableTaskDraftPersistence,
setComposerFocused,
- submitComposerForm,
requestCancellation,
updateQueuedMessage,
removeQueuedMessage,
@@ -96,7 +101,7 @@ export function TaskRunComposer({
onChange={draft.onChange}
onSubmit={() =>
draft.submit(() => {
- submitComposerForm()
+ submitComposer()
return runInteractionLogic(logicProps).values.composerForm.draft
})
}
@@ -105,6 +110,15 @@ export function TaskRunComposer({
isTurnActive={isBusy}
onStop={requestCancellation}
>
+ {commandResult && (
+ <Composer.Banner>
+ <CommandResultCard
+ title={commandResult.title}
+ body={commandResult.body}
+ onDismiss={dismissCommandResult}
+ />
+ </Composer.Banner>
+ )}
{draftRecovery && composerForm.draft && (
<Composer.Banner>
<p className="text-xs text-muted px-2 mb-2" data-attr="task-draft-restored">
@@ -130,12 +144,16 @@ export function TaskRunComposer({
<Composer.Header>
<AttachedContextBar />
</Composer.Header>
- <Composer.Field>
- <Composer.Placeholder>
- {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
- </Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
- </Composer.Field>
+ <ComposerCommandMenu commands={slashCommands}>
+ <Composer.Field>
+ <Composer.Placeholder>
+ {isTerminal
+ ? 'Send a message to start a new run, or type / for commands…'
+ : 'Send a follow-up message, or type / for commands…'}
+ </Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
+ </Composer.Field>
+ </ComposerCommandMenu>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
<fieldset
disabled={!controlsReady}
@@ -177,7 +195,16 @@ export function TaskRunComposer({
showArrow
ignoreDismissal
hidden={!consentBlocked}
- onApprove={submitAfterConsent}
+ // A draft may be a slash command, so it resubmits through the command path rather than
+ // straight to the agent. Queue and steer have no command form and go back as they were.
+ onApprove={() => {
+ if (consentBlockedSource === 'draft') {
+ clearConsentBlock()
+ submitComposer()
+ } else {
+ submitAfterConsent()
+ }
+ }}
onDismiss={() => clearConsentBlock()}
>
<Composer.Submit data-attr="sandbox-composer-send" />
diff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.ts
index 0adc39ee8bae..a5ce824b3b83 100644
--- a/products/posthog_ai/frontend/types/wireTypes.ts
+++ b/products/posthog_ai/frontend/types/wireTypes.ts
@@ -313,6 +313,42 @@ export function isSessionUpdateUsage(update: unknown): update is SessionUpdateUs
return isRecord(update) && update.sessionUpdate === 'usage_update'
}
+/** The agent's full slash-command list. Each frame replaces the previous list. */
+export interface SessionUpdateAvailableCommands {
+ sessionUpdate: 'available_commands_update'
+ availableCommands?: unknown
+}
+
+export function isSessionUpdateAvailableCommands(update: unknown): update is SessionUpdateAvailableCommands {
+ return isRecord(update) && update.sessionUpdate === 'available_commands_update'
+}
+
+/** An agent-advertised command, guarded down from the loosely-typed ACP `AvailableCommand`. */
+export interface AgentCommand {
+ name: string
+ description: string
+ hint?: string
+}
+
+export function parseAvailableCommands(raw: unknown): AgentCommand[] {
+ if (!Array.isArray(raw)) {
+ return []
+ }
+ return raw.flatMap((command): AgentCommand[] => {
+ if (!isRecord(command) || typeof command.name !== 'string' || !command.name) {
+ return []
+ }
+ const hint = isRecord(command.input) && typeof command.input.hint === 'string' ? command.input.hint : undefined
+ return [
+ {
+ name: command.name.replace(/^\//, ''),
+ description: typeof command.description === 'string' ? command.description : '',
+ ...(hint ? { hint } : {}),
+ },
+ ]
+ })
+}
+
/**
* The user's own turn, echoed back by the agent adapter and persisted to the run log as a
* `session/update` (not a `_posthog/*` ext-notification). Carries the full prompt text in a single
diff --git a/products/posthog_ai/frontend/utils/feedbackEvents.ts b/products/posthog_ai/frontend/utils/feedbackEvents.ts
index a4d5379843aa..b7846a6312ad 100644
--- a/products/posthog_ai/frontend/utils/feedbackEvents.ts
+++ b/products/posthog_ai/frontend/utils/feedbackEvents.ts
@@ -46,6 +46,33 @@ export function captureTurnFeedbackText(
})
}
+/** Feedback typed as a `/good`, `/bad`, or `/feedback` command. A rating without text is valid, and so is text without a rating. */
+export function captureCommandFeedback(
+ sessionId: string,
+ traceId: string | null,
+ rating: 'good' | 'bad' | null,
+ run: RunRef,
+ feedbackText?: string
+): void {
+ if (rating) {
+ posthog.capture('$ai_metric', {
+ $ai_metric_name: 'feedback',
+ $ai_metric_value: rating,
+ feedback_trigger_type: 'slash_command',
+ turn_index: null,
+ ...feedbackContext(sessionId, traceId, run),
+ })
+ }
+ if (feedbackText) {
+ posthog.capture('$ai_feedback', {
+ $ai_feedback_text: feedbackText,
+ feedback_trigger_type: 'slash_command',
+ turn_index: null,
+ ...feedbackContext(sessionId, traceId, run),
+ })
+ }
+}
+
export type FeedbackPromptRating = 'bad' | 'okay' | 'good' | 'dismissed' | 'implicit_dismiss'
export type FeedbackPromptTrigger = 'message_interval' | 'random_sample' | 'manual' | 'cancel'
diff --git a/products/posthog_ai/frontend/utils/slashCommands.test.ts b/products/posthog_ai/frontend/utils/slashCommands.test.ts
new file mode 100644
index 000000000000..ca27172cf964
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/slashCommands.test.ts
@@ -0,0 +1,44 @@
+import { APP_COMMANDS, buildSlashCommands, filterSlashCommands, parseSlashCommand } from './slashCommands'
+
+describe('slashCommands', () => {
+ const agentCommands = [
+ { name: 'clear', description: 'Clear conversation history' },
+ { name: 'compact', description: 'Compact the conversation' },
+ { name: 'init', description: 'Initialize a CLAUDE.md file' },
+ { name: 'security-review', description: 'Review the branch' },
+ { name: 'mcp:posthog:query', description: 'MCP prompt' },
+ { name: 'usage', description: 'Show plan usage limits' },
+ { name: 'querying-posthog-data', description: 'Query PostHog data', hint: 'question' },
+ ]
+
+ it('keeps clear, compact, and skills from the agent, and hides harness built-ins', () => {
+ const commands = buildSlashCommands(APP_COMMANDS, agentCommands)
+ const agentNames = commands.filter((c) => c.source === 'agent').map((c) => c.name)
+
+ expect(agentNames).toEqual(['clear', 'compact', 'querying-posthog-data'])
+ // The app /usage wins over the agent's /usage, and appears once.
+ expect(commands.filter((c) => c.name === 'usage')).toEqual([expect.objectContaining({ source: 'app' })])
+ })
+
+ it.each([
+ ['/', 'all commands', ['btw', 'good', 'bad', 'feedback', 'usage', 'ticket', 'clear', 'compact']],
+ ['/co', 'name-prefix matches before description matches', ['compact', 'btw', 'usage', 'clear']],
+ ['/COM', 'case-insensitive', ['compact']],
+ ['/compact ', 'nothing once arguments start', []],
+ ['hello /compact', 'nothing when the draft does not start with a slash', []],
+ ])('filters %j to %s', (draft, _label, expected) => {
+ const commands = buildSlashCommands(APP_COMMANDS, agentCommands.slice(0, 2))
+
+ expect(filterSlashCommands(commands, draft).map((c) => c.name)).toEqual(expected)
+ })
+
+ it.each([
+ ['/btw what is this?', { name: 'btw', args: 'what is this?' }],
+ [' /usage ', { name: 'usage', args: '' }],
+ ['/feedback line one\nline two', { name: 'feedback', args: 'line one\nline two' }],
+ ['what does /btw do', null],
+ ['/', null],
+ ])('parses %j', (text, expected) => {
+ expect(parseSlashCommand(text)).toEqual(expected)
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/slashCommands.ts b/products/posthog_ai/frontend/utils/slashCommands.ts
new file mode 100644
index 000000000000..d1eeb37b56bb
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/slashCommands.ts
@@ -0,0 +1,149 @@
+import type { AgentCommand } from '../types/wireTypes'
+
+export type AppCommandName = 'btw' | 'good' | 'bad' | 'feedback' | 'usage' | 'ticket'
+
+export interface SlashCommand {
+ /** Without the leading slash. */
+ name: string
+ description: string
+ hint?: string
+ /** `app` commands run in the browser; `agent` commands go to the agent as prompt text. */
+ source: 'app' | 'agent'
+}
+
+export interface AppCommand extends SlashCommand {
+ name: AppCommandName
+ source: 'app'
+ /** Set when the command needs text after its name. The value is the error shown when it is missing. */
+ requiredInputError?: string
+ /** Shown when the command is typed on a run that does not offer it. */
+ unavailableError?: string
+}
+
+export const APP_COMMANDS: AppCommand[] = [
+ {
+ name: 'btw',
+ description: 'Ask a quick side question without interrupting the conversation',
+ hint: 'your question',
+ source: 'app',
+ requiredInputError: 'Add a question after /btw',
+ unavailableError: 'Side questions only work while a Claude run is live',
+ },
+ { name: 'good', description: 'Send positive feedback', hint: 'optional comment', source: 'app' },
+ { name: 'bad', description: 'Send negative feedback', hint: 'optional comment', source: 'app' },
+ {
+ name: 'feedback',
+ description: 'Send feedback about PostHog AI',
+ hint: 'your feedback',
+ source: 'app',
+ requiredInputError: 'Add your feedback after /feedback. To rate without a comment, use /good or /bad.',
+ },
+ { name: 'usage', description: 'Show token usage and cost for this run', source: 'app' },
+ { name: 'ticket', description: 'Open a support ticket about this task', source: 'app' },
+]
+
+const APP_COMMANDS_BY_NAME: ReadonlyMap<string, AppCommand> = new Map(APP_COMMANDS.map((c) => [c.name, c]))
+
+export function getAppCommand(name: string): AppCommand | undefined {
+ return APP_COMMANDS_BY_NAME.get(name)
+}
+
+// The agent advertises its harness built-ins next to skills, with no field that tells them apart. These
+// built-ins act on a local terminal or repo, or duplicate an app command, so they are hidden by name.
+// Everything else the agent advertises (skills) stays visible, as do `clear` and `compact`.
+const HIDDEN_AGENT_COMMANDS: ReadonlySet<string> = new Set([
+ 'add-dir',
+ 'agents',
+ 'batch',
+ 'bug',
+ 'claude-api',
+ 'config',
+ 'context',
+ 'cost',
+ 'debug',
+ 'doctor',
+ 'export',
+ 'extra-usage',
+ 'fewer-permission-prompts',
+ 'goal',
+ 'heapdump',
+ 'help',
+ 'hooks',
+ 'ide',
+ 'init',
+ 'insights',
+ 'install-github-app',
+ 'keybindings-help',
+ 'login',
+ 'logout',
+ 'loop',
+ 'mcp',
+ 'memory',
+ 'model',
+ 'output-style:new',
+ 'permissions',
+ 'plugin',
+ 'pr-comments',
+ 'privacy-settings',
+ 'release-notes',
+ 'resume',
+ 'review',
+ 'rewind',
+ 'sandbox',
+ 'schedule',
+ 'security-review',
+ 'simplify',
+ 'status',
+ 'statusline',
+ 'terminal-setup',
+ 'todos',
+ 'update-config',
+ 'upgrade',
+ 'vim',
+])
+
+export function isVisibleAgentCommand(name: string): boolean {
+ return !HIDDEN_AGENT_COMMANDS.has(name) && !name.startsWith('mcp:')
+}
+
+/** App commands first, then the visible agent commands. An app command wins a name clash. */
+export function buildSlashCommands(appCommands: AppCommand[], agentCommands: AgentCommand[]): SlashCommand[] {
+ const names = new Set<string>(appCommands.map((c) => c.name))
+ const visibleAgentCommands: SlashCommand[] = []
+ for (const command of agentCommands) {
+ if (names.has(command.name) || !isVisibleAgentCommand(command.name)) {
+ continue
+ }
+ names.add(command.name)
+ visibleAgentCommands.push({ ...command, source: 'agent' })
+ }
+ return [...appCommands, ...visibleAgentCommands]
+}
+
+/**
+ * The commands to suggest for a draft. Suggests only while the draft is a lone `/name` token, so the menu
+ * closes once the user types a space to add arguments. Name-prefix matches rank first.
+ */
+export function filterSlashCommands(commands: SlashCommand[], draft: string): SlashCommand[] {
+ const match = /^\/(\S*)$/.exec(draft)
+ if (!match) {
+ return []
+ }
+ const query = match[1].toLowerCase()
+ const prefix: SlashCommand[] = []
+ const contains: SlashCommand[] = []
+ for (const command of commands) {
+ const name = command.name.toLowerCase()
+ if (name.startsWith(query)) {
+ prefix.push(command)
+ } else if (name.includes(query) || command.description.toLowerCase().includes(query)) {
+ contains.push(command)
+ }
+ }
+ return [...prefix, ...contains]
+}
+
+export function parseSlashCommand(text: string): { name: string; args: string } | null {
+ const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text.trim())
+ return match ? { name: match[1], args: (match[2] ?? '').trim() } : null
+}