:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(today): start a session from a space feed (#109195)
Shy Alter2012bf9835ef
diff --git a/products/posthog_ai/frontend/api/runner.ts b/products/posthog_ai/frontend/api/runner.tsindex df1b468146b7..65ec9ba735f3 100644--- a/products/posthog_ai/frontend/api/runner.ts+++ b/products/posthog_ai/frontend/api/runner.ts@@ -18,3 +18,9 @@ export { EmbeddedRunner, type TaskTrackerProps } from '../components/EmbeddedRun// its dynamic `import()`. `panelId` keys an embedded `taskTrackerSceneLogic` instance independent of the// `/tasks` scene's own singleton — submitting a task here never navigates the host.export { SidePanelRunner, type SidePanelRunnerProps } from '../components/SidePanelRunner'++// `EmbeddedTaskComposer` (`<EmbeddedTaskComposer panelId />`) is the lazy, code-split new-task composer alone,+// for a host page that lists tasks itself. It has the same LIGHT boundary and `panelId` keying as+// `SidePanelRunner`. `channelId` files the created task in a tasks channel, `initialRepositoryConfig` sets the+// starting repo, and `onTaskCreated` gives the new task id back, so the host decides what to open.+export { EmbeddedTaskComposer, type EmbeddedTaskComposerProps } from '../components/EmbeddedTaskComposer'diff --git a/products/posthog_ai/frontend/components/EmbeddedTaskComposer.tsx b/products/posthog_ai/frontend/components/EmbeddedTaskComposer.tsxnew file mode 100644index 000000000000..c91bf543d1f0--- /dev/null+++ b/products/posthog_ai/frontend/components/EmbeddedTaskComposer.tsx@@ -0,0 +1,31 @@+import { Suspense } from 'react'++import { Spinner } from 'lib/lemon-ui/Spinner'+import { lazyWithRetry } from 'lib/utils/retryImport'++import type { EmbeddedTaskComposerImplProps } from '../scenes/TaskTracker/components/EmbeddedTaskComposerImpl'++export type EmbeddedTaskComposerProps = EmbeddedTaskComposerImplProps++// The composer pulls in the TaskTracker scene logic and its pickers, so it loads on demand. A host that+// only imports this module keeps its own chunk light.+const Lazy = lazyWithRetry(() =>+ import('../scenes/TaskTracker/components/EmbeddedTaskComposerImpl').then((m) => ({+ default: m.EmbeddedTaskComposerImpl,+ }))+)++/** The new-task composer (repository, mode, model and effort pickers, attachments, context) without the run view. */+export function EmbeddedTaskComposer(props: EmbeddedTaskComposerProps): JSX.Element {+ return (+ <Suspense+ fallback={+ <div className="flex items-center justify-center py-6">+ <Spinner className="text-2xl" />+ </div>+ }+ >+ <Lazy {...props} />+ </Suspense>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/EmbeddedTaskComposerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/EmbeddedTaskComposerImpl.tsxnew file mode 100644index 000000000000..85923389a9f1--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/EmbeddedTaskComposerImpl.tsx@@ -0,0 +1,20 @@+import { BindLogic } from 'kea'++import { TaskTrackerSceneLogicProps, taskTrackerSceneLogic } from '../taskTrackerSceneLogic'+import { TaskComposer } from './TaskComposer'++export type EmbeddedTaskComposerImplProps = Required<Pick<TaskTrackerSceneLogicProps, 'panelId'>> &+ Pick<TaskTrackerSceneLogicProps, 'channelId' | 'initialRepositoryConfig' | 'composerOverride' | 'onTaskCreated'>++/**+ * The new-task composer alone, for a host page that lists tasks itself. It binds an embedded+ * `taskTrackerSceneLogic` instance keyed by `panelId`, so it never shares a draft with the `/tasks` scene.+ * It never renders the run: the host opens the created task from `onTaskCreated`.+ */+export function EmbeddedTaskComposerImpl(props: EmbeddedTaskComposerImplProps): JSX.Element {+ return (+ <BindLogic logic={taskTrackerSceneLogic} props={props}>+ <TaskComposer variant="inline" />+ </BindLogic>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex 4e3b2172b649..61a4b995176a 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -35,7 +35,13 @@ import { OnboardingReplayButton } from '../../../components/onboarding/Onboardinimport { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { RepositorySelector } from './RepositorySelector'-export function TaskComposer(): JSX.Element {+export interface TaskComposerProps {+ /** `inline` drops the welcome header and the full-height centering, for a composer placed inside a host page. */+ variant?: 'page' | 'inline'+}++export function TaskComposer({ variant = 'page' }: TaskComposerProps): JSX.Element {+ const inline = variant === 'inline'const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion, clearConsentBlock } =useActions(taskTrackerSceneLogic)const {@@ -82,13 +88,23 @@ export function TaskComposer(): JSX.Element {}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={displayHeadline} subheadline={composerOverride?.subheadline}>- {/* Temporary migration affordance — delete with the rest of the onboarding takeover- once everyone is on the new PostHog AI. */}- {!composerOverride?.hideOnboardingReplay && <OnboardingReplayButton panelId={panelId} />}- </Welcome>+ <div+ className={+ inline+ ? 'flex flex-col'+ : 'flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4'+ }+ >+ <div+ className={inline ? 'w-full flex flex-col gap-4' : 'w-full max-w-2xl flex flex-col items-center gap-4'}+ >+ {!inline && (+ <Welcome headline={displayHeadline} subheadline={composerOverride?.subheadline}>+ {/* Temporary migration affordance — delete with the rest of the onboarding takeover+ once everyone is on the new PostHog AI. */}+ {!composerOverride?.hideOnboardingReplay && <OnboardingReplayButton panelId={panelId} />}+ </Welcome>+ )}<Suggestions.RootactiveGroup={activeSuggestionGroup}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 9764a0d4f752..3699151c343e 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -394,6 +394,8 @@ describe('taskTrackerSceneLogic', () => {repository: null,github_integration: null,})+ // Only a host that passes `channelId` files the task in a channel.+ expect(createBody).not.toHaveProperty('channel')// Interactive so the sandbox event stream survives across turns (follow-ups stream), and the// typed message is seeded as turn 1 (interactive runs boot with the agent pulling it from run// state). Dropping either regresses follow-up streaming / loses the first prompt.@@ -714,6 +716,45 @@ describe('taskTrackerSceneLogic', () => {expect(logic.values.newTaskData.repositoryConfig.integrationId).toBe(7)})+ // A channel host starts on its own repo instead of the remembered one, files the task in its channel, and+ // keeps the shared last-used repo intact.+ it('creates the task in the host channel from the host repository default', async () => {+ useMocks({+ get: {+ '/api/projects/:team/integrations/': {+ results: [{ id: 7, kind: 'github', display_name: 'acme', config: {} }],+ },+ },+ })+ localStorage.setItem(+ 'posthog_ai.tasks.lastRepositoryConfig',+ JSON.stringify({ integrationId: 7, repository: 'acme/remembered' })+ )+ const onTaskCreated = jest.fn()+ logic = taskTrackerSceneLogic({+ panelId: 'space-1',+ channelId: 'channel-1',+ initialRepositoryConfig: { integrationId: 7, repository: 'acme/space-repo' },+ onTaskCreated,+ })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.newTaskData.repositoryConfig).toEqual({ integrationId: 7, repository: 'acme/space-repo' })++ logic.actions.setNewTaskData({ description: 'ship it' })+ logic.actions.submitNewTask()+ await expectLogic(logic).toFinishAllListeners()++ expect(createBody).toMatchObject({+ channel: 'channel-1',+ repository: 'acme/space-repo',+ github_integration: 7,+ })+ expect(onTaskCreated).toHaveBeenCalledWith('new-task')+ expect(logic.values.newTaskData.repositoryConfig.repository).toBe('acme/space-repo')+ expect(logic.values.persistedRepositoryConfig).toEqual({ integrationId: 7, repository: 'acme/remembered' })+ })+// The side panel shares this logic, so a hidden picker can still hold a remembered repo. It must not reach the requests.it.each(['global', 'runner'])('keeps a repository hidden by a %s override out of requests', async (scope) => {useMocks({diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex f46c8932fe21..a3eeb2e6d628 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -91,6 +91,12 @@ export interface TaskTrackerSceneLogicProps {contextItems?: AttachedContextItem[]composerOverride?: ComposerOverridewelcomeHeadlines?: string[]+ /** Tasks channel that owns every task this composer creates. */+ channelId?: string+ /** Repository the composer starts from instead of the last-used one. The user can still change it. */+ initialRepositoryConfig?: PersistedRepositoryConfig+ /** Called with the created task's id after its run starts, so the host can open or list it. */+ onTaskCreated?: (taskId: string) => void}const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'@@ -619,7 +625,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// 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) {+ // A host default owns this composer's starting repo, so picks made here keep the shared memory intact.+ if (data.repositoryConfig?.repository && !props.initialRepositoryConfig) {const { integrationId, repository } = data.repositoryConfigactions.setPersistedRepositoryConfig({ integrationId, repository })}@@ -652,9 +659,12 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([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+ // Restore the host default or 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 initial = props.initialRepositoryConfig+ const { integrationId, repository } = initial?.repository+ ? { integrationId: initial.integrationId ?? githubIntegrations[0].id, repository: initial.repository }+ : values.persistedRepositoryConfigif (integrationId && githubIntegrations.some((integration) => integration.id === integrationId)) {actions.setNewTaskData({ repositoryConfig: { integrationId, repository } })return@@ -824,6 +834,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}: { initial_permission_mode: permissionMode }),pending_user_message: pendingUserMessage,+ ...(props.channelId ? { channel: props.channelId } : {}),}const newTask = await submitWithWarmRunRetry(@@ -937,6 +948,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([actions.submitNewTaskSuccess()actions.loadTasks(values.taskListParams)actions.loadRepositories()+ props.onTaskCreated?.(newTask.id)} catch (error) {if (disposables.isDisposed) {returndiff --git a/products/tasks/frontend/spaces/SpaceScene.tsx b/products/tasks/frontend/spaces/SpaceScene.tsxindex 7677213baa5c..2840283714be 100644--- a/products/tasks/frontend/spaces/SpaceScene.tsx+++ b/products/tasks/frontend/spaces/SpaceScene.tsx@@ -28,10 +28,19 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { spaceLabel } from '~/layout/today/todaySpacesLogic'+import { EmbeddedTaskComposer } from 'products/posthog_ai/frontend/api/runner'+import { SpaceFeed } from './SpaceFeed'import { SpaceSceneLogicProps, SpaceTab, spaceSceneLogic } from './spaceSceneLogic'import { SpaceSettings } from './SpaceSettings'+const SPACE_COMPOSER_OVERRIDE = {+ placeholder: 'What do you want to ship?',+ hideSuggestions: true,+ hideRecentTasks: true,+ hideOnboardingReplay: true,+}+export const scene: SceneExport<SpaceSceneLogicProps> = {component: SpaceScene,logic: spaceSceneLogic,@@ -40,10 +49,9 @@ export const scene: SceneExport<SpaceSceneLogicProps> = {export function SpaceScene({ id }: SpaceSceneLogicProps): JSX.Element {const enabled = useFeatureFlag('TODAY_RAIL_NAV')- const { space, spaceLoading, spaceUnavailable, spaceMissing, activeTab, savingSpace } = useValues(- spaceSceneLogic({ id })- )- const { setStarred, loadSpace } = useActions(spaceSceneLogic({ id }))+ const { space, spaceLoading, spaceUnavailable, spaceMissing, activeTab, savingSpace, composerRepositoryConfig } =+ useValues(spaceSceneLogic({ id }))+ const { setStarred, loadSpace, sessionStarted } = useActions(spaceSceneLogic({ id }))if (!enabled || spaceMissing) {return <NotFound object="space" />@@ -121,7 +129,22 @@ export function SpaceScene({ id }: SpaceSceneLogicProps): JSX.Element {</TabsTrigger></TabsList><TabsContent value="feed">- <SpaceFeed id={id} />+ <div className="flex max-w-3xl flex-col gap-4">+ {/* Mounted once the space loads, so the composer starts on the space's repository. */}+ {space && (+ <div data-attr="today-space-new-task">+ <EmbeddedTaskComposer+ key={space.id}+ panelId={`space-${space.id}`}+ channelId={space.id}+ initialRepositoryConfig={composerRepositoryConfig}+ composerOverride={SPACE_COMPOSER_OVERRIDE}+ onTaskCreated={sessionStarted}+ />+ </div>+ )}+ <SpaceFeed id={id} />+ </div></TabsContent><TabsContent value="settings"><SpaceSettings key={space?.id} id={id} />diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.test.ts b/products/tasks/frontend/spaces/spaceSceneLogic.test.tsindex 0e46dfdf7258..0fb94da5a408 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.test.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.test.ts@@ -1,3 +1,4 @@+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { todaySessionMenuLogic } from '~/layout/today/todaySessionMenuLogic'@@ -16,7 +17,13 @@ describe('spaceSceneLogic', () => {'/api/projects/:team_id/task_channels/': [],'/api/projects/:team_id/task_channels/:id/': ({ params }) => [200,- { id: params.id, name: String(params.id), system_role: null },+ {+ id: params.id,+ name: String(params.id),+ system_role: null,+ github_integration: params.id === 'space-a' ? 3 : null,+ repositories: params.id === 'space-a' ? ['acme/api', 'acme/web'] : [],+ },],'/api/projects/:team_id/task_channels/:id/members/': [{ id: 7, uuid: 'user-7', first_name: 'Ada', email: '[email protected]' },@@ -84,6 +91,29 @@ describe('spaceSceneLogic', () => {expect(logic.values.spaceUnavailable).toBe(true)})+ it.each([+ ['space-a', { integrationId: 3, repository: 'acme/api' }],+ ['space-b', undefined],+ ])('starts the new-session composer of %s on its first repository', async (id, expected) => {+ const logic = spaceSceneLogic({ id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.composerRepositoryConfig).toEqual(expected)+ })++ it('opens a started session and lists it in the feed', async () => {+ const logic = spaceSceneLogic({ id: 'space-a' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.sessionStarted('task-new')+ await expectLogic(logic).toDispatchActions(['loadSessions', 'loadSessionsSuccess'])++ expect(router.values.location.pathname).toMatch(/\/ai$/)+ expect(router.values.searchParams).toEqual({ task: 'task-new' })+ })+it('loads the members once the space turns private', async () => {const logic = spaceSceneLogic({ id: 'space-a' })logic.mount()diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.ts b/products/tasks/frontend/spaces/spaceSceneLogic.tsindex 3745de96b981..fd524db3a9c8 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.ts@@ -13,6 +13,8 @@ import { spaceLabel, todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { TodayWorkGroup, groupByDay, sessionItem } from '~/layout/today/todayWorkItems'import { Breadcrumb } from '~/types'+import type { EmbeddedTaskComposerProps } from 'products/posthog_ai/frontend/api/runner'+import {taskChannelsDestroy,taskChannelsMembersRetrieve,@@ -32,11 +34,14 @@ export interface SpaceSceneLogicProps {id: string}+export type SpaceComposerRepositoryConfig = EmbeddedTaskComposerProps['initialRepositoryConfig']+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface spaceSceneLogicValues {currentTeamId: number | null // teamLogicactiveTab: SpaceTabbreadcrumbs: Breadcrumb[]+ composerRepositoryConfig: SpaceComposerRepositoryConfigfeedGroups: TodayWorkGroup[]members: TaskUserBasicInfoApi[]membersLoading: boolean@@ -108,6 +113,9 @@ export interface spaceSceneLogicActions {savingFinished: () => {value: true}+ sessionStarted: (sessionId: string) => {+ sessionId: string+ }setMemberIds: (userIds: number[]) => number[]setMemberIdsFailure: (error: string,@@ -142,6 +150,7 @@ export interface spaceSceneLogicMeta {feedGroups: (sessions: TaskListItemApi[]) => TodayWorkGroup[]sessionsById: (sessions: TaskListItemApi[]) => Record<string, TaskListItemApi>breadcrumbs: (space: ChannelDTOApi | null, arg: any) => Breadcrumb[]+ composerRepositoryConfig: (space: ChannelDTOApi | null) => SpaceComposerRepositoryConfig}}@@ -166,6 +175,7 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([deleteSpace: true,spaceSaved: (space: ChannelDTOApi) => ({ space }),savingFinished: true,+ sessionStarted: (sessionId: string) => ({ sessionId }),}),loaders(({ props, values }) => ({space: [@@ -253,11 +263,24 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([},],],+ // The new-session composer starts on the space's first repository.+ composerRepositoryConfig: [+ (s) => [s.space],+ (space: ChannelDTOApi | null): SpaceComposerRepositoryConfig =>+ space?.repositories.length+ ? { integrationId: space.github_integration ?? undefined, repository: space.repositories[0] }+ : undefined,+ ],}),listeners(({ actions, props, values }) => ({sessionUpdated: () => {actions.loadSessions()},+ // Open the new session like the web's new-session composer does, and list it for when the user comes back.+ sessionStarted: ({ sessionId }) => {+ actions.loadSessions()+ router.actions.push(urls.aiTask(sessionId))+ },loadSpaceSuccess: ({ space }) => {if (space?.channel_type === 'private') {actions.loadMembers()