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(phai): center task composer with footer repo pickers (#66694)

Georgiy Tarasovc750f7ab7940
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 29c6d09a587f..32e18015ef86 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6749,37 +6749,41 @@ snapshots:
scenes-app-surveys-surveyresponsekeysreference--webhook--light:
hash: v1.k794b7964.9b5c484a3a1bd7a09c266a1f164e3ed9eef3ffabbcd12253f0843b3f0b69a808.cc6Rai2vShlFJA_KypMbVcc1IIaVX0nTcZ29RPEEZjo
scenes-app-tasks--empty--dark:
- hash: v1.k794b7964.2a229a3f53490cc99b64a15121f858f85ee90be46ce4c8264ed9ad1a0fd2fd88.w9qFySaTmjgYwFxL10ckNfEHq1-F9ZuJbzLn-wtE9Ag
+ hash: v1.k794b7964.5a2e42d1db05b06fc4edde0d4c24a490c6418631d43dd0682dae547c9012fba7.xr5po4ts7Wb5Y5rhbyS7vPugr-2ZzqQv2iT8o3WGdjY
scenes-app-tasks--empty--light:
- hash: v1.k794b7964.26738f6d7f71991a943cb09851df2e75ba06e297db673178542b54d143d446b2.Al9AsDXcTSwZjXBKJa1DQFB9hodBSgVGFbFCsoZAYas
+ hash: v1.k794b7964.786f433b10400c1dc9bfa5f03841a0c23d88ccf5fcf525bfac0cafcfd5ddd4c4.nvBTgjIgLtzs1hQ5CeUZFp8UFKU2yvFFC2wznJzy9Wg
scenes-app-tasks--list-load-error--dark:
- hash: v1.k794b7964.d4c5ccf7f63724f0add4de82ec33eb7bb01df963666920af61d6699e3b709155.hdfAIjYpVUPW-72JAMt-60gOKVyqQBvnLnz4SNIAkl0
+ hash: v1.k794b7964.01e46f97e23683d5a837592b89ff471253b1f41be94c91f576db9fa1a15e3e96.97CjMV_GLbssX7rpQSRk7OiSlxxhEMtnW2t9P0BjCFY
scenes-app-tasks--list-load-error--light:
- hash: v1.k794b7964.b5cad08684e6c9bbae28221cd49e4c90b759821314638988f8031ad132a07964.8vDj1yR82QM88WRq78IUHodUMAYB74Ic2-spmA-neZY
+ hash: v1.k794b7964.5c97840343ddc57ed9790d06429e49bec394203b670b8ddb357ea0c9ab687ca1.jANgN9fNGxjm0d2yL0dGxkm5XieTZFJtlv0SExDe8Jk
scenes-app-tasks--list-with-composer--dark:
- hash: v1.k794b7964.16c59902a774acd3799d2f1e33b365f6950445d060eb0c333bd1727c87784663.2Rdgn90Q9bAlOZbR0J-Tkj0xEBC5CQDAj5pLgbjGMqo
+ hash: v1.k794b7964.5d77f4e365629fa30c360641e5019ac0c388ae5add14e7a754708c1faac591ec._UmVLAcn3OC66Y6ZxrtETpqL65LV9k_NMhVyORql5-8
scenes-app-tasks--list-with-composer--light:
- hash: v1.k794b7964.537a4a32d45e825b4e70af09861da3ff8544e48b6537081ae77692fe3d427d52.5FLb9BmdvoEzENBWY8hb5o0htemfLsUVgdcfWHrD5Yc
+ hash: v1.k794b7964.0ab6f6ec637c9b48f6a2b5899bdf75b58810f096efa6d28efec44db57b9c5afb.rzut9E9Spy55ouA5sZHoYdZbmZQbem86lVD_74zSNgw
scenes-app-tasks--loading--dark:
- hash: v1.k794b7964.dd70956f52ca13614528b72cc7f564a4cbf44034df75dc80faee0451b97aa88d.Q6CBG7oYAO_mE1n0nSRxGWuazxzUtLXnLHC55zls8_U
+ hash: v1.k794b7964.e4b9f0063a06f336ff946e6fdb294368a0c409ce2d0ab3e2a7b6912bb9e7c0ad.d9oTg4w0QmPgzecqF5DD2PtNaM3giKamhRohjbG_PmE
scenes-app-tasks--loading--light:
- hash: v1.k794b7964.e7e9c42f73ffcafe77e8afd6113b31f1a237ddadfe22fe873dd3688909f1da61.Y7Mr50uPW0-Kx5HPq8M872WEc5qlJzPz6rQ35su7F20
+ hash: v1.k794b7964.d63a062123b8430135c57972207eb2fd436cb3c368b324b0682e16c61dcd557d.uIyuu6myMDNxHw5Mp1FYBmU0MfZDxaA9o84NZnllpnU
scenes-app-tasks--mobile-list--dark:
hash: v1.k794b7964.8b8954327495955b38c9d7cb370d629a455427020afa88d02bb245aa0c0179b8.INO40pNr6q1c-n7E0o__E3IxQLCkNMXAWWYHJiwYleY
scenes-app-tasks--mobile-list--light:
hash: v1.k794b7964.d037ad8f6622654e28ff3a9d072c5a6eafdda8f5c647860a89557bcbe3c779f0.YJudQaFNTmR90w12ID3HRugQSz8-AernL6qG01j-doQ
scenes-app-tasks--mobile-new-task--dark:
- hash: v1.k794b7964.94c3479bf0e00dc38972551e04e81ea755a13e4679b81f935f1ff12c501e95ae.GExTQnD2Sx1EQlmYDqHNccqQfyYRW-aYBkH9B3AbwjU
+ hash: v1.k794b7964.de22e10e282dd787afc1fc4784d1aef6064b32b7c3bed6b3bced8ba776264cf2.UCqKfpWcRlmvwmvML2DjdyVQCwj3zUZpXlKA8wxMgVs
scenes-app-tasks--mobile-new-task--light:
- hash: v1.k794b7964.c28ab66e9201b84fb893ff6d661d5af159afb5dc69d646dcf12e55c80ee5f6fd.FB3N3ZfQFFAz8Z5g6aUXzHSx47UrNWDuNrz41kFBns0
+ hash: v1.k794b7964.cf669044c3c0e2b6d870e588a22f58be3032bec6d90a2c1c3b1ee1412a491661.3mNJ_P0G8pSfhi3oEkjsTKKG7wVSFB9jdY7ujjDXj7k
scenes-app-tasks--mobile-task-selected--dark:
hash: v1.k794b7964.45c56cdba57d4cdfcca851cc2ad88c08831fe0cbab19863b86a028705d7b52a8.BwQ4BP5IbXOFCimc4-sLUVE54-zEA9naxwb7q7EWR58
scenes-app-tasks--mobile-task-selected--light:
hash: v1.k794b7964.fcba0f8e9e7360da3c671debfff263fc22467c9820e5706207523add08e29d99.Nr7dbzdN-8LSM4JvLEOty1cjbb4zz4XFhGfJp9pH8iQ
scenes-app-tasks--new-task--dark:
- hash: v1.k794b7964.16c59902a774acd3799d2f1e33b365f6950445d060eb0c333bd1727c87784663.lE9tbirpfGIJfkIw5H4dXX9fncaqnaM-qcD1J3x8Yv4
+ hash: v1.k794b7964.5d77f4e365629fa30c360641e5019ac0c388ae5add14e7a754708c1faac591ec.zSqbzjD11FX5bzEnJpf-edSj6hd2I8vg7EqjkpmXR-Q
scenes-app-tasks--new-task--light:
- hash: v1.k794b7964.3674cdd577b0a22f9459dfd9e7c6e98c36a7bf3b9a68e8e7508ac6a0366708d7.QZSXTiTa56QfQlAsFFRfl5KniKwm0rvJdkIvjwliLmM
+ hash: v1.k794b7964.0ab6f6ec637c9b48f6a2b5899bdf75b58810f096efa6d28efec44db57b9c5afb.SpqpdgzYL7ZiBufdHwTsZWSSeysHdi8aMR8EoFGbHw0
+ scenes-app-tasks--new-task-with-repository--dark:
+ hash: v1.k794b7964.618c5e54d814e8cc472e6769050aac33678862e01ae77317738836240dbed3e1.SnsTmytzBSx3-Ak__uCvwF4U7rgrlFXCAOyqk9KS4lM
+ scenes-app-tasks--new-task-with-repository--light:
+ hash: v1.k794b7964.5894011b70910a77a35a242427678221e97171b6d0a78216d6520ad87e292719.D9fI3-Ed65sDNH0UiY9uGO8aR4YIBBS-CQ3DZacxy-M
scenes-app-tasks--task-detail-loading--dark:
hash: v1.k794b7964.d3643f39c3ebd6c0b4da18ee269b86373be7f8f07c65bf895e6527e69330f872.BWj6tyeJtfgZdzKGw_Yu7Kh3NPd88r3CtTORgjWowq4
scenes-app-tasks--task-detail-loading--light:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 0cc0df8a84dd..8cfba1e5a31c 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -253,7 +253,10 @@ import type {
SessionGroupSummaryType,
SessionSummariesConfig,
} from 'products/session_summaries/frontend/types'
-import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+import type {
+ ClaudeTaskRunCreateSchemaApi,
+ TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,
+} from 'products/tasks/frontend/generated/api.schemas'
import type { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'
import type { OptOutEntry } from 'products/workflows/frontend/OptOuts/types'
import type { MessageTemplate } from 'products/workflows/frontend/TemplateLibrary/types'
@@ -5318,7 +5321,7 @@ const api = {
async bulkReorder(columns: Record<string, string[]>): Promise<{ updated: number; tasks: Task[] }> {
return await new ApiRequest().tasks().withAction('bulk_reorder').create({ data: { columns } })
},
- async run(id: Task['id'], data?: { branch?: string | null }): Promise<Task> {
+ async run(id: Task['id'], data?: ClaudeTaskRunCreateSchemaApi): Promise<Task> {
return await new ApiRequest()
.task(id)
.withAction('run')
diff --git a/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx b/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx
index 8fd1d1d8f59e..5f6586d78ba4 100644
--- a/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx
+++ b/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx
@@ -26,6 +26,8 @@ export interface GitHubRepositoryComboboxProps {
onChange: (value: string | null) => void
disabled?: boolean
placeholder?: string
+ /** When true, prepends a "— No repository —" item so users can explicitly clear the selection. */
+ showNoneOption?: boolean
}
/**
@@ -34,12 +36,15 @@ export interface GitHubRepositoryComboboxProps {
* refresh control. Searching and pagination are delegated to {@link githubRepositorySearchLogic} so large
* accounts never load the full repository list up front.
*/
+const NONE_SENTINEL = '\x00none'
+
export function GitHubRepositoryCombobox({
integrationId,
value,
onChange,
disabled = false,
placeholder = 'Select repository...',
+ showNoneOption = false,
}: GitHubRepositoryComboboxProps): JSX.Element {
const logic = githubRepositorySearchLogic({ id: integrationId })
const { repositoryNames, loading, hasMore, searchQuery, error } = useValues(logic)
@@ -73,13 +78,15 @@ export function GitHubRepositoryCombobox({
)
}
+ const items = showNoneOption ? [NONE_SENTINEL, ...repositoryNames] : repositoryNames
+
return (
<Combobox
- items={repositoryNames}
+ items={items}
// Server-side search already filtered the list; don't let the combobox re-filter by input value.
filter={null}
value={value || null}
- onValueChange={(next: string | null) => onChange(next ? next : null)}
+ onValueChange={(next: string | null) => onChange(next === NONE_SENTINEL ? null : next || null)}
open={open}
onOpenChange={(nextOpen: boolean) => {
setOpen(nextOpen)
@@ -136,11 +143,17 @@ export function GitHubRepositoryCombobox({
{showInlineLoadingState ? 'Loading repositories...' : error ? error : 'No repositories found.'}
</ComboboxEmpty>
<ComboboxList>
- {(repo: string) => (
- <ComboboxItem key={repo} value={repo}>
- {repo}
- </ComboboxItem>
- )}
+ {(repo: string) =>
+ repo === NONE_SENTINEL ? (
+ <ComboboxItem key={repo} value={repo}>
+ No repository
+ </ComboboxItem>
+ ) : (
+ <ComboboxItem key={repo} value={repo}>
+ {repo}
+ </ComboboxItem>
+ )
+ }
</ComboboxList>
{hasMore && (
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index b8fa75a2f092..adaa311805a9 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -874,7 +874,7 @@ export const QUESTION_SUGGESTIONS_DATA: readonly SuggestionGroup[] = [
content: 'Create a survey to collect NPS responses from users',
},
{
- content: 'Create a survey to CSAT responses from users',
+ content: 'Create a survey to collect CSAT responses from users',
},
{
content: 'Create a survey to measure product market fit',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c503630be626..7e59bd23e075 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3773,6 +3773,9 @@ importers:
'@posthog/icons':
specifier: 'catalog:'
+ '@posthog/quill-primitives':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/primitives
'@storybook/react':
specifier: 'catalog:'
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index 18320494768c..8b232142f979 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -19,6 +19,22 @@ export type {
ComposerSubmitProps,
} from '../components/composer/Composer'
+// Welcome header (logomark + headline + subheadline) and its overridable default headlines.
+export { Welcome } from '../components/welcome/Welcome'
+export type { WelcomeProps } from '../components/welcome/Welcome'
+export { DEFAULT_HEADLINES, pickHeadline } from '../components/welcome/welcomeDefaults'
+
+// Suggestions compound (the "Try PostHog AI for…" button row + in-input dropdown) and its default content.
+export { Suggestions } from '../components/suggestions/Suggestions'
+export type {
+ SuggestionItem,
+ SuggestionGroup,
+ SuggestionsRootProps,
+ SuggestionsButtonsProps,
+ SuggestionsDropdownProps,
+} from '../components/suggestions/Suggestions'
+export { DEFAULT_SUGGESTIONS_DATA } from '../components/suggestions/suggestionsDefaults'
+
// `Thread` is the Radix-style compound (Root + Message/Markdown/Reasoning/Failure/Activity/ToolCall
// atoms); `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).
export { Thread } from '../components/Thread'
diff --git a/products/posthog_ai/frontend/components/ContextUsageBar.tsx b/products/posthog_ai/frontend/components/ContextUsageBar.tsx
index 12644d095449..0d32bb14333c 100644
--- a/products/posthog_ai/frontend/components/ContextUsageBar.tsx
+++ b/products/posthog_ai/frontend/components/ContextUsageBar.tsx
@@ -51,7 +51,7 @@ export function ContextUsageBar(): JSX.Element | null {
}
return (
- <div className="flex items-center gap-2 px-3 py-1 text-xs text-muted" data-attr="max-sandbox-context-usage">
+ <div className="flex items-center gap-2 px-2 text-xs text-muted" data-attr="max-sandbox-context-usage">
{hasRing && (
<Tooltip title="Context window usage">
<span className="flex items-center gap-1.5">
diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsx
index 36727c9a0d0a..6ca5633e9446 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx
@@ -4,6 +4,7 @@ import {
type HTMLAttributes,
type ReactNode,
type RefObject,
+ useCallback,
useContext,
useId,
useMemo,
@@ -70,7 +71,7 @@ export interface ComposerRootProps {
children: ReactNode
}
-const ComposerRoot = forwardRef<HTMLDivElement, ComposerRootProps>(function ComposerRoot(
+const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function ComposerRoot(
{
value,
onChange,
@@ -95,6 +96,16 @@ const ComposerRoot = forwardRef<HTMLDivElement, ComposerRootProps>(function Comp
const sendDisabledReason = !value.trim() ? 'Type a message first' : loading ? 'Sending…' : disabledReason
+ // Focuses the textarea when blocked, otherwise submits — shared by the native form submit and the
+ // textarea keyboard shortcuts.
+ const submit = useCallback(() => {
+ if (sendDisabledReason) {
+ textAreaRef.current?.focus()
+ return
+ }
+ onSubmit()
+ }, [sendDisabledReason, textAreaRef, onSubmit])
+
const ctx = useMemo<ComposerContextValue>(
() => ({
value,
@@ -102,30 +113,30 @@ const ComposerRoot = forwardRef<HTMLDivElement, ComposerRootProps>(function Comp
loading,
disabled,
sendDisabledReason,
- submit: () => {
- if (sendDisabledReason) {
- textAreaRef.current?.focus()
- return
- }
- onSubmit()
- },
+ submit,
textAreaRef,
id,
isThreadVisible,
}),
- [value, onChange, loading, disabled, sendDisabledReason, onSubmit, textAreaRef, id, isThreadVisible]
+ [value, onChange, loading, disabled, sendDisabledReason, submit, textAreaRef, id, isThreadVisible]
)
- // The relative wrapper is the positioning context for the absolutely-placed Submit + Placeholder.
+ // The relative wrapper is the positioning context for the absolutely-placed Submit + Placeholder. It's a
+ // real <form> so the send button is a native submit and Enter/Cmd+Enter route through `onSubmit`. The
+ // forwarded ref always points to this form, regardless of chrome mode.
const hasChrome = isSticky || isThreadVisible || !!containerClassName
const positioned = (
- <div
+ <form
data-slot="composer-root"
className={cn('relative w-full flex flex-col', hasChrome ? 'z-1' : className)}
- ref={hasChrome ? undefined : ref}
+ ref={ref}
+ onSubmit={(e) => {
+ e.preventDefault()
+ submit()
+ }}
>
{children}
- </div>
+ </form>
)
return (
@@ -137,7 +148,6 @@ const ComposerRoot = forwardRef<HTMLDivElement, ComposerRootProps>(function Comp
(isSticky || isThreadVisible) && 'sticky bottom-0 z-10 max-w-180 self-center',
containerClassName
)}
- ref={ref}
>
<div
className={cn(
@@ -298,7 +308,7 @@ export interface ComposerSubmitProps {
/** The absolutely-positioned send cluster, sibling of Frame inside Root's relative wrapper. */
function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitProps): JSX.Element {
- const { sendDisabledReason, loading, submit, isThreadVisible } = useComposerContext()
+ const { sendDisabledReason, loading, isThreadVisible } = useComposerContext()
return (
<div
data-slot="composer-submit"
@@ -311,8 +321,8 @@ function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitPro
<LemonButton
type="primary"
size="small"
+ htmlType="submit"
icon={icon ?? <IconArrowRight />}
- onClick={() => submit()}
loading={loading}
disabledReason={sendDisabledReason}
tooltip={sendDisabledReason ? undefined : (tooltip ?? "Let's go!")}
diff --git a/products/posthog_ai/frontend/components/suggestions/Suggestions.scss b/products/posthog_ai/frontend/components/suggestions/Suggestions.scss
new file mode 100644
index 000000000000..cef101436940
--- /dev/null
+++ b/products/posthog_ai/frontend/components/suggestions/Suggestions.scss
@@ -0,0 +1,30 @@
+.Suggestions__list {
+ opacity: 0;
+ transition:
+ opacity 150ms ease-out,
+ transform 150ms ease-out;
+ transform: scale(0.95) translateY(-0.5rem);
+
+ &--visible {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+
+.Suggestions__item {
+ opacity: 0;
+ animation: Suggestions__item__slide-in-fade-down 60ms ease-out forwards;
+ animation-delay: calc(var(--index) * 25ms);
+}
+
+@keyframes Suggestions__item__slide-in-fade-down {
+ from {
+ opacity: 0;
+ transform: translateY(-0.5rem);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
diff --git a/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx b/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx
new file mode 100644
index 000000000000..f97ffb37fc80
--- /dev/null
+++ b/products/posthog_ai/frontend/components/suggestions/Suggestions.tsx
@@ -0,0 +1,232 @@
+import './Suggestions.scss'
+
+import { createContext, type ReactNode, useContext, useEffect, useRef } from 'react'
+
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+import { useAnimatedPresence } from 'lib/hooks/useAnimatedPresence'
+import { useOutsideClickHandler } from 'lib/hooks/useOutsideClickHandler'
+import { cn } from 'lib/utils/css-classes'
+
+// Radix-style compound suggestions surface: a logic-free button row ("Try PostHog AI for…") plus an
+// in-input dropdown that opens when a multi-suggestion category is picked. Reproduces the look of
+// scenes/max's FloatingSuggestionsDisplay + SuggestionsList without any conversation logic — the caller owns
+// the open state and decides what a chosen suggestion does (fill, submit, navigate). The dropdown attaches
+// to the bottom edge of whatever positioned ancestor it's placed in (e.g. inside <Composer.Root>).
+
+export interface SuggestionItem {
+ content: string
+ /** When true the caller should fill the input and let the user finish typing; otherwise submit directly. */
+ requiresUserInput?: boolean
+}
+
+export interface SuggestionGroup {
+ label: string
+ icon: JSX.Element
+ suggestions: SuggestionItem[]
+ /** Optional product page to open when the group is clicked (handled by the caller's `onNavigate`). */
+ url?: string
+ tooltip?: string
+}
+
+interface SuggestionsContextValue {
+ activeGroup: SuggestionGroup | null
+ handleGroupClick: (group: SuggestionGroup) => void
+ handleSelect: (item: SuggestionItem) => void
+ disabled: boolean
+ disabledReason?: string | null
+}
+
+const SuggestionsContext = createContext<SuggestionsContextValue | null>(null)
+
+function useSuggestionsContext(): SuggestionsContextValue {
+ const ctx = useContext(SuggestionsContext)
+ if (!ctx) {
+ throw new Error('Suggestions.* components must be rendered inside <Suggestions.Root>')
+ }
+ return ctx
+}
+
+export interface SuggestionsRootProps {
+ /** Controlled open-dropdown state; `null` when no category is expanded. The caller owns it. */
+ activeGroup: SuggestionGroup | null
+ onActiveGroupChange: (group: SuggestionGroup | null) => void
+ /** Called when a concrete suggestion is chosen — from the dropdown or a single-suggestion group. */
+ onSelectSuggestion: (item: SuggestionItem) => void
+ /** Called (before the open/select logic) for groups carrying a `url`, e.g. to open the product page. */
+ onNavigate?: (url: string) => void
+ disabled?: boolean
+ disabledReason?: string | null
+ children: ReactNode
+}
+
+function SuggestionsRoot({
+ activeGroup,
+ onActiveGroupChange,
+ onSelectSuggestion,
+ onNavigate,
+ disabled = false,
+ disabledReason,
+ children,
+}: SuggestionsRootProps): JSX.Element {
+ const handleGroupClick = (group: SuggestionGroup): void => {
+ if (group.url) {
+ onNavigate?.(group.url)
+ }
+ // ≤1 suggestion: nothing to expand, apply it straight away. Otherwise open the dropdown.
+ if (group.suggestions.length <= 1) {
+ if (group.suggestions[0]) {
+ onSelectSuggestion(group.suggestions[0])
+ }
+ } else {
+ onActiveGroupChange(group)
+ }
+ }
+
+ const handleSelect = (item: SuggestionItem): void => {
+ onSelectSuggestion(item)
+ onActiveGroupChange(null)
+ }
+
+ // The dropdown dismisses on Esc or a click anywhere outside the suggestions subtree. The `contents`
+ // wrapper is layout-transparent (it doesn't establish a box or positioning context, so the flex layout
+ // and the dropdown's absolute positioning are unchanged) but gives `useOutsideClickHandler` one node that
+ // spans every slot — so clicking another category button to switch groups doesn't count as "outside".
+ const rootRef = useRef<HTMLDivElement | null>(null)
+ useOutsideClickHandler([rootRef], () => {
+ if (activeGroup) {
+ onActiveGroupChange(null)
+ }
+ })
+
+ useEffect(() => {
+ if (!activeGroup) {
+ return
+ }
+ const handleKeyDown = (event: KeyboardEvent): void => {
+ if (event.key === 'Escape') {
+ onActiveGroupChange(null)
+ }
+ }
+ document.addEventListener('keydown', handleKeyDown)
+ return () => document.removeEventListener('keydown', handleKeyDown)
+ }, [activeGroup, onActiveGroupChange])
+
+ return (
+ <SuggestionsContext.Provider value={{ activeGroup, handleGroupClick, handleSelect, disabled, disabledReason }}>
+ <div ref={rootRef} className="contents">
+ {children}
+ </div>
+ </SuggestionsContext.Provider>
+ )
+}
+
+export interface SuggestionsButtonsProps {
+ data: readonly SuggestionGroup[]
+ /** The label above the row. Defaults to the PostHog AI prompt; pass `null` to hide it. */
+ tip?: ReactNode
+ type?: 'primary' | 'secondary' | 'tertiary'
+ /** Extra buttons appended after the category buttons (e.g. a settings affordance). */
+ additionalSuggestions?: ReactNode[]
+ className?: string
+}
+
+function SuggestionsButtons({
+ data,
+ tip = 'Try PostHog AI for…',
+ type = 'secondary',
+ additionalSuggestions,
+ className,
+}: SuggestionsButtonsProps): JSX.Element {
+ const { activeGroup, handleGroupClick, disabled, disabledReason } = useSuggestionsContext()
+
+ return (
+ <div className={cn('flex flex-col items-center justify-center gap-y-2', className)}>
+ {tip && <h3 className="text-center text-xs font-medium mb-0 text-secondary">{tip}</h3>}
+ <Tooltip title={disabled ? disabledReason || undefined : undefined}>
+ <ul
+ className={cn(
+ 'flex items-center justify-center flex-wrap gap-1.5 mb-0',
+ activeGroup && 'fade-out pointer-events-none'
+ )}
+ >
+ {data.map((group) => (
+ <li key={group.label}>
+ <LemonButton
+ onClick={() => handleGroupClick(group)}
+ size="xsmall"
+ type={type}
+ icon={group.icon}
+ tooltip={disabled ? undefined : group.tooltip}
+ disabled={disabled}
+ >
+ {group.label}
+ </LemonButton>
+ </li>
+ ))}
+ {additionalSuggestions?.map((node, index) => (
+ <li key={index}>{node}</li>
+ ))}
+ </ul>
+ </Tooltip>
+ </div>
+ )
+}
+
+export interface SuggestionsDropdownProps {
+ className?: string
+}
+
+function SuggestionsDropdown({ className }: SuggestionsDropdownProps): JSX.Element | null {
+ const { activeGroup, handleSelect } = useSuggestionsContext()
+ const containerRef = useRef<HTMLDivElement | null>(null)
+ // Keep the last group around so its items stay rendered through the exit animation.
+ const previousGroup = useRef<SuggestionGroup | null>(null)
+ const { rendered, shown } = useAnimatedPresence(!!activeGroup, 150)
+
+ useEffect(() => {
+ if (activeGroup && containerRef.current) {
+ // Move focus into the dropdown so keyboard users can act on it immediately.
+ containerRef.current.querySelector<HTMLElement>('button')?.focus()
+ }
+ previousGroup.current = activeGroup
+ }, [activeGroup, rendered])
+
+ const group = activeGroup || previousGroup.current
+
+ if (!rendered) {
+ return null
+ }
+
+ return (
+ <div
+ ref={containerRef}
+ role="listbox"
+ className={cn(
+ 'Suggestions__list absolute inset-x-2 top-full grid auto-rows-auto p-1 border-x border-b rounded-b-lg bg-surface-primary z-10',
+ shown && 'Suggestions__list--visible',
+ className
+ )}
+ >
+ {group?.suggestions.map((suggestion, index) => (
+ <LemonButton
+ key={suggestion.content}
+ className="Suggestions__item text-left"
+ style={{ '--index': index } as React.CSSProperties}
+ size="small"
+ type="tertiary"
+ fullWidth
+ onClick={() => handleSelect(suggestion)}
+ >
+ <span className="font-normal">{suggestion.content}</span>
+ </LemonButton>
+ ))}
+ </div>
+ )
+}
+
+export const Suggestions = Object.assign(SuggestionsRoot, {
+ Root: SuggestionsRoot,
+ Buttons: SuggestionsButtons,
+ Dropdown: SuggestionsDropdown,
+})
diff --git a/products/posthog_ai/frontend/components/suggestions/suggestionsDefaults.tsx b/products/posthog_ai/frontend/components/suggestions/suggestionsDefaults.tsx
new file mode 100644
index 000000000000..ffb6ef1ee2e8
--- /dev/null
+++ b/products/posthog_ai/frontend/components/suggestions/suggestionsDefaults.tsx
@@ -0,0 +1,200 @@
+import { IconBook, IconCode } from '@posthog/icons'
+
+import { urls } from 'scenes/urls'
+
+import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { productUrls } from '~/products'
+
+import { type SuggestionGroup } from './Suggestions'
+
+// Default, overridable suggestion content for the Suggestions primitive. The "Coding" group leads (this
+// surface drives an agent that writes code), followed by PostHog's analytics categories. Pass your own
+// array to override.
+export const DEFAULT_SUGGESTIONS_DATA: readonly SuggestionGroup[] = [
+ {
+ label: 'Coding',
+ icon: <IconCode />,
+ suggestions: [
+ {
+ content: 'Instrument an event/property',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Fix a bug for me',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Research how my codebase works',
+ },
+ ],
+ tooltip: 'PostHog AI can write code in your repository — instrument events, fix bugs, and explore code.',
+ },
+ {
+ label: 'Product analytics',
+ icon: iconForType('product_analytics'),
+ suggestions: [
+ {
+ content: 'Create a funnel of the Pirate Metrics (AARRR)',
+ },
+ {
+ content: 'What are the most popular pages or screens?',
+ },
+ {
+ content: 'What is the retention in the last two weeks?',
+ },
+ {
+ content: 'What are the top referring domains?',
+ },
+ {
+ content: 'Calculate a conversion rate for <events or actions>…',
+ requiresUserInput: true,
+ },
+ ],
+ tooltip: 'PostHog AI can generate insights from natural language and tweak existing ones.',
+ },
+ {
+ label: 'SQL',
+ icon: iconForType('insight/hog'),
+ suggestions: [
+ {
+ content: 'Write an SQL query to…',
+ requiresUserInput: true,
+ },
+ ],
+ url: urls.sqlEditor(),
+ tooltip: 'PostHog AI can generate SQL queries for your PostHog data, both analytics and the data warehouse.',
+ },
+ {
+ label: 'Session replay',
+ icon: iconForType('session_replay'),
+ suggestions: [
+ {
+ content: 'Find recordings for…',
+ requiresUserInput: true,
+ },
+ ],
+ url: productUrls.replay(),
+ tooltip: 'PostHog AI can find session recordings for you.',
+ },
+ {
+ label: 'SDK setup',
+ icon: iconForType('sql_editor'),
+ suggestions: [
+ {
+ content: 'How can I set up the session replay in <a framework or language>…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up the feature flags in…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up the experiments in…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up the data warehouse in…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up the error tracking in…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up AI observability in…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'How can I set up the product analytics in…',
+ requiresUserInput: true,
+ },
+ ],
+ tooltip: 'PostHog AI can help you set up PostHog SDKs in your stack.',
+ },
+ {
+ label: 'Feature flags',
+ icon: iconForType('feature_flag'),
+ url: urls.featureFlags(),
+ suggestions: [
+ {
+ content: 'Create a flag to gradually roll out…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Create a flag that starts at 10% rollout for…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Create a multivariate flag for…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Create a beta testing flag for…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Audit my feature flags for issues',
+ },
+ ],
+ },
+ {
+ label: 'Experiments',
+ icon: iconForType('experiment'),
+ url: urls.experiments(),
+ suggestions: [
+ {
+ content: 'Create an experiment to test…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Set up an A/B test with a 70/30 split between control and test for…',
+ requiresUserInput: true,
+ },
+ {
+ content: 'Check if my running experiments are set up correctly',
+ },
+ ],
+ },
+ {
+ label: 'Surveys',
+ icon: iconForType('survey'),
+ suggestions: [
+ {
+ content: 'Create a survey to collect NPS responses from users',
+ },
+ {
+ content: 'Create a survey to collect CSAT responses from users',
+ },
+ {
+ content: 'Create a survey to measure product market fit',
+ },
+ {
+ content: 'Analyze survey responses to prioritize key features our users are interested in',
+ },
+ ],
+ url: urls.surveys(),
+ tooltip: 'PostHog AI can help you create surveys to collect feedback from your users.',
+ },
+ {
+ label: 'Docs',
+ icon: <IconBook />,
+ suggestions: [
+ {
+ content: 'How can I create a feature flag?',
+ },
+ {
+ content: 'Where do I watch session replays?',
+ },
+ {
+ content: 'Help me set up an experiment',
+ },
+ {
+ content: 'Explain autocapture',
+ },
+ {
+ content: 'How can I capture an exception?',
+ },
+ ],
+ tooltip: 'PostHog AI has access to PostHog docs and can help you get the most out of PostHog.',
+ },
+]
diff --git a/products/posthog_ai/frontend/components/welcome/Welcome.tsx b/products/posthog_ai/frontend/components/welcome/Welcome.tsx
new file mode 100644
index 000000000000..cea55c6692ae
--- /dev/null
+++ b/products/posthog_ai/frontend/components/welcome/Welcome.tsx
@@ -0,0 +1,32 @@
+import { type ReactNode } from 'react'
+
+import { JumpingLogomark } from 'lib/brand/JumpingLogomark'
+
+// Logic-free welcome header: the jumping logomark, a headline, and a subheadline. Mirrors the look of
+// scenes/max/Intro.tsx without its conversation coupling — the caller passes the (already-chosen) headline
+// and may append extras (notices, changelog) via `children`.
+
+export interface WelcomeProps {
+ headline: string
+ /** Defaults to the PostHog AI tagline; pass `null` to hide it entirely. */
+ subheadline?: string | null
+ /** Rendered after the header — e.g. a liability notice or changelog the consumer owns. */
+ children?: ReactNode
+}
+
+export function Welcome({
+ headline,
+ subheadline = 'Build something people want.',
+ children,
+}: WelcomeProps): JSX.Element {
+ return (
+ <>
+ <JumpingLogomark className="flex *:h-full *:w-12 p-2" />
+ <div className="text-center mb-1">
+ <h2 className="text-xl @2xl/main-content:text-2xl font-bold mb-2 text-balance">{headline}</h2>
+ {subheadline && <div className="text-sm italic text-tertiary text-pretty py-0.5">{subheadline}</div>}
+ </div>
+ {children}
+ </>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/welcome/welcomeDefaults.ts b/products/posthog_ai/frontend/components/welcome/welcomeDefaults.ts
new file mode 100644
index 000000000000..fb348e2b8f57
--- /dev/null
+++ b/products/posthog_ai/frontend/components/welcome/welcomeDefaults.ts
@@ -0,0 +1,25 @@
+// Default, overridable content for the Welcome primitive. Shipped here so both consumers (the tasks
+// composer and the new PostHog AI welcome) share one source; pass your own list to override.
+
+export const DEFAULT_HEADLINES: readonly string[] = [
+ 'How can I help you build?',
+ 'What are you curious about?',
+ 'How can I help you understand users?',
+ 'What do you want to know today?',
+]
+
+/**
+ * Pick a headline from `headlines`. Forces the first one under Storybook so visual snapshots stay stable;
+ * with a `seed` it's deterministic, otherwise it rotates at random. Call once and hold the result (e.g. in a
+ * logic reducer) — calling it on every render would reshuffle the headline.
+ */
+export function pickHeadline(headlines: readonly string[] = DEFAULT_HEADLINES, seed?: number): string {
+ if (headlines.length === 0) {
+ return ''
+ }
+ if (process.env.STORYBOOK) {
+ return headlines[0]
+ }
+ const index = seed !== undefined ? seed % headlines.length : Math.floor(Math.random() * headlines.length)
+ return headlines[index]
+}
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index 59c765f1b8fb..feb958954567 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -99,6 +99,13 @@ describe('runInteractionLogic', () => {
{ jsonrpc: '2.0', method: 'user_message', params: { content } },
]
+ const setConfigCommand = (configId: string, value: string): [string, string, string, Record<string, unknown>] => [
+ '997',
+ TASK_ID,
+ RUN_ID,
+ { jsonrpc: '2.0', method: 'set_config_option', params: { configId, value } },
+ ]
+
beforeEach(() => {
jest.clearAllMocks()
;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({})
@@ -120,37 +127,76 @@ describe('runInteractionLogic', () => {
it('sends immediately and echoes the message when the agent is idle', async () => {
setThinking(false)
- logic.actions.setDraft('ship it')
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))
await expectLogic(stream).toDispatchActions(['pushHumanMessage'])
- expect(logic.values.draft).toBe('')
+ expect(logic.values.composerForm.draft).toBe('')
expect(logic.values.queuedMessages).toEqual([])
})
+ it('does not send any command when the model or effort is picked', async () => {
+ setThinking(false)
+ logic.actions.setModel('claude-sonnet-4-6')
+ logic.actions.setEffort('low')
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ // Picking is client-side only now — nothing is synced until the message is sent.
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.selectedModel).toBe('claude-sonnet-4-6')
+ expect(logic.values.selectedEffort).toBe('low')
+ })
+
+ it('syncs a changed model to the agent right before the message, and only when it changed', async () => {
+ setThinking(false)
+ logic.actions.setModel('claude-sonnet-4-6')
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitComposerForm()
+ }).toFinishAllListeners()
+
+ // The config sync lands before the message, never inside it.
+ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([
+ setConfigCommand('model', 'claude-sonnet-4-6'),
+ userMessageCommand('ship it'),
+ ])
+
+ // A follow-up with the same selection re-syncs nothing — just the message.
+ ;(tasksRunsCommandCreate as jest.Mock).mockClear()
+ logic.actions.setComposerFormValues({ draft: 'again' })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitComposerForm()
+ }).toFinishAllListeners()
+
+ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('again')])
+ })
+
it('stages the message in the queue while the agent is busy', async () => {
setThinking(true)
- logic.actions.setDraft('follow up')
+ logic.actions.setComposerFormValues({ draft: 'follow up' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
- expect(logic.values.draft).toBe('')
+ expect(logic.values.composerForm.draft).toBe('')
expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])
})
it('concatenates follow-ups into a single staged message and flushes it when the turn completes', async () => {
setThinking(true)
- logic.actions.setDraft('first')
- logic.actions.submit()
- logic.actions.setDraft('second')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'first' })
+ logic.actions.submitComposerForm()
+ logic.actions.setComposerFormValues({ draft: 'second' })
+ logic.actions.submitComposerForm()
// A second follow-up concatenates onto the first rather than fanning out into a separate message.
expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'first\n\nsecond' }])
@@ -167,8 +213,8 @@ describe('runInteractionLogic', () => {
it('edits and removes staged messages', async () => {
setThinking(true)
- logic.actions.setDraft('typo')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'typo' })
+ logic.actions.submitComposerForm()
const { id } = logic.values.queuedMessages[0]
logic.actions.updateQueuedMessage(id, 'fixed')
@@ -181,48 +227,51 @@ describe('runInteractionLogic', () => {
it('keeps the draft and toasts when the send fails', async () => {
;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('boom'))
setThinking(false)
- logic.actions.setDraft('ship it')
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
expect(lemonToast.error).toHaveBeenCalled()
- expect(logic.values.draft).toBe('ship it')
+ expect(logic.values.composerForm.draft).toBe('ship it')
expect(logic.values.sending).toBe(false)
})
it('starts a fresh run seeded with the message when the run is terminal', async () => {
setStatus('completed')
- logic.actions.setDraft('continue from here')
+ logic.actions.setComposerFormValues({ draft: 'continue from here' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
// No live-run signal for a finished run — it resumes into a new run instead.
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
expect(tasksRunCreate).toHaveBeenCalledWith('997', TASK_ID, {
+ runtime_adapter: 'claude',
+ model: 'claude-opus-4-8',
+ reasoning_effort: 'high',
resume_from_run_id: RUN_ID,
pending_user_message: 'continue from here',
})
expect(onRunStarted).toHaveBeenCalledWith('run-2')
expect(logic.values.queuedMessages).toEqual([])
- expect(logic.values.draft).toBe('')
+ expect(logic.values.composerForm.draft).toBe('')
})
it('keeps the draft and toasts when starting a new run fails', async () => {
;(tasksRunCreate as jest.Mock).mockRejectedValue(new Error('boom'))
setStatus('completed')
- logic.actions.setDraft('continue from here')
+ logic.actions.setComposerFormValues({ draft: 'continue from here' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
expect(lemonToast.error).toHaveBeenCalled()
expect(onRunStarted).not.toHaveBeenCalled()
- expect(logic.values.draft).toBe('continue from here')
+ expect(logic.values.composerForm.draft).toBe('continue from here')
})
const setProjectId = (id: number | null): void =>
@@ -231,30 +280,30 @@ describe('runInteractionLogic', () => {
it('no-ops and keeps the draft when submitting idle without a current project', async () => {
setProjectId(null)
setThinking(false)
- logic.actions.setDraft('ship it')
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
// Nothing can be sent without a project — the draft is preserved rather than dropped.
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
- expect(logic.values.draft).toBe('ship it')
+ expect(logic.values.composerForm.draft).toBe('ship it')
expect(logic.values.queuedMessages).toEqual([])
})
it('stages the message while busy without a current project and never silently sends it', async () => {
setProjectId(null)
setThinking(true)
- logic.actions.setDraft('follow up')
+ logic.actions.setComposerFormValues({ draft: 'follow up' })
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
// Busy + no project: the message is staged, and the guarded flush keeps it there rather than POSTing.
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
- expect(logic.values.draft).toBe('')
+ expect(logic.values.composerForm.draft).toBe('')
expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])
})
@@ -268,13 +317,13 @@ describe('runInteractionLogic', () => {
// Idle send straight from the draft: the draft is cleared up-front, before the await.
setThinking(false)
- logic.actions.setDraft('ship it')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
+ logic.actions.submitComposerForm()
expect(logic.values.sending).toBe(true)
- expect(logic.values.draft).toBe('')
+ expect(logic.values.composerForm.draft).toBe('')
// The user keeps typing while the send is in flight.
- logic.actions.setDraft('next thought')
+ logic.actions.setComposerFormValues({ draft: 'next thought' })
await expectLogic(logic, () => {
resolveSend()
@@ -282,7 +331,7 @@ describe('runInteractionLogic', () => {
// Success leaves the composer alone — the newly typed text survives rather than being wiped.
expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))
- expect(logic.values.draft).toBe('next thought')
+ expect(logic.values.composerForm.draft).toBe('next thought')
})
it('restores a failed draft send ahead of text typed during the send, preserving order', async () => {
@@ -294,11 +343,11 @@ describe('runInteractionLogic', () => {
)
setThinking(false)
- logic.actions.setDraft('ship it')
- logic.actions.submit()
- expect(logic.values.draft).toBe('')
+ logic.actions.setComposerFormValues({ draft: 'ship it' })
+ logic.actions.submitComposerForm()
+ expect(logic.values.composerForm.draft).toBe('')
- logic.actions.setDraft('next thought')
+ logic.actions.setComposerFormValues({ draft: 'next thought' })
await expectLogic(logic, () => {
rejectSend()
@@ -306,7 +355,7 @@ describe('runInteractionLogic', () => {
// The failed send puts the original back in front of what was typed since, so nothing is lost.
expect(lemonToast.error).toHaveBeenCalled()
- expect(logic.values.draft).toBe('ship it\n\nnext thought')
+ expect(logic.values.composerForm.draft).toBe('ship it\n\nnext thought')
})
it('keeps a follow-up typed during an in-flight queue flush instead of clearing it with the send', async () => {
@@ -319,8 +368,8 @@ describe('runInteractionLogic', () => {
// Stage a message while busy, then complete the turn to start flushing it.
setThinking(true)
- logic.actions.setDraft('first')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'first' })
+ logic.actions.submitComposerForm()
setThinking(false)
stream.actions.markTurnComplete()
@@ -328,8 +377,8 @@ describe('runInteractionLogic', () => {
expect(logic.values.sending).toBe(true)
expect(logic.values.queuedMessages).toEqual([])
- logic.actions.setDraft('second')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'second' })
+ logic.actions.submitComposerForm()
expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'second' }])
await expectLogic(logic, () => {
@@ -351,16 +400,16 @@ describe('runInteractionLogic', () => {
)
setThinking(true)
- logic.actions.setDraft('first')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'first' })
+ logic.actions.submitComposerForm()
setThinking(false)
stream.actions.markTurnComplete()
expect(logic.values.queuedMessages).toEqual([])
// A follow-up staged while the flush is in flight.
- logic.actions.setDraft('second')
- logic.actions.submit()
+ logic.actions.setComposerFormValues({ draft: 'second' })
+ logic.actions.submitComposerForm()
await expectLogic(logic, () => {
rejectSend()
@@ -373,7 +422,7 @@ describe('runInteractionLogic', () => {
it('no-ops on submit with an empty draft', async () => {
await expectLogic(logic, () => {
- logic.actions.submit()
+ logic.actions.submitComposerForm()
}).toFinishAllListeners()
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 097381e8f3bd..7fbc99e27219 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -1,10 +1,20 @@
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { forms } from 'kea-forms'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
+import {
+ DEFAULT_COMPOSER_EFFORT,
+ DEFAULT_COMPOSER_MODEL,
+ resolveEffortForModel,
+} from 'products/posthog_ai/frontend/utils/composerModels'
import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'
-import type { TaskRunResumeRequestSchemaApi } from 'products/tasks/frontend/generated/api.schemas'
+import {
+ ClaudeRuntimeAdapterEnumApi,
+ type ClaudeTaskRunCreateSchemaApi,
+ type ReasoningEffortEnumApi,
+} from 'products/tasks/frontend/generated/api.schemas'
import type { runInteractionLogicType } from './runInteractionLogicType'
import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
@@ -12,6 +22,10 @@ import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
export interface RunInteractionLogicProps {
taskId: string
runId: string
+ /** The run's stored model / reasoning effort, injected by the consumer. They seed the picker's display and
+ * the config a terminal-run send launches the next run with (override ?? this ?? default). */
+ currentModel?: string | null
+ currentEffort?: string | null
/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can
* re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */
onRunStarted?: (runId: string) => void
@@ -26,6 +40,11 @@ export interface QueuedMessage {
/** Stable id for the single staged "Up next" message — the queue never holds more than one. */
const QUEUED_MESSAGE_ID = 'queued'
+// Agent-server (ACP) session config option ids — see the `/code` agent's buildConfigOptions. The model
+// option's id is `model`; the effort option's id is `effort` (its category is `thought_level`).
+const MODEL_CONFIG_ID = 'model'
+const EFFORT_CONFIG_ID = 'effort'
+
/**
* Max-agnostic interaction facade for a single task run. The UI binds to this one logic to drive every
* user → run interaction — sending follow-ups, staging an editable "Up next" message while the agent is
@@ -58,10 +77,6 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
})),
actions({
- setDraft: (draft: string) => ({ draft }),
- clearDraft: true,
- // Single entry point the composer's `onSubmit` calls — decides send-now vs enqueue vs new-run.
- submit: true,
setSending: (sending: boolean) => ({ sending }),
// Start a fresh run on the task, seeded with this message and chained from the finished run.
startNewRun: (content: string) => ({ content }),
@@ -79,16 +94,18 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
clearQueue: true,
// Internal: drain the staged "Up next" message when the agent is idle.
flushQueue: true,
+ // Pick the model / reasoning effort for the next message. Selection is held client-side only and
+ // synced to the running agent (via `set_config_option`) at send time — not on each pick. The backend
+ // doesn't persist live changes back to the run state, so the override is the source of truth.
+ setModel: (model: string) => ({ model }),
+ setEffort: (effort: string) => ({ effort }),
+ // Internal: record the model / effort last synced to the agent session, so a send only fires a
+ // `set_config_option` when the pick actually differs from what the session is already running.
+ setSentModel: (model: string) => ({ model }),
+ setSentEffort: (effort: string) => ({ effort }),
}),
reducers({
- draft: [
- '',
- {
- setDraft: (_, { draft }) => draft,
- clearDraft: () => '',
- },
- ],
sending: [
false,
{
@@ -121,10 +138,85 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
clearQueue: () => [],
},
],
+ // Optimistic, client-side only — null means "use the run's stored model/effort". The logic is keyed by
+ // `runId`, so switching runs gets a fresh instance with the override reset.
+ modelOverride: [
+ null as string | null,
+ {
+ setModel: (_, { model }) => model,
+ },
+ ],
+ effortOverride: [
+ null as string | null,
+ {
+ setEffort: (_, { effort }) => effort,
+ },
+ ],
+ // The model/effort last synced to the agent session via `set_config_option`. null means "not synced
+ // yet this session" — the active config is then the run's stored value (or the default).
+ sentModel: [
+ null as string | null,
+ {
+ setSentModel: (_, { model }) => model,
+ },
+ ],
+ sentEffort: [
+ null as string | null,
+ {
+ setSentEffort: (_, { effort }) => effort,
+ },
+ ],
}),
+ forms(({ actions, values }) => ({
+ // The composer draft lives here so the input region is a real <form>. `submit` is the single entry
+ // point the composer's `onSubmit` calls — it decides send-now vs enqueue vs new-run. It dispatches
+ // synchronously (no await), so `isComposerFormSubmitting` isn't the UI loading state — `isSubmitting`
+ // (sending || startingRun) is. `errors` gates programmatic `submitComposerForm()`; the UI's own
+ // `Composer.Root` disabled-reason is the parallel guard.
+ composerForm: {
+ defaults: { draft: '' as string },
+ errors: ({ draft }) => ({
+ draft: !draft.trim() ? 'Type a message first' : undefined,
+ }),
+ submit: ({ draft }) => {
+ const content = draft.trim()
+ if (!content) {
+ return
+ }
+ // A finished run can't take a follow-up signal — send starts a fresh run instead, seeded with
+ // this message and chained from the run just viewed.
+ if (values.isTerminal) {
+ actions.startNewRun(content)
+ return
+ }
+ // While the agent is working, a send is in flight, or a message is already staged — concatenate
+ // this onto the single queued message so follow-ups never jump ahead or fan out; otherwise send
+ // it straight from the draft. `flushQueue` self-guards, draining only when the run is fully idle.
+ if (values.isBusy || values.sending || values.queuedMessages.length > 0) {
+ actions.enqueueMessage(content)
+ actions.resetComposerForm()
+ actions.flushQueue()
+ } else {
+ actions.sendNow(content, 'draft')
+ }
+ },
+ },
+ })),
+
selectors({
isTerminal: [(s) => [s.currentRunStatus], (status): boolean => isTerminalRunStatus(status)],
+ // The model/effort to display in the picker and launch the next run with: the optimistic client-side
+ // override, else the run's stored value, else the default. Effort is clamped to one the model supports.
+ selectedModel: [
+ (s) => [s.modelOverride, (_, p) => p.currentModel],
+ (override, current): string => override ?? current ?? DEFAULT_COMPOSER_MODEL,
+ ],
+ selectedEffort: [
+ (s) => [s.effortOverride, (_, p) => p.currentEffort, s.selectedModel],
+ (override, current, model): ReasoningEffortEnumApi =>
+ resolveEffortForModel(override ?? current ?? DEFAULT_COMPOSER_EFFORT, model),
+ ],
// The agent is actively working a turn — a follow-up typed now should stage rather than send.
isBusy: [(s) => [s.isThinking], (isThinking): boolean => isThinking],
canSend: [
@@ -136,29 +228,6 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}),
listeners(({ actions, values, props }) => ({
- submit: () => {
- const content = values.draft.trim()
- if (!content) {
- return
- }
- // A finished run can't take a follow-up signal — send starts a fresh run instead, seeded with
- // this message and chained from the run just viewed.
- if (values.isTerminal) {
- actions.startNewRun(content)
- return
- }
- // While the agent is working, a send is in flight, or a message is already staged — concatenate
- // this onto the single queued message so follow-ups never jump ahead or fan out; otherwise send it
- // straight from the draft. `flushQueue` self-guards, draining only when the run is fully idle.
- if (values.isBusy || values.sending || values.queuedMessages.length > 0) {
- actions.enqueueMessage(content)
- actions.clearDraft()
- actions.flushQueue()
- } else {
- actions.sendNow(content, 'draft')
- }
- },
-
// Drain the staged "Up next" message — only when the run is idle and can actually take it, so a flush
// against a busy/terminal/in-flight send is a no-op rather than dropping the message. The buffer is
// cleared up-front (not after the send) so a follow-up typed during the in-flight send stages cleanly
@@ -186,9 +255,35 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// flight isn't clobbered when the request resolves; a failed send restores it ahead of anything
// typed since. The queue buffer was already cleared up-front in `flushQueue`.
if (source === 'draft') {
- actions.clearDraft()
+ actions.resetComposerForm()
}
try {
+ // Sync the picked model/effort to the agent session first, but only what the user actually
+ // changed since the last sync — mid-run config lives as session state, so it must go via a
+ // `set_config_option` command before the message rather than ride inside `user_message`. A
+ // failure here aborts the send (the catch restores the content); `setSent*` runs only after a
+ // successful sync so the next send retries an unsent change.
+ const activeModel = values.sentModel ?? props.currentModel ?? DEFAULT_COMPOSER_MODEL
+ const activeEffort = resolveEffortForModel(
+ values.sentEffort ?? props.currentEffort ?? DEFAULT_COMPOSER_EFFORT,
+ activeModel
+ )
+ if (values.selectedModel !== activeModel) {
+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {
+ jsonrpc: '2.0',
+ method: 'set_config_option',
+ params: { configId: MODEL_CONFIG_ID, value: values.selectedModel },
+ })
+ actions.setSentModel(values.selectedModel)
+ }
+ if (values.selectedEffort !== activeEffort) {
+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {
+ jsonrpc: '2.0',
+ method: 'set_config_option',
+ params: { configId: EFFORT_CONFIG_ID, value: values.selectedEffort },
+ })
+ actions.setSentEffort(values.selectedEffort)
+ }
await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {
jsonrpc: '2.0',
method: 'user_message',
@@ -200,7 +295,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Restore unsent content for retry, preserving send order — draft content goes back ahead of
// anything typed during the failed send, queue content re-stages ahead of anything staged since.
if (source === 'draft') {
- actions.setDraft(values.draft ? `${content}\n\n${values.draft}` : content)
+ actions.setComposerFormValues({
+ draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,
+ })
} else {
actions.prependQueuedMessage(content)
}
@@ -215,6 +312,16 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.flushQueue()
},
+ // The new model may not support the current effort — clamp the override so it never holds an
+ // unsupported value. No network here: the pick is synced to the agent at send time.
+ setModel: ({ model }) => {
+ const currentEffort = values.effortOverride ?? props.currentEffort
+ const resolvedEffort = resolveEffortForModel(currentEffort, model)
+ if (resolvedEffort !== currentEffort) {
+ actions.setEffort(resolvedEffort)
+ }
+ },
+
startNewRun: async ({ content }) => {
if (values.startingRun || !content.trim() || values.currentProjectId == null) {
return
@@ -222,14 +329,18 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.setStartingRun(true)
try {
// Same endpoint as the "Run again" button, but seeded with the user's message and chained
- // from the finished run so the new run continues the thread. The response carries the new
- // run id as `latest_run`; the consumer-provided `onRunStarted` re-points selection to it.
- const resumeRequest: TaskRunResumeRequestSchemaApi = {
+ // from the finished run so the new run continues the thread, and carrying the picked model /
+ // reasoning effort (the resume schema can't, so we send the Claude create shape). The response
+ // carries the new run id as `latest_run`; the consumer-provided `onRunStarted` re-points to it.
+ const createRequest: ClaudeTaskRunCreateSchemaApi = {
+ runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,
+ model: values.selectedModel,
+ reasoning_effort: values.selectedEffort,
resume_from_run_id: props.runId,
pending_user_message: content,
}
- const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, resumeRequest)
- actions.clearDraft()
+ const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)
+ actions.resetComposerForm()
if (result.latest_run) {
props.onRunStarted?.(result.latest_run)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
index 2f4ebe5e3822..256a74a6a9e2 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
@@ -98,6 +98,16 @@ const listResponse = (results: Task[]): Record<string, unknown> => ({
results,
})
+const GITHUB_INTEGRATION = {
+ id: 1,
+ kind: 'github',
+ display_name: 'PostHog',
+ icon_url: '',
+ config: {},
+ created_by: null,
+ created_at: '2024-01-01T00:00:00Z',
+}
+
const meta: Meta = {
component: App,
title: 'Scenes-App/Tasks',
@@ -135,6 +145,33 @@ export const NewTask: Story = {
},
}
+// New-task route with a GitHub integration connected — the footer shows the repository picker chip (and,
+// once a repo is auto/selected, the branch picker) instead of the "Connect GitHub" chip.
+export const NewTaskWithRepository: Story = {
+ parameters: {
+ pageUrl: taskNewUrl(),
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/integrations/': { results: [GITHUB_INTEGRATION] },
+ '/api/environments/:team_id/integrations/1/github_repos': {
+ repositories: [
+ { id: 1, name: 'posthog', full_name: 'PostHog/posthog' },
+ { id: 2, name: 'posthog.com', full_name: 'PostHog/posthog.com' },
+ ],
+ has_more: false,
+ },
+ '/api/environments/:team_id/integrations/1/github_branches': {
+ branches: ['master', 'release'],
+ default_branch: 'master',
+ has_more: false,
+ },
+ },
+ }),
+ ],
+}
+
// A task is selected: the row is highlighted and its detail fills the right column.
export const TaskSelected: Story = {
parameters: {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ComposerModelEffortPickers.tsx
new file mode 100644
index 000000000000..56be6dc567be
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ComposerModelEffortPickers.tsx
@@ -0,0 +1,103 @@
+import { useState } from 'react'
+
+import { IconBrain, IconChevronDown } from '@posthog/icons'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from '@posthog/quill-primitives'
+
+import {
+ COMPOSER_MODELS,
+ getEffortLabel,
+ getEffortsForModel,
+ getModelLabel,
+} from 'products/posthog_ai/frontend/utils/composerModels'
+import { ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+export interface ComposerModelEffortPickersProps {
+ selectedModel: string
+ selectedEffort: ReasoningEffortEnumApi
+ onModelChange: (model: string) => void
+ onEffortChange: (effort: ReasoningEffortEnumApi) => void
+}
+
+/**
+ * Controlled, logic-free model + reasoning-effort pickers for a composer footer. The caller owns the selection
+ * and the side effects of changing it — the run composer wires it to `runInteractionLogic` (held client-side and
+ * applied at send time), the new-task composer wires it to the form that seeds the first run. This component only
+ * renders the dropdowns and reports changes up.
+ */
+export function ComposerModelEffortPickers({
+ selectedModel,
+ selectedEffort,
+ onModelChange,
+ onEffortChange,
+}: ComposerModelEffortPickersProps): JSX.Element {
+ const effortOptions = getEffortsForModel(selectedModel)
+ const [modelOpen, setModelOpen] = useState(false)
+ const [effortOpen, setEffortOpen] = useState(false)
+
+ return (
+ <div className="flex items-center gap-1 pl-2">
+ <DropdownMenu open={modelOpen} onOpenChange={setModelOpen}>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="outline" size="sm">
+ {getModelLabel(selectedModel)}
+ <IconChevronDown />
+ </Button>
+ }
+ />
+ <DropdownMenuContent className="w-auto min-w-(--anchor-width)">
+ <DropdownMenuRadioGroup
+ value={selectedModel}
+ onValueChange={(value) => {
+ onModelChange(value)
+ setModelOpen(false)
+ }}
+ >
+ <DropdownMenuLabel>Model</DropdownMenuLabel>
+ {COMPOSER_MODELS.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <DropdownMenu open={effortOpen} onOpenChange={setEffortOpen}>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="outline" size="sm">
+ <IconBrain />
+ {getEffortLabel(selectedEffort)}
+ <IconChevronDown />
+ </Button>
+ }
+ />
+ <DropdownMenuContent className="w-auto min-w-(--anchor-width)">
+ <DropdownMenuRadioGroup
+ value={selectedEffort}
+ onValueChange={(value: string) => {
+ onEffortChange(value as ReasoningEffortEnumApi)
+ setEffortOpen(false)
+ }}
+ >
+ <DropdownMenuLabel>Effort</DropdownMenuLabel>
+ {effortOptions.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
index fe5d1078fe8a..c6697ebe3d59 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
@@ -1,8 +1,10 @@
import { useValues } from 'kea'
-import { LemonSkeleton } from '@posthog/lemon-ui'
+import { IconGitBranch, IconGithub } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
+import { Button, ButtonGroup } from '@posthog/quill-primitives'
-import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
+import api from 'lib/api'
import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'
import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
@@ -15,11 +17,18 @@ export interface RepositorySelectorProps {
onChange: (config: RepositoryConfig) => void
}
+const githubAuthorizeUrl = api.integrations.authorizeUrl({ kind: 'github', next: urls.taskTracker() })
+
+/**
+ * Compact repo/branch picker. With no GitHub integration it shows a single "Connect GitHub" chip;
+ * with one or more it shows a joined [repo ▾][branch ▾] ButtonGroup (matching the posthog/code
+ * composer), plus a leading integration switcher when several GitHub orgs are connected.
+ */
export function RepositorySelector({ value, onChange }: RepositorySelectorProps): JSX.Element {
- const { integrationsLoading } = useValues(integrationsLogic)
+ const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)
+ const githubIntegrations = getIntegrationsByKind(['github'])
- // The picker selects on `owner/repo`, which is exactly the format the Task API expects. Switching repos
- // clears the branch so the new repo's default branch is picked up.
+ // Selecting a repo clears the branch so GitHubBranchCombobox auto-picks the new repo's default branch.
const handleRepositoryChange = (repository: string | null): void => {
onChange({ ...value, repository: repository ?? undefined, branch: undefined })
}
@@ -28,50 +37,94 @@ export function RepositorySelector({ value, onChange }: RepositorySelectorProps)
onChange({ ...value, branch: branch ?? undefined })
}
+ const handleIntegrationChange = (integrationId: number): void => {
+ onChange({ ...value, integrationId, repository: undefined, branch: undefined })
+ }
+
if (integrationsLoading) {
- return <LemonSkeleton className="h-24" />
+ // Inert placeholder so we never flash "Connect GitHub" before the integration list resolves.
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ <Button variant="outline" size="sm" disabled>
+ <IconGithub className="shrink-0" />
+ GitHub
+ </Button>
+ </div>
+ )
}
- return (
- <div className="space-y-4">
- <div>
- <label className="block text-sm font-medium mb-2">GitHub integration</label>
- <IntegrationChoice
- integration="github"
- value={value.integrationId}
- onChange={(integrationId) =>
- onChange({
- ...value,
- integrationId: integrationId ?? undefined,
- repository: undefined,
- branch: undefined,
- })
- }
- redirectUrl={urls.taskTracker()}
- />
+ if (githubIntegrations.length === 0) {
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconGithub />}
+ to={githubAuthorizeUrl}
+ disableClientSideRouting
+ >
+ Connect GitHub
+ </LemonButton>
</div>
+ )
+ }
+
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ {githubIntegrations.length > 1 && (
+ <LemonMenu
+ items={[
+ {
+ items: githubIntegrations.map((integration) => ({
+ icon: (
+ <img
+ src={integration.icon_url}
+ alt={`${integration.display_name} icon`}
+ className="w-5 h-5 rounded"
+ />
+ ),
+ label: integration.display_name,
+ active: integration.id === value.integrationId,
+ onClick: () => handleIntegrationChange(integration.id),
+ })),
+ },
+ {
+ items: [
+ { to: githubAuthorizeUrl, disableClientSideRouting: true, label: 'Connect another' },
+ { to: urls.settings('project-integrations'), label: 'Manage integrations' },
+ ],
+ },
+ ]}
+ >
+ <LemonButton size="small" type="secondary" icon={<IconGithub />}>
+ {githubIntegrations.find((i) => i.id === value.integrationId)?.display_name ?? 'GitHub'}
+ </LemonButton>
+ </LemonMenu>
+ )}
{value.integrationId ? (
- <div>
- <label className="block text-sm font-medium mb-2">Repository</label>
+ <ButtonGroup>
<GitHubRepositoryCombobox
integrationId={value.integrationId}
value={value.repository ?? ''}
onChange={handleRepositoryChange}
+ placeholder="No repo"
+ showNoneOption
/>
- </div>
- ) : null}
-
- {value.integrationId && value.repository ? (
- <div>
- <label className="block text-sm font-medium mb-2">Branch</label>
- <GitHubBranchCombobox
- integrationId={value.integrationId}
- repo={value.repository}
- value={value.branch ?? ''}
- onChange={handleBranchChange}
- />
- </div>
+ {value.repository ? (
+ <GitHubBranchCombobox
+ integrationId={value.integrationId}
+ repo={value.repository}
+ value={value.branch ?? ''}
+ onChange={handleBranchChange}
+ />
+ ) : (
+ <Button variant="outline" size="sm" disabled aria-label="Branch">
+ <IconGitBranch className="shrink-0" />
+ Branch
+ </Button>
+ )}
+ </ButtonGroup>
) : null}
</div>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 3a508470d598..de379ffb9b15 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -1,59 +1,93 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useRef } from 'react'
-import { IconArrowRight } from '@posthog/icons'
-import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
+import {
+ Composer,
+ DEFAULT_SUGGESTIONS_DATA,
+ type SuggestionItem,
+ Suggestions,
+ Welcome,
+} from 'products/posthog_ai/frontend/api/primitives'
+import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'
import { RepositorySelector } from './RepositorySelector'
export function TaskComposer(): JSX.Element {
- const { submitNewTask, setNewTaskData } = useActions(taskTrackerSceneLogic)
- const { newTaskData, isSubmittingTask } = useValues(taskTrackerSceneLogic)
+ const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion } =
+ useActions(taskTrackerSceneLogic)
+ const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline, sendDisabledReason } =
+ useValues(taskTrackerSceneLogic)
- return (
- <div className="flex flex-col h-full min-h-0">
- <div className="flex-1 min-h-0 overflow-y-auto">
- <div className="flex flex-col gap-6 w-full max-w-2xl mx-auto lg:py-8 lg:px-4">
- <div>
- <h2 className="text-lg font-semibold mb-1">New task</h2>
- <p className="text-muted text-sm mb-0">
- Describe what you'd like an agent to do, then pick a repository to run it against.
- </p>
- </div>
+ const textAreaRef = useRef<HTMLTextAreaElement>(null)
- <div>
- <label className="block text-sm font-medium mb-2">Description</label>
- <LemonTextArea
- value={newTaskData.description}
- onChange={(value) => setNewTaskData({ description: value })}
- placeholder="Describe the task in detail..."
- rows={8}
- autoFocus
- />
- </div>
+ const handleSelectSuggestion = (item: SuggestionItem): void => {
+ applySuggestion(item)
+ if (item.requiresUserInput) {
+ textAreaRef.current?.focus()
+ }
+ }
- <div>
- <label className="block text-sm font-medium mb-2">Repository</label>
+ return (
+ <div className="flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4">
+ <div className="w-full max-w-2xl flex flex-col items-center gap-4">
+ <Welcome headline={headline} />
+
+ <Suggestions.Root
+ activeGroup={activeSuggestionGroup}
+ onActiveGroupChange={setActiveSuggestionGroup}
+ onSelectSuggestion={handleSelectSuggestion}
+ onNavigate={(url) => router.actions.push(url)}
+ >
+ {/* Repo/branch picker sits 8px above the input it configures. */}
+ <div className="w-full flex flex-col gap-2">
<RepositorySelector
value={newTaskData.repositoryConfig}
onChange={(config) => setNewTaskData({ repositoryConfig: config })}
/>
+ <Composer.Root
+ value={newTaskData.description}
+ onChange={(value) => setNewTaskData({ description: value })}
+ onSubmit={submitNewTask}
+ loading={isSubmittingTask}
+ disabledReason={sendDisabledReason}
+ textAreaRef={textAreaRef}
+ >
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>Describe the task in detail…</Composer.Placeholder>
+ <Composer.Textarea
+ submitShortcut="cmd-enter"
+ autoFocus
+ data-attr="task-composer-input"
+ />
+ </Composer.Field>
+ <Composer.Footer>
+ <ComposerModelEffortPickers
+ selectedModel={newTaskData.model}
+ selectedEffort={newTaskData.reasoningEffort}
+ onModelChange={(model) =>
+ setNewTaskData({
+ model,
+ reasoningEffort: resolveEffortForModel(
+ newTaskData.reasoningEffort,
+ model
+ ),
+ })
+ }
+ onEffortChange={(reasoningEffort) => setNewTaskData({ reasoningEffort })}
+ />
+ </Composer.Footer>
+ </Composer.Frame>
+ <Suggestions.Dropdown />
+ <Composer.Submit data-attr="task-composer-send" />
+ </Composer.Root>
</div>
- </div>
- </div>
- <div className="border-t px-4 py-3 shrink-0">
- <div className="w-full max-w-2xl mx-auto flex justify-end">
- <LemonButton
- type="primary"
- icon={<IconArrowRight />}
- onClick={submitNewTask}
- loading={isSubmittingTask}
- disabledReason={!newTaskData.description.trim() ? 'Add a description first' : undefined}
- >
- Create task
- </LemonButton>
- </div>
+ <Suggestions.Buttons data={DEFAULT_SUGGESTIONS_DATA} />
+ </Suggestions.Root>
</div>
</div>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 0f57298af9c0..c553b7f7037d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -8,6 +8,7 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
+import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'
export interface TaskRunChatProps {
taskId: string
@@ -24,9 +25,12 @@ export interface TaskRunChatProps {
*/
export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {
const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))
+ const { selectedRun } = useValues(taskDetailSceneLogic({ taskId }))
const logicProps: RunInteractionLogicProps = {
taskId,
runId,
+ currentModel: selectedRun?.state?.model,
+ currentEffort: selectedRun?.state?.reasoning_effort,
onRunStarted: (newRunId) => {
setSelectedRunId(newRunId, taskId)
loadTaskRuns()
@@ -41,8 +45,11 @@ export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {
}
function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {
- const { draft, isSubmitting, queuedMessages, isTerminal } = useValues(runInteractionLogic(logicProps))
- const { setDraft, submit, updateQueuedMessage, removeQueuedMessage } = useActions(runInteractionLogic(logicProps))
+ const { composerForm, isSubmitting, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(
+ runInteractionLogic(logicProps)
+ )
+ const { setComposerFormValues, submitComposerForm, updateQueuedMessage, removeQueuedMessage, setModel, setEffort } =
+ useActions(runInteractionLogic(logicProps))
return (
// `RunSurface.Root` binds `runStreamLogic` keyed by `runId`; `runInteractionLogic` connects to the same
@@ -52,7 +59,12 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicPro
<RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
<RunSurface.Composer>
<RunSurface.Resources />
- <Composer.Root value={draft} onChange={setDraft} onSubmit={submit} loading={isSubmitting}>
+ <Composer.Root
+ value={composerForm.draft}
+ onChange={(value) => setComposerFormValues({ draft: value })}
+ onSubmit={submitComposerForm}
+ loading={isSubmitting}
+ >
{queuedMessages.length > 0 && (
<Composer.Banner>
<QueuedMessageList
@@ -69,6 +81,17 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicPro
</Composer.Placeholder>
<Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />
</Composer.Field>
+ <Composer.Footer>
+ {/* Model/effort picker: selection lives in the bound runInteractionLogic and is
+ applied when the message is sent — synced to the running agent on a follow-up,
+ or used to seed the next run once terminal. */}
+ <ComposerModelEffortPickers
+ selectedModel={selectedModel}
+ selectedEffort={selectedEffort}
+ onModelChange={setModel}
+ onEffortChange={setEffort}
+ />
+ </Composer.Footer>
</Composer.Frame>
<Composer.Submit data-attr="sandbox-composer-send" />
</Composer.Root>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
new file mode 100644
index 000000000000..83f4ae240c2d
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -0,0 +1,61 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { OriginProduct } from '../../types/taskTypes'
+import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
+
+describe('taskTrackerSceneLogic', () => {
+ let logic: ReturnType<typeof taskTrackerSceneLogic.build>
+ let createBody: Record<string, any> | null
+ let runCalled: boolean
+
+ beforeEach(() => {
+ createBody = null
+ runCalled = false
+ useMocks({
+ get: {
+ '/api/projects/:team/tasks/': { results: [], count: 0 },
+ '/api/projects/:team/tasks/repositories/': { repositories: [] },
+ '/api/projects/:team/integrations/': { results: [] },
+ },
+ post: {
+ '/api/projects/:team/tasks/': async ({ request }) => {
+ createBody = (await request.json()) as Record<string, any>
+ return [200, { id: 'new-task', ...createBody }]
+ },
+ '/api/projects/:team/tasks/:id/run/': () => {
+ runCalled = true
+ return [200, { id: 'new-task' }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = taskTrackerSceneLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // PostHog AI can run without a repo: a description-only submit must still create and run the task with a
+ // null repository, not bail. Guards against re-adding a "Repository is required" gate on the send path.
+ it('creates and runs a task with no repository selected', async () => {
+ logic.actions.setNewTaskData({ description: 'do the thing' })
+ logic.actions.submitNewTask()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBody).toMatchObject({
+ description: 'do the thing',
+ origin_product: OriginProduct.POSTHOG_AI,
+ repository: null,
+ github_integration: null,
+ })
+ expect(runCalled).toBe(true)
+ expect(router.values.location.pathname).toContain('/tasks/new-task')
+ })
+})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 25cabdc32fed..4defa6afa07d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -1,34 +1,55 @@
-import { actions, connect, events, kea, listeners, path, reducers } from 'kea'
+import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { ClaudeRuntimeAdapterEnumApi, ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'
+import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
import { tasksLogic } from '../../logics/tasksLogic'
import type { RepositoryConfig } from '../../types/taskTypes'
import { OriginProduct, TaskUpsertProps } from '../../types/taskTypes'
+import { DEFAULT_COMPOSER_EFFORT, DEFAULT_COMPOSER_MODEL, resolveEffortForModel } from '../../utils/composerModels'
import type { taskTrackerSceneLogicType } from './taskTrackerSceneLogicType'
-export type TaskCreateForm = {
+export interface TaskCreateForm {
description: string
repositoryConfig: RepositoryConfig
+ model: string
+ reasoningEffort: ReasoningEffortEnumApi
}
+// The slice of the repo picker we remember across visits. Branch is deliberately excluded — on restore we
+// want the branch picker to re-derive the repo's actual default branch (from the GitHub API), not pin a stale one.
+export type PersistedRepositoryConfig = Pick<RepositoryConfig, 'integrationId' | 'repository'>
+
+const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'
+
const EMPTY_TASK_FORM: TaskCreateForm = {
description: '',
repositoryConfig: {
integrationId: undefined,
repository: undefined,
},
+ model: DEFAULT_COMPOSER_MODEL,
+ reasoningEffort: DEFAULT_COMPOSER_EFFORT,
}
export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
path(['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskTrackerSceneLogic']),
connect(() => ({
- values: [tasksLogic, ['tasks', 'repositories']],
- actions: [tasksLogic, ['loadTasks', 'loadRepositories', 'deleteTask']],
+ values: [tasksLogic, ['tasks', 'repositories'], integrationsLogic, ['integrations']],
+ actions: [
+ tasksLogic,
+ ['loadTasks', 'loadRepositories', 'deleteTask'],
+ integrationsLogic,
+ ['loadIntegrationsSuccess'],
+ ],
})),
actions({
@@ -37,11 +58,16 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
submitNewTask: true,
submitNewTaskSuccess: true,
submitNewTaskFailure: (error: string) => ({ error }),
+ maybeAutoSelectIntegration: true,
+ setActiveSuggestionGroup: (group: SuggestionGroup | null) => ({ group }),
+ applySuggestion: (item: SuggestionItem) => ({ item }),
+ setHeadline: (headline: string) => ({ headline }),
+ setPersistedRepositoryConfig: (config: PersistedRepositoryConfig) => ({ config }),
}),
reducers({
newTaskData: [
- EMPTY_TASK_FORM,
+ EMPTY_TASK_FORM as TaskCreateForm,
{
setNewTaskData: (state, { data }) => ({ ...state, ...data }),
resetNewTaskData: () => EMPTY_TASK_FORM,
@@ -55,29 +81,100 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
submitNewTaskFailure: () => false,
},
],
+ // Last repo/integration the user picked, persisted to localStorage so the composer comes back pre-filled.
+ persistedRepositoryConfig: [
+ {} as PersistedRepositoryConfig,
+ { persist: true, storageKey: LAST_REPOSITORY_CONFIG_STORAGE_KEY },
+ {
+ setPersistedRepositoryConfig: (_, { config }) => config,
+ },
+ ],
+ activeSuggestionGroup: [
+ null as SuggestionGroup | null,
+ {
+ setActiveSuggestionGroup: (_, { group }) => group,
+ // Clearing the description (e.g. after submit/reset) collapses any open dropdown.
+ setNewTaskData: (state, { data }) =>
+ data.description !== undefined && !data.description ? null : state,
+ resetNewTaskData: () => null,
+ },
+ ],
+ headline: [
+ DEFAULT_HEADLINES[0],
+ {
+ setHeadline: (_, { headline }) => headline,
+ },
+ ],
+ }),
+
+ selectors({
+ sendDisabledReason: [
+ (s) => [s.newTaskData],
+ (newTaskData): string | undefined =>
+ !newTaskData.description.trim() ? 'Describe the task first' : undefined,
+ ],
}),
listeners(({ actions, values }) => ({
+ // Remember the repo/integration whenever the picker changes it to a real selection. Clearing the
+ // repo ("No repo" option) is intentionally NOT persisted so the next visit restores the last good pick.
+ setNewTaskData: ({ data }) => {
+ if (data.repositoryConfig?.repository) {
+ const { integrationId, repository } = data.repositoryConfig
+ actions.setPersistedRepositoryConfig({ integrationId, repository })
+ }
+ },
+ // Restore the remembered repo (or fall back to the first connected GitHub integration) when nothing is
+ // chosen yet. The IntegrationChoice picker that used to own this selection is no longer rendered.
+ maybeAutoSelectIntegration: () => {
+ if (values.newTaskData.repositoryConfig.integrationId) {
+ return
+ }
+ const githubIntegrations = values.integrations?.filter((integration) => integration.kind === 'github') ?? []
+ if (githubIntegrations.length === 0) {
+ return
+ }
+ // Restore the last-used repo only if its integration is still connected. Branch is left unset so
+ // GitHubBranchCombobox re-selects the repo's actual default branch.
+ const { integrationId, repository } = values.persistedRepositoryConfig
+ if (integrationId && githubIntegrations.some((integration) => integration.id === integrationId)) {
+ actions.setNewTaskData({ repositoryConfig: { integrationId, repository } })
+ return
+ }
+ actions.setNewTaskData({
+ repositoryConfig: {
+ ...values.newTaskData.repositoryConfig,
+ integrationId: githubIntegrations[0].id,
+ },
+ })
+ },
+ loadIntegrationsSuccess: () => {
+ actions.maybeAutoSelectIntegration()
+ },
+ // Fill the composer with the suggestion; submit straight away unless it needs the user to finish
+ // typing (the component focuses the textarea in that case).
+ applySuggestion: ({ item }) => {
+ actions.setNewTaskData({ description: item.content })
+ if (!item.requiresUserInput) {
+ actions.submitNewTask()
+ }
+ },
submitNewTask: async () => {
- const { description, repositoryConfig } = values.newTaskData
+ const { description, repositoryConfig, model, reasoningEffort } = values.newTaskData
if (!description.trim()) {
lemonToast.error('Description is required')
actions.submitNewTaskFailure('Description is required')
return
}
- if (!repositoryConfig.integrationId || !repositoryConfig.repository) {
- lemonToast.error('Repository is required')
- actions.submitNewTaskFailure('Repository is required')
- return
- }
try {
const taskData: TaskUpsertProps = {
title: '',
description,
- origin_product: OriginProduct.USER_CREATED,
- repository: repositoryConfig.repository,
+ origin_product: OriginProduct.POSTHOG_AI,
+ // PostHog AI can run without a repo; null means the task is not scoped to any repository.
+ repository: repositoryConfig.repository ?? null,
github_integration: repositoryConfig.integrationId ?? null,
}
@@ -85,14 +182,19 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
lemonToast.success('Task created successfully')
// Auto-run the task after creation; the detail scene shows the latest run by default. The
- // run checks out the chosen branch (server falls back to the repo's default branch if unset).
- await api.tasks.run(newTask.id, { branch: repositoryConfig.branch ?? null })
+ // run checks out the chosen branch (server falls back to the repo's default branch if unset)
+ // and launches with the picked model / reasoning effort (clamped to one the model supports).
+ await api.tasks.run(newTask.id, {
+ branch: repositoryConfig.branch ?? null,
+ runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,
+ model,
+ reasoning_effort: resolveEffortForModel(reasoningEffort, model),
+ })
router.actions.push(`/tasks/${newTask.id}`)
actions.submitNewTaskSuccess()
actions.resetNewTaskData()
- actions.loadTasks()
- actions.loadRepositories()
+ tasksLogic.actions.loadTasks()
} catch (error) {
lemonToast.error('Failed to create task')
actions.submitNewTaskFailure(error instanceof Error ? error.message : 'Unknown error')
@@ -102,8 +204,14 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
events(({ actions }) => ({
afterMount: () => {
- actions.loadTasks()
- actions.loadRepositories()
+ tasksLogic.actions.loadTasks()
+ tasksLogic.actions.loadRepositories()
+ // Roll a headline once per mount (pickHeadline forces index 0 under Storybook for stable snapshots).
+ actions.setHeadline(pickHeadline())
+ // integrationsLogic loads on its own mount (triggered by the connect above), so we don't call
+ // loadIntegrations ourselves. loadIntegrationsSuccess covers that first load; this call covers
+ // integrations already cached by an earlier mount.
+ actions.maybeAutoSelectIntegration()
},
})),
])
diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.ts
index 75714803dd24..9f7cac5aeaa5 100644
--- a/products/posthog_ai/frontend/types/taskTypes.ts
+++ b/products/posthog_ai/frontend/types/taskTypes.ts
@@ -19,6 +19,7 @@ export enum OriginProduct {
SIGNAL_REPORT = 'signal_report',
// Runs created by a Signals scout (automated agent) — no interactive context budget to surface.
SIGNALS_SCOUT = 'signals_scout',
+ POSTHOG_AI = 'posthog_ai',
}
export enum TaskRunStatus {
diff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.ts
new file mode 100644
index 000000000000..ca39fa2f14c3
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/composerModels.ts
@@ -0,0 +1,75 @@
+import { ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+export interface ComposerModelOption {
+ value: string
+ label: string
+}
+
+export interface ComposerEffortOption {
+ value: ReasoningEffortEnumApi
+ label: string
+}
+
+// Claude-only lineup — the task tracker always launches the `claude` runtime adapter, so Codex/GPT models are
+// intentionally absent. Add new Claude models here as they ship.
+export const COMPOSER_MODELS: ComposerModelOption[] = [
+ { value: 'claude-opus-4-8', label: 'Claude Opus 4.8' },
+ { value: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },
+]
+
+export const DEFAULT_COMPOSER_MODEL = 'claude-opus-4-8'
+export const DEFAULT_COMPOSER_EFFORT: ReasoningEffortEnumApi = ReasoningEffortEnumApi.High
+
+const EFFORT_LABELS: Record<ReasoningEffortEnumApi, string> = {
+ [ReasoningEffortEnumApi.Low]: 'Low',
+ [ReasoningEffortEnumApi.Medium]: 'Medium',
+ [ReasoningEffortEnumApi.High]: 'High',
+ [ReasoningEffortEnumApi.Xhigh]: 'Extra high',
+ [ReasoningEffortEnumApi.Max]: 'Max',
+}
+
+// Mirrors backend CLAUDE_REASONING_EFFORTS_BY_MODEL (products/tasks/backend/temporal/process_task/utils.py):
+// xhigh/max are only offered for models that support them.
+const EFFORTS_BY_MODEL: Record<string, ReasoningEffortEnumApi[]> = {
+ 'claude-opus-4-8': [
+ ReasoningEffortEnumApi.Low,
+ ReasoningEffortEnumApi.Medium,
+ ReasoningEffortEnumApi.High,
+ ReasoningEffortEnumApi.Xhigh,
+ ReasoningEffortEnumApi.Max,
+ ],
+ 'claude-sonnet-4-6': [ReasoningEffortEnumApi.Low, ReasoningEffortEnumApi.Medium, ReasoningEffortEnumApi.High],
+}
+
+const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = [
+ ReasoningEffortEnumApi.Low,
+ ReasoningEffortEnumApi.Medium,
+ ReasoningEffortEnumApi.High,
+]
+
+export function getEffortsForModel(model: string | null | undefined): ComposerEffortOption[] {
+ const efforts = (model && EFFORTS_BY_MODEL[model]) || FALLBACK_EFFORTS
+ return efforts.map((value) => ({ value, label: EFFORT_LABELS[value] }))
+}
+
+export function getModelLabel(model: string | null | undefined): string {
+ return COMPOSER_MODELS.find((option) => option.value === model)?.label ?? model ?? 'Model'
+}
+
+export function getEffortLabel(effort: string | null | undefined): string {
+ return effort ? (EFFORT_LABELS[effort as ReasoningEffortEnumApi] ?? effort) : 'Effort'
+}
+
+// Clamp an effort to one the selected model actually supports — the new-run path can inherit an effort from a
+// previous run on a different model (e.g. `max` carried over to Sonnet, which only offers low/medium/high), and
+// the backend rejects an out-of-range effort. Falls back to the default when valid, else the highest available.
+export function resolveEffortForModel(
+ effort: string | null | undefined,
+ model: string | null | undefined
+): ReasoningEffortEnumApi {
+ const allowed = getEffortsForModel(model).map((option) => option.value)
+ if (effort && allowed.includes(effort as ReasoningEffortEnumApi)) {
+ return effort as ReasoningEffortEnumApi
+ }
+ return allowed.includes(DEFAULT_COMPOSER_EFFORT) ? DEFAULT_COMPOSER_EFFORT : allowed[allowed.length - 1]
+}
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index a5c3e5001c90..2762330a9d95 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -20,6 +20,7 @@
},
"peerDependencies": {
"@posthog/icons": "catalog:",
+ "@posthog/quill-primitives": "workspace:*",
"@storybook/react": "catalog:",
"@types/react": "*",
"@types/react-dom": "*",