: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(llma): community skills browse UI (3/7) (#65012)
Andrew Maguire7e49646aef00
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.mdindex 22110cac0f63..5ea30d9dc1ff 100644--- a/docs/internal/skills/community-skills-api.md+++ b/docs/internal/skills/community-skills-api.md@@ -14,11 +14,9 @@ Route: registered in `products/skills/backend/routes.py` as `community_skills` u- Web-app session auth only (`scope_object = "INTERNAL"`); the endpoint is **not** exposed forpersonal-API-key scoping, since the catalog is instance-global.-- Gated by `CommunitySkillFeatureFlagPermission`, which requires **both**- `llm-analytics-community-skills` (the marketplace) and `llm-analytics-skills` (the base skills- product the installed skill lands in) to be enabled.- The flag is evaluated with the organization **and** project group so a per-project rollout matches- in-app evaluation, and `POSTHOG_FEATURE_FLAGS_FORCE_ENABLED` is honored for self-hosted.+- Gated by `CommunitySkillFeatureFlagPermission`, which requires `llm-analytics-community-skills` alone.+ Skills went GA in June 2026 and the `llm-analytics-skills` flag was removed with it, so there is no base-product flag left to check.+ The flag is evaluated with the organization **and** project group so a per-project rollout matches in-app evaluation, and `POSTHOG_FEATURE_FLAGS_FORCE_ENABLED` is honored for self-hosted.- `install` and `vote` additionally require resource-level `editor` access on `llm_skill`, and arerate-limited by a burst + sustained throttle.diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 150c902c0119..04fba2680942 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -350,6 +350,7 @@ export const FEATURE_FLAGS = {LIVE_DEBUGGER: 'live-debugger', // owner: @marcecollLIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analyticsLLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observability+ LLM_ANALYTICS_COMMUNITY_SKILLS: 'llm-analytics-community-skills', // owner: #team-ai-observabilityLLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-aiLLM_ANALYTICS_EVAL_SETTLING_STRATEGY: 'llm-analytics-eval-settling-strategy', // owner: #team-ai-observabilityLLM_ANALYTICS_EVALUATIONS_START_WITH_AI: 'llm-analytics-evaluations-start-with-ai', // owner: #team-ai-observabilitydiff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex e32eaff4dcaf..ee2a19bba4bc 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -133,6 +133,7 @@ export const productScenes: Record<string, () => Promise<any>> = {Inbox: () => import('../../products/signals/frontend/inbox/InboxScene'),Skills: () => import('../../products/skills/frontend/LLMSkillsScene'),Skill: () => import('../../products/skills/frontend/LLMSkillScene'),+ CommunitySkills: () => import('../../products/skills/frontend/CommunitySkillsScene'),Stamphog: () => import('../../products/stamphog/frontend/scenes/StamphogScene/StamphogScene'),StreamlitApps: () => import('../../products/streamlit_apps/frontend/StreamlitApps'),StreamlitApp: () => import('../../products/streamlit_apps/frontend/StreamlitApp'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex fe9a90d66790..55a54ba575a5 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -223,6 +223,7 @@ export const productRoutes: Record<string, [string, string]> = {'/skills': ['Skills', 'skills'],'/skills/scouts': ['Skills', 'skillsScouts'],'/skills/review-hog': ['Skills', 'skillsReviewHog'],+ '/community-skills': ['CommunitySkills', 'communitySkills'],'/skills/:name': ['Skill', 'skill'],'/stamphog': ['Stamphog', 'stamphog'],'/stamphog/install/callback': ['Stamphog', 'stamphogCallback'],@@ -874,6 +875,13 @@ export const productConfiguration: Record<string, any> = {iconType: 'llm_prompts',},Skill: { projectBased: true, name: 'Skill', layout: 'app-container', iconType: 'llm_prompts' },+ CommunitySkills: {+ projectBased: true,+ name: 'Community skills',+ description: 'Discover and install agent skills shared by the PostHog community.',+ layout: 'app-container',+ iconType: 'llm_prompts',+ },Stamphog: { projectBased: true, name: 'Stamphog', iconType: 'stamphog' },StreamlitApps: { name: 'Streamlit apps', projectBased: true },StreamlitApp: { name: 'Streamlit app', projectBased: true },@@ -1428,6 +1436,7 @@ export const productUrls = {version?: number}): string => combineUrl(`/skills/${name}`, params).url,+ communitySkills: (): string => '/community-skills',stamphog: (): string => '/stamphog',stamphogCallback: (): string => '/stamphog/install/callback',streamlitApps: (): string => '/streamlit-apps',@@ -2387,7 +2396,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,href: urls.skills(),sceneKey: 'Skills',- sceneKeys: ['Skills', 'Skill'],+ sceneKeys: ['Skills', 'Skill', 'CommunitySkills'],},{path: 'Support',diff --git a/products/skills/backend/api/community_skills.py b/products/skills/backend/api/community_skills.pyindex d5c4391daf59..61b74a9092cb 100644--- a/products/skills/backend/api/community_skills.py+++ b/products/skills/backend/api/community_skills.py@@ -38,9 +38,6 @@ from .skill_services import LLMSkillDuplicateNameConflictError, LLMSkillFileLimilogger = structlog.get_logger(__name__)COMMUNITY_SKILL_FEATURE_FLAG = "llm-analytics-community-skills"-# Installing copies into a regular LLMSkill, whose UI and APIs are gated by this base flag — so the-# marketplace also requires it, otherwise installed skills would be unreachable.-BASE_SKILL_FEATURE_FLAG = "llm-analytics-skills"class CommunitySkillBurstThrottle(PersonalApiKeyOrUserRateThrottle):@@ -77,19 +74,18 @@ class CommunitySkillFeatureFlagPermission(BasePermission):# Honor POSTHOG_FEATURE_FLAGS_FORCE_ENABLED so self-hosted deployments can enable the# marketplace without a round-trip to PostHog Cloud, matching the canonical permission.- return all(- flag in _FORCE_ENABLED_FLAGS- or bool(- posthoganalytics.feature_enabled(- flag,- distinct_id,- groups=groups,- group_properties=group_properties,- only_evaluate_locally=False,- send_feature_flag_events=False,- )+ if COMMUNITY_SKILL_FEATURE_FLAG in _FORCE_ENABLED_FLAGS:+ return True++ return bool(+ posthoganalytics.feature_enabled(+ COMMUNITY_SKILL_FEATURE_FLAG,+ distinct_id,+ groups=groups,+ group_properties=group_properties,+ only_evaluate_locally=False,+ send_feature_flag_events=False,)- for flag in (COMMUNITY_SKILL_FEATURE_FLAG, BASE_SKILL_FEATURE_FLAG))diff --git a/products/skills/backend/api/test/test_community_skills.py b/products/skills/backend/api/test/test_community_skills.pyindex 3a72b520335b..28f0cfaeafb6 100644--- a/products/skills/backend/api/test/test_community_skills.py+++ b/products/skills/backend/api/test/test_community_skills.py@@ -223,3 +223,24 @@ class TestCommunitySkillWriteAccess(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)self.assertFalse(LLMSkill.objects.filter(team=self.team).exists())self.assertFalse(CommunitySkillVote.objects.exists())+++class TestCommunitySkillFeatureFlagGate(APIBaseTest):+ @parameterized.expand(+ [+ ("only_community_flag_enabled", {"llm-analytics-community-skills"}, status.HTTP_200_OK),+ ("no_flags_enabled", set(), status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_gate_depends_only_on_the_community_flag(+ self, _name: str, enabled_flags: set[str], expected_status: int+ ) -> None:+ _create_community_skill(slug="web-analytics-triage")++ with patch(+ "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled",+ side_effect=lambda flag, *args, **kwargs: flag in enabled_flags,+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/community_skills/")++ self.assertEqual(response.status_code, expected_status, response.content)diff --git a/products/skills/frontend/CommunitySkillsScene.tsx b/products/skills/frontend/CommunitySkillsScene.tsxnew file mode 100644index 000000000000..43193b6636c2--- /dev/null+++ b/products/skills/frontend/CommunitySkillsScene.tsx@@ -0,0 +1,197 @@+import { useActions, useValues } from 'kea'++import { IconGithub, IconThumbsUp } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'+import { PaginationControl } from 'lib/lemon-ui/PaginationControl'+import { usePagination } from 'lib/lemon-ui/PaginationControl/usePagination'+import { SceneExport } from 'scenes/sceneTypes'++import { ProductKey } from '~/queries/schema/schema-general'++import { communitySkillsLogic } from './communitySkillsLogic'+import { TrustTierEnumApi } from './generated/api.schemas'+import type { CommunitySkillListApi } from './generated/api.schemas'+import { SkillsSceneShell } from './SkillsSceneShell'++export const scene: SceneExport = {+ component: CommunitySkillsScene,+ logic: communitySkillsLogic,+ productKey: ProductKey.AI_OBSERVABILITY,+}++const SKILL_GRID_CLASSES = 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4'++const TRUST_TIER_TAG: Record<TrustTierEnumApi, { label: string; type: LemonTagType }> = {+ official: { label: 'Official', type: 'success' },+ verified: { label: 'Verified', type: 'completion' },+ community: { label: 'Community', type: 'default' },+}++// GitHub usernames are alphanumeric with single inner hyphens, up to 39 characters.+const GITHUB_HANDLE = /^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$/++// The registry stores github_url and author_handle without checking either, so anything we turn+// into a link has to be validated here before a user is invited to click it.+function githubSourceUrl(url: string): string | null {+ try {+ const parsed = new URL(url)+ return parsed.protocol === 'https:' && parsed.hostname === 'github.com' ? parsed.toString() : null+ } catch {+ return null+ }+}++function TrustTierBadge({ tier }: { tier: TrustTierEnumApi }): JSX.Element {+ const config = TRUST_TIER_TAG[tier] ?? TRUST_TIER_TAG.community+ return <LemonTag type={config.type}>{config.label}</LemonTag>+}++// author_handle is the contributor's GitHub username (from the skill's PR/frontmatter).+function AuthorHandle({ handle }: { handle: string }): JSX.Element {+ if (!GITHUB_HANDLE.test(handle)) {+ return <span>@{handle}</span>+ }+ return (+ <Link to={`https://github.com/${handle}`} target="_blank">+ @{handle}+ </Link>+ )+}++function CommunitySkillCard({ skill }: { skill: CommunitySkillListApi }): JSX.Element {+ const { installingSlugs, votingSlugs } = useValues(communitySkillsLogic)+ const { installSkill, toggleVote } = useActions(communitySkillsLogic)+ const installing = !!installingSlugs[skill.slug]+ const voting = !!votingSlugs[skill.slug]+ const sourceUrl = skill.github_url ? githubSourceUrl(skill.github_url) : null++ return (+ <div className="flex flex-col gap-2 border rounded p-4 bg-bg-light h-full">+ <div className="flex items-start justify-between gap-2">+ <h3 className="font-semibold m-0">{skill.name}</h3>+ <TrustTierBadge tier={skill.trust_tier} />+ </div>+ <p className="text-muted text-sm grow line-clamp-3">{skill.description}</p>+ <div className="flex flex-wrap gap-1">+ {(skill.tags ?? []).slice(0, 4).map((tag) => (+ <LemonTag key={tag} type="muted" size="small">+ {tag}+ </LemonTag>+ ))}+ </div>+ <div className="flex items-center justify-between gap-2 pt-2 border-t">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-muted text-xs">+ <span>{skill.install_count} installs</span>+ {skill.author_handle ? <AuthorHandle handle={skill.author_handle} /> : null}+ {sourceUrl ? (+ <Link to={sourceUrl} target="_blank" className="flex items-center gap-1">+ <IconGithub /> View on GitHub+ </Link>+ ) : null}+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconThumbsUp />}+ active={skill.has_voted}+ loading={voting}+ disabledReason={voting ? 'Saving your vote…' : undefined}+ onClick={() => toggleVote(skill.slug)}+ tooltip={skill.has_voted ? 'Remove your vote' : 'Upvote this skill'}+ >+ {skill.vote_count}+ </LemonButton>+ <LemonButton+ size="small"+ type="primary"+ loading={installing}+ disabledReason={installing ? 'Installing…' : undefined}+ onClick={() => installSkill(skill.slug)}+ >+ Install+ </LemonButton>+ </div>+ </div>+ </div>+ )+}++function CommunitySkillsGrid({ skills, loading }: { skills: CommunitySkillListApi[]; loading: boolean }): JSX.Element {+ if (loading && skills.length === 0) {+ return (+ <div className={SKILL_GRID_CLASSES}>+ {Array.from({ length: 6 }, (_, index) => (+ <LemonSkeleton key={index} className="h-40 w-full" />+ ))}+ </div>+ )+ }++ if (skills.length === 0) {+ return <div className="text-muted text-center p-8">No community skills match your filters yet.</div>+ }++ return (+ <div className={SKILL_GRID_CLASSES}>+ {skills.map((skill) => (+ <CommunitySkillCard key={skill.slug} skill={skill} />+ ))}+ </div>+ )+}++export function CommunitySkillsScene(): JSX.Element {+ return <SkillsSceneShell activeTab="community" content={<CommunitySkillsContent />} />+}++function CommunitySkillsContent(): JSX.Element {+ const { displaySkills, filters, pagination, skillsLoading } = useValues(communitySkillsLogic)+ const { setFilters } = useActions(communitySkillsLogic)+ // Controlled pagination: page changes write the `page` URL param, which urlToAction turns into setFilters.+ const paginationState = usePagination(displaySkills, pagination)++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-wrap items-center gap-2">+ <LemonInput+ type="search"+ placeholder="Search skills…"+ value={filters.search}+ onChange={(search) => setFilters({ search })}+ className="grow max-w-100"+ />+ <LemonSelect<TrustTierEnumApi | ''>+ value={filters.trust_tier}+ onChange={(trust_tier) => setFilters({ trust_tier })}+ options={[+ { value: '', label: 'All tiers' },+ { value: 'official', label: 'Official' },+ { value: 'verified', label: 'Verified' },+ { value: 'community', label: 'Community' },+ ]}+ />+ <LemonSelect+ value={filters.order_by}+ onChange={(order_by) => setFilters({ order_by })}+ options={[+ { value: '-install_count', label: 'Most installed' },+ { value: '-vote_count', label: 'Top rated' },+ { value: '-published_at', label: 'Newest' },+ { value: 'name', label: 'Name (A–Z)' },+ ]}+ />+ </div>++ <CommunitySkillsGrid skills={displaySkills} loading={skillsLoading} />++ <PaginationControl {...paginationState} nouns={['skill', 'skills']} />+ </div>+ )+}diff --git a/products/skills/frontend/LLMSkillsScene.tsx b/products/skills/frontend/LLMSkillsScene.tsxindex 601d645fc4b4..c2a46ee35430 100644--- a/products/skills/frontend/LLMSkillsScene.tsx+++ b/products/skills/frontend/LLMSkillsScene.tsx@@ -8,6 +8,7 @@ import { LemonDivider, LemonModal, LemonSwitch, LemonTabs, LemonTag, Link } fromimport { AccessControlAction } from 'lib/components/AccessControlAction'import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'import { MemberSelect } from 'lib/components/MemberSelect'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -15,11 +16,10 @@ import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Spinner } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'-import { SceneContent } from '~/layout/scenes/components/SceneContent'-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { LemonDialog } from '~/lib/lemon-ui/LemonDialog'import { LemonField } from '~/lib/lemon-ui/LemonField'import { LemonInput } from '~/lib/lemon-ui/LemonInput'@@ -41,6 +41,7 @@ import {} from './llmSkillsLogic'import { SKILL_NAME_MAX_LENGTH, validateSkillName } from './skillConstants'import { openArchiveSkillDialog } from './skillSceneComponents'+import { SkillsSceneShell } from './SkillsSceneShell'export const scene: SceneExport = {component: LLMSkillsScene,@@ -442,11 +443,15 @@ export function LLMSkillsScene(): JSX.Element {activeTabDescription,visibleCategoryTabs,} = useValues(llmSkillsLogic)+ const { featureFlags } = useValues(featureFlagLogic)const { searchParams } = useValues(router)const skillUrl = (name: string): string => combineUrl(urls.skill(name), searchParams).urlconst fileInputRef = useRef<HTMLInputElement | null>(null)const showScoutOrigin = activeCategory === 'scout'+ const communitySkillsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_COMMUNITY_SKILLS]+ // Discovery CTA: when a project has no skills of its own yet, point first-timers at the community catalog.+ const showCommunityDiscovery = communitySkillsEnabled && !skillsLoading && skills.count === 0 && !filters.search// Memoize columns so the array reference doesn't change every render — otherwise every// nested LemonTable inside the grouped tree reconciles on each parent re-render.@@ -460,8 +465,8 @@ export function LLMSkillsScene(): JSX.Element {const showGroupedLoadingSkeleton = filters.group_by_prefix && skillsLoadingconst truncated = filters.group_by_prefix && skills.count > skills.results.length- return (- <SceneContent>+ const content = (+ <><inputref={fileInputRef}type="file"@@ -478,53 +483,16 @@ export function LLMSkillsScene(): JSX.Element {}}/><ConnectToClaudeCodeModal />- <SceneTitleSection- name="Skills"- description={activeTabDescription}- resourceType={{ type: 'llm_analytics' }}- actions={- <>- <LemonButton- type="secondary"- size="small"- onClick={() => setConnectModalOpen(true)}- data-attr="connect-coding-agent-button"- >- Load skills in your agent- </LemonButton>- <AccessControlAction- resourceType={AccessControlResourceType.LlmSkill}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="secondary"- size="small"- icon={<IconUpload />}- onClick={() => fileInputRef.current?.click()}- loading={importing}- data-attr="import-skill-button"- tooltip="Import a skill from a spec-compliant .zip"- >- Import- </LemonButton>- </AccessControlAction>- <AccessControlAction- resourceType={AccessControlResourceType.LlmSkill}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- size="small"- to={skillUrl('new')}- icon={<IconPlusSmall />}- data-attr="new-skill-button"- >- New skill- </LemonButton>- </AccessControlAction>- </>- }- />++ {showCommunityDiscovery && (+ <LemonBanner+ type="info"+ action={{ children: 'Browse community', to: urls.communitySkills() }}+ data-attr="skills-community-discovery-banner"+ >+ No skills yet — explore agent skills shared by the PostHog community and install them in one click.+ </LemonBanner>+ )}{visibleCategoryTabs.length > 0 && (<LemonTabs@@ -613,6 +581,56 @@ export function LLMSkillsScene(): JSX.Element {/>)}</div>- </SceneContent>+ </>+ )++ return (+ <SkillsSceneShell+ activeTab="your"+ description={activeTabDescription}+ actions={+ <>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setConnectModalOpen(true)}+ data-attr="connect-coding-agent-button"+ >+ Load skills in your agent+ </LemonButton>+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconUpload />}+ onClick={() => fileInputRef.current?.click()}+ loading={importing}+ data-attr="import-skill-button"+ tooltip="Import a skill from a spec-compliant .zip"+ >+ Import+ </LemonButton>+ </AccessControlAction>+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ size="small"+ to={skillUrl('new')}+ icon={<IconPlusSmall />}+ data-attr="new-skill-button"+ >+ New skill+ </LemonButton>+ </AccessControlAction>+ </>+ }+ content={content}+ />)}diff --git a/products/skills/frontend/SkillsSceneShell.tsx b/products/skills/frontend/SkillsSceneShell.tsxnew file mode 100644index 000000000000..ba23b53db880--- /dev/null+++ b/products/skills/frontend/SkillsSceneShell.tsx@@ -0,0 +1,76 @@+import { useValues } from 'kea'++import { LemonTab, LemonTabs } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++export type SkillsTab = 'your' | 'community'++const TAB_DESCRIPTIONS: Record<SkillsTab, string> = {+ your: 'Manage versioned agent skills that any MCP-connected agent can discover and use.',+ community: 'Discover and install agent skills shared by the PostHog community.',+}++/**+ * Shared shell for the two Skills tabs ("Your skills" and "Community"). Each scene renders this+ * with only its own tab's content; the inactive tab navigates via its `link`, so its content is+ * never mounted here. This keeps the two scenes' logics (and URL contracts) independent while+ * presenting them as one tabbed surface. The Community tab is gated behind the community-skills+ * flag (but stays visible when it's already the active tab, so a direct URL still renders cleanly).+ */+export function SkillsSceneShell({+ activeTab,+ actions,+ description,+ content,+}: {+ activeTab: SkillsTab+ actions?: JSX.Element+ description?: string+ content: JSX.Element+}): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const communityEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_COMMUNITY_SKILLS]++ const tabs: LemonTab<SkillsTab>[] = [+ {+ key: 'your',+ label: 'Your skills',+ link: urls.skills(),+ content: activeTab === 'your' ? content : <></>,+ },+ ...(communityEnabled || activeTab === 'community'+ ? [+ {+ key: 'community' as SkillsTab,+ label: 'Community',+ link: urls.communitySkills(),+ content: activeTab === 'community' ? content : <></>,+ },+ ]+ : []),+ ]++ return (+ <SceneContent>+ <SceneTitleSection+ name="Skills"+ description={description ?? TAB_DESCRIPTIONS[activeTab]}+ resourceType={{ type: 'llm_analytics' }}+ actions={actions}+ />+ {/* Only surface the tab bar once Community is reachable — otherwise the lone "Your skills"+ tab is noise, so flag-off users see the plain Skills scene exactly as before. */}+ {tabs.length > 1 ? (+ <LemonTabs activeKey={activeTab} data-attr="skills-tabs" tabs={tabs} sceneInset />+ ) : (+ content+ )}+ </SceneContent>+ )+}diff --git a/products/skills/frontend/communitySkillsLogic.test.ts b/products/skills/frontend/communitySkillsLogic.test.tsnew file mode 100644index 000000000000..633181423248--- /dev/null+++ b/products/skills/frontend/communitySkillsLogic.test.ts@@ -0,0 +1,71 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { ApiError } from '~/lib/api-error'+import { urls } from '~/scenes/urls'+import { initKeaTests } from '~/test/init'++import { communitySkillsLogic } from './communitySkillsLogic'+import { communitySkillsInstallCreate, communitySkillsList } from './generated/api'++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { error: jest.fn(), success: jest.fn(), info: jest.fn() },+}))++jest.mock('./generated/api', () => ({+ communitySkillsInstallCreate: jest.fn(),+ communitySkillsList: jest.fn(),+ communitySkillsVoteCreate: jest.fn(),+}))++const mockList = communitySkillsList as jest.MockedFunction<typeof communitySkillsList>+const mockInstall = communitySkillsInstallCreate as jest.MockedFunction<typeof communitySkillsInstallCreate>++describe('communitySkillsLogic', () => {+ let logic: ReturnType<typeof communitySkillsLogic.build>++ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ mockList.mockResolvedValue({ results: [], count: 0 })+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('ignores a trust tier the API does not define', async () => {+ logic = communitySkillsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSkillsSuccess'])++ router.actions.push(urls.communitySkills(), { trust_tier: 'platinum' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.filters.trust_tier).toBe('')+ expect(mockList).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ trust_tier: undefined }))+ })++ it.each([+ [+ 'the backend explanation when there is one',+ new ApiError('Bad request', 400, undefined, {+ detail: 'A skill named "make-pr" is already installed in your project.',+ }),+ 'A skill named "make-pr" is already installed in your project.',+ ],+ ['generic copy otherwise', new Error('network down'), 'Could not install the skill. Try again in a moment.'],+ ])('failing to install reports %s', async (_name, error, expectedMessage) => {+ mockInstall.mockRejectedValue(error)+ logic = communitySkillsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSkillsSuccess'])++ logic.actions.installSkill('make-pr')+ await expectLogic(logic).toDispatchActions(['installSkillFailure'])++ expect(lemonToast.error).toHaveBeenCalledWith(expectedMessage)+ })+})diff --git a/products/skills/frontend/communitySkillsLogic.ts b/products/skills/frontend/communitySkillsLogic.tsnew file mode 100644index 000000000000..0c009779869f--- /dev/null+++ b/products/skills/frontend/communitySkillsLogic.ts@@ -0,0 +1,342 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'++import { objectsEqual } from 'lib/utils/objects'++import { ApiConfig, ApiError } from '~/lib/api'+import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'+import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'+import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'+import { urls } from '~/scenes/urls'++import { communitySkillsInstallCreate, communitySkillsList, communitySkillsVoteCreate } from './generated/api'+import { TrustTierEnumApi } from './generated/api.schemas'+import type { CommunitySkillListApi, PaginatedCommunitySkillListListApi } from './generated/api.schemas'++export const COMMUNITY_SKILLS_PER_PAGE = 30++const TRUST_TIERS = Object.values(TrustTierEnumApi)++export interface CommunitySkillFilters {+ page: number+ search: string+ order_by: string+ tag: string+ trust_tier: TrustTierEnumApi | ''+}++// Filters can arrive from the URL, so anything that isn't a known tier falls back to "all tiers".+function cleanTrustTier(value: unknown): TrustTierEnumApi | '' {+ return TRUST_TIERS.find((tier) => tier === value) ?? ''+}++function cleanFilters(values: Partial<CommunitySkillFilters>): CommunitySkillFilters {+ return {+ page: parseInt(String(values.page)) || 1,+ search: String(values.search || ''),+ order_by: values.order_by || '-install_count',+ tag: String(values.tag || ''),+ trust_tier: cleanTrustTier(values.trust_tier),+ }+}++function cleanFilterUrlParams(filters: CommunitySkillFilters): Record<string, unknown> {+ return {+ page: filters.page === 1 ? undefined : filters.page,+ search: filters.search || undefined,+ order_by: filters.order_by === '-install_count' ? undefined : filters.order_by,+ tag: filters.tag || undefined,+ trust_tier: filters.trust_tier || undefined,+ }+}++export type CommunitySkillsLogicProps = Record<string, never>++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface communitySkillsLogicValues {+ count: number+ displaySkills: CommunitySkillListApi[]+ filters: CommunitySkillFilters+ installingSlugs: Record<string, boolean>+ pagination: PaginationManual+ rawFilters: Partial<CommunitySkillFilters> | null+ skills: PaginatedCommunitySkillListListApi+ skillsLoading: boolean+ voteOverrides: Record<+ string,+ {+ has_voted: boolean+ vote_count: number+ }+ >+ votingSlugs: Record<string, boolean>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface communitySkillsLogicActions {+ installSkill: (+ slug: string,+ newName?: string+ ) => {+ newName: string | undefined+ slug: string+ }+ installSkillFailure: (slug: string) => {+ slug: string+ }+ installSkillSuccess: (slug: string) => {+ slug: string+ }+ loadSkills: (debounce?: boolean) => {+ debounce: boolean+ }+ loadSkillsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSkillsSuccess: (+ skills: PaginatedCommunitySkillListListApi,+ payload?: {+ debounce: boolean+ }+ ) => {+ skills: PaginatedCommunitySkillListListApi+ payload?: {+ debounce: boolean+ }+ }+ setFilters: (+ filters: Partial<CommunitySkillFilters>,+ merge?: boolean,+ debounce?: boolean+ ) => {+ debounce: boolean+ filters: Partial<CommunitySkillFilters>+ merge: boolean+ }+ toggleVote: (slug: string) => {+ slug: string+ }+ toggleVoteFailure: (slug: string) => {+ slug: string+ }+ toggleVoteSuccess: (+ slug: string,+ voteResult: {+ has_voted: boolean+ vote_count: number+ }+ ) => {+ slug: string+ voteResult: {+ has_voted: boolean+ vote_count: number+ }+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface communitySkillsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ filters: (rawFilters: Partial<CommunitySkillFilters> | null) => CommunitySkillFilters+ count: (skills: PaginatedCommunitySkillListListApi) => number+ displaySkills: (+ skills: PaginatedCommunitySkillListListApi,+ voteOverrides: Record<+ string,+ {+ has_voted: boolean+ vote_count: number+ }+ >+ ) => CommunitySkillListApi[]+ pagination: (filters: CommunitySkillFilters, count: number) => PaginationManual+ }+}++export type communitySkillsLogicType = MakeLogicType<+ communitySkillsLogicValues,+ communitySkillsLogicActions,+ CommunitySkillsLogicProps,+ communitySkillsLogicMeta+>++export const communitySkillsLogic = kea<communitySkillsLogicType>([+ path(['scenes', 'skills', 'communitySkillsLogic']),+ props({} as CommunitySkillsLogicProps),++ actions({+ setFilters: (filters: Partial<CommunitySkillFilters>, merge: boolean = true, debounce: boolean = true) => ({+ filters,+ merge,+ debounce,+ }),+ loadSkills: (debounce: boolean = true) => ({ debounce }),+ installSkill: (slug: string, newName?: string) => ({ slug, newName }),+ installSkillSuccess: (slug: string) => ({ slug }),+ installSkillFailure: (slug: string) => ({ slug }),+ toggleVote: (slug: string) => ({ slug }),+ toggleVoteSuccess: (slug: string, voteResult: { has_voted: boolean; vote_count: number }) => ({+ slug,+ voteResult,+ }),+ toggleVoteFailure: (slug: string) => ({ slug }),+ }),++ reducers({+ rawFilters: [+ null as Partial<CommunitySkillFilters> | null,+ {+ setFilters: (state, { filters, merge }) =>+ cleanFilters({+ ...(merge ? state || {} : {}),+ ...filters,+ ...('page' in filters ? {} : { page: 1 }),+ }),+ },+ ],+ // Optimistic per-slug vote state keyed by slug, merged over the server values for snappy UI.+ voteOverrides: [+ {} as Record<string, { has_voted: boolean; vote_count: number }>,+ {+ toggleVoteSuccess: (state, { slug, voteResult }) => ({ ...state, [slug]: voteResult }),+ },+ ],+ installingSlugs: [+ {} as Record<string, boolean>,+ {+ installSkill: (state, { slug }) => ({ ...state, [slug]: true }),+ installSkillSuccess: (state, { slug }) => ({ ...state, [slug]: false }),+ installSkillFailure: (state, { slug }) => ({ ...state, [slug]: false }),+ },+ ],+ votingSlugs: [+ {} as Record<string, boolean>,+ {+ toggleVote: (state, { slug }) => ({ ...state, [slug]: true }),+ toggleVoteSuccess: (state, { slug }) => ({ ...state, [slug]: false }),+ toggleVoteFailure: (state, { slug }) => ({ ...state, [slug]: false }),+ },+ ],+ }),++ loaders(({ values }) => ({+ skills: [+ { results: [], count: 0 } as PaginatedCommunitySkillListListApi,+ {+ loadSkills: async ({ debounce }, breakpoint) => {+ // The delay debounces typing and filter changes. Mount and URL entry pass+ // debounce=false so the first load isn't held back by it.+ await breakpoint(debounce ? 300 : 0)+ const { filters } = values+ const response = await communitySkillsList(String(ApiConfig.getCurrentTeamId()), {+ search: filters.search,+ order_by: filters.order_by,+ tag: filters.tag,+ trust_tier: filters.trust_tier || undefined,+ offset: Math.max(0, (filters.page - 1) * COMMUNITY_SKILLS_PER_PAGE),+ limit: COMMUNITY_SKILLS_PER_PAGE,+ })+ // Discard this response if newer filters started another load while it was in flight.+ breakpoint()+ return response+ },+ },+ ],+ })),++ selectors({+ filters: [+ (s) => [s.rawFilters],+ (rawFilters: Partial<CommunitySkillFilters> | null): CommunitySkillFilters =>+ cleanFilters(rawFilters || {}),+ ],+ count: [(s) => [s.skills], (skills: PaginatedCommunitySkillListListApi) => skills.count],+ // Server results with optimistic vote overrides applied.+ displaySkills: [+ (s) => [s.skills, s.voteOverrides],+ (+ skills: PaginatedCommunitySkillListListApi,+ voteOverrides: Record<string, { has_voted: boolean; vote_count: number }>+ ): CommunitySkillListApi[] =>+ skills.results.map((skill) => {+ const override = voteOverrides[skill.slug]+ return override ? { ...skill, ...override } : skill+ }),+ ],+ pagination: [+ (s) => [s.filters, s.count],+ (filters: CommunitySkillFilters, count: number): PaginationManual => ({+ controlled: true,+ pageSize: COMMUNITY_SKILLS_PER_PAGE,+ currentPage: filters.page,+ entryCount: count,+ }),+ ],+ }),++ listeners(({ actions, asyncActions, values, selectors }) => ({+ setFilters: async ({ debounce }, _, __, previousState) => {+ const oldFilters = selectors.filters(previousState)+ if (!objectsEqual(oldFilters, values.filters)) {+ await asyncActions.loadSkills(debounce)+ }+ },++ installSkill: async ({ slug, newName }) => {+ try {+ await communitySkillsInstallCreate(String(ApiConfig.getCurrentTeamId()), slug, {+ new_name: newName,+ })+ lemonToast.success(`Installed "${newName || slug}" into your project.`)+ actions.installSkillSuccess(slug)+ router.actions.push(urls.skill(newName || slug))+ } catch (e) {+ console.error('Failed to install community skill', e)+ const detail = e instanceof ApiError ? e.detail : null+ lemonToast.error(detail || 'Could not install the skill. Try again in a moment.')+ actions.installSkillFailure(slug)+ }+ },++ toggleVote: async ({ slug }) => {+ try {+ const result = await communitySkillsVoteCreate(String(ApiConfig.getCurrentTeamId()), slug)+ actions.toggleVoteSuccess(slug, result)+ } catch (e) {+ console.error('Failed to vote on community skill', e)+ const detail = e instanceof ApiError ? e.detail : null+ lemonToast.error(detail || 'Could not save your vote. Try again in a moment.')+ actions.toggleVoteFailure(slug)+ }+ },+ })),++ trackedActionToUrl(({ values }) => {+ const changeUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] | void => {+ const nextValues = cleanFilterUrlParams(values.filters)+ const urlValues = cleanFilters(router.values.searchParams)+ if (!objectsEqual(values.filters, urlValues)) {+ return [urls.communitySkills(), nextValues, {}, { replace: true }]+ }+ }+ return { setFilters: changeUrl }+ }),++ urlToAction(({ actions, values }) => ({+ [urls.communitySkills()]: (_, searchParams) => {+ const newFilters = cleanFilters(searchParams)+ if (!objectsEqual(values.filters, newFilters)) {+ actions.setFilters(newFilters, false, false)+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadSkills(false)+ }),+])diff --git a/products/skills/manifest.tsx b/products/skills/manifest.tsxindex 6c486640daa0..c22c92e2a1d7 100644--- a/products/skills/manifest.tsx+++ b/products/skills/manifest.tsx@@ -24,6 +24,14 @@ export const manifest: ProductManifest = {layout: 'app-container',iconType: 'llm_prompts',},+ CommunitySkills: {+ import: () => import('./frontend/CommunitySkillsScene'),+ projectBased: true,+ name: 'Community skills',+ description: 'Discover and install agent skills shared by the PostHog community.',+ layout: 'app-container',+ iconType: 'llm_prompts',+ },},routes: {'/skills': ['Skills', 'skills'],@@ -31,6 +39,7 @@ export const manifest: ProductManifest = {// aren't captured as a skill named after the tab. Route order = match precedence.'/skills/scouts': ['Skills', 'skillsScouts'],'/skills/review-hog': ['Skills', 'skillsReviewHog'],+ '/community-skills': ['CommunitySkills', 'communitySkills'],'/skills/:name': ['Skill', 'skill'],},redirects: {@@ -49,6 +58,7 @@ export const manifest: ProductManifest = {skillsCategoryTab: (categoryTab: string): string => `/skills/${categoryTab}`,skill: (name: string, params?: { file?: string; version?: number }): string =>combineUrl(`/skills/${name}`, params).url,+ communitySkills: (): string => '/community-skills',},fileSystemTypes: {},treeItemsNew: [],