: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(aio): Support dropping folders into skill bundled files (#75939)
Juraj Majerik73a33c1dd9b1
diff --git a/products/skills/frontend/LLMSkillScene.tsx b/products/skills/frontend/LLMSkillScene.tsxindex b65b1c170289..6426d187c1fd 100644--- a/products/skills/frontend/LLMSkillScene.tsx+++ b/products/skills/frontend/LLMSkillScene.tsx@@ -14,7 +14,7 @@ import {IconUpload,IconX,} from '@posthog/icons'-import { LemonBanner, LemonButton, LemonFileInput, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'@@ -25,6 +25,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonMarkdownWithMermaid } from 'lib/lemon-ui/LemonMarkdown/LemonMarkdownWithMermaid'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { userHasAccess } from 'lib/utils/accessControlUtils'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { lazyWithRetry } from 'lib/utils/retryImport'@@ -44,6 +45,7 @@ import type { SkillFormFileValues } from './llmSkillLogic'import { SkillLogicProps, SkillMode, isSkill, llmSkillLogic } from './llmSkillLogic'import { SKILL_NAME_MAX_LENGTH, SKILL_DESCRIPTION_MAX_LENGTH } from './skillConstants'import { skillFileLogic } from './skillFileLogic'+import { collectFilesFromDrop } from './skillFileUpload'import { openArchiveSkillDialog } from './skillSceneComponents'const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))@@ -673,10 +675,6 @@ function SkillFileViewer({)}-// Stable reference so LemonFileInput never re-syncs its internal selection from the prop;-// uploads flow one-way into the skill form via addUploadedFiles.-const NO_UPLOADED_FILES: File[] = []-const COMMON_CONTENT_TYPES = [{ value: 'text/plain', label: 'text/plain' },{ value: 'text/markdown', label: 'text/markdown' },@@ -697,7 +695,44 @@ function SkillEditForm({}): JSX.Element {const { isNewSkill, skillForm } = useValues(llmSkillLogic)const { setSkillFormValues, addUploadedFiles } = useActions(llmSkillLogic)- const filesDropTargetRef = useRef<HTMLDivElement | null>(null)+ const uploadInputRef = useRef<HTMLInputElement | null>(null)+ // Depth counter instead of a boolean: dragenter/dragleave also fire for child elements,+ // so a plain boolean would flicker off while moving across the section.+ const dragDepthRef = useRef(0)+ const [dropActive, setDropActive] = useState(false)++ const onDragEnter = (e: React.DragEvent): void => {+ e.preventDefault()+ dragDepthRef.current += 1+ setDropActive(true)+ }++ const onDragOver = (e: React.DragEvent): void => {+ e.preventDefault()+ }++ const onDragLeave = (e: React.DragEvent): void => {+ e.preventDefault()+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)+ if (dragDepthRef.current === 0) {+ setDropActive(false)+ }+ }++ const onDrop = (e: React.DragEvent): void => {+ e.preventDefault()+ dragDepthRef.current = 0+ setDropActive(false)+ void collectFilesFromDrop(e.dataTransfer)+ .then((files) => {+ if (files.length > 0) {+ addUploadedFiles(files)+ }+ })+ .catch(() => {+ lemonToast.error('Couldn\'t read the dropped files. Try the "Upload files" button instead.')+ })+ }const addFile = (): void => {setSkillFormValues({@@ -787,7 +822,13 @@ function SkillEditForm({/></LemonField>- <div ref={filesDropTargetRef}>+ <div+ onDragEnter={onDragEnter}+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ className={dropActive ? 'rounded outline-2 outline-dashed outline-accent outline-offset-4' : undefined}+ ><div className="mb-2 flex items-center justify-between gap-2"><div><label className="text-sm font-semibold">Bundled files</label>@@ -797,24 +838,28 @@ function SkillEditForm({</p></div><div className="flex shrink-0 items-center gap-2">- <LemonFileInput+ <input+ ref={uploadInputRef}+ type="file"multiple- accept=""- value={NO_UPLOADED_FILES}- onChange={addUploadedFiles}- showUploadedFiles={false}- alternativeDropTargetRef={filesDropTargetRef}- callToAction={- <LemonButton- type="secondary"- icon={<IconUpload />}- size="small"- data-attr="llma-skill-upload-files-button"- >- Upload files- </LemonButton>- }+ className="hidden"+ onChange={(e) => {+ const files = Array.from(e.target.files ?? [])+ if (files.length > 0) {+ addUploadedFiles(files.map((file) => ({ path: file.name, file })))+ }+ e.target.value = ''+ }}/>+ <LemonButton+ type="secondary"+ icon={<IconUpload />}+ size="small"+ onClick={() => uploadInputRef.current?.click()}+ data-attr="llma-skill-upload-files-button"+ >+ Upload files+ </LemonButton><LemonButtontype="secondary"icon={<IconPlus />}@@ -835,8 +880,8 @@ function SkillEditForm({</div>) : skillForm.files.length === 0 ? (<div className="rounded border border-dashed p-4 text-center text-sm text-secondary">- No bundled files. Upload files, drag and drop them here, or click "Add file" to write one from- scratch.+ No bundled files. Upload files, drag and drop files or folders here, or click "Add file" to+ write one from scratch.</div>) : (<div className="space-y-3">diff --git a/products/skills/frontend/llmSkillLogic.test.ts b/products/skills/frontend/llmSkillLogic.test.tsindex 657368a266c1..c7db981a6f16 100644--- a/products/skills/frontend/llmSkillLogic.test.ts+++ b/products/skills/frontend/llmSkillLogic.test.ts@@ -5,6 +5,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { initKeaTests } from '~/test/init'import { llmSkillLogic } from './llmSkillLogic'+import type { SkillFileUpload } from './skillFileUpload'jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: { error: jest.fn(), success: jest.fn(), info: jest.fn() },@@ -24,48 +25,42 @@ describe('llmSkillLogic file uploads', () => {logic?.unmount()})- const upload = async (files: File[]): Promise<void> => {+ const asUpload = (content: string, path: string): SkillFileUpload => ({+ path,+ file: new File([content], path.split('/').pop() ?? path),+ })++ const upload = async (files: SkillFileUpload[]): Promise<void> => {await expectLogic(logic, () => logic.actions.addUploadedFiles(files)).toFinishAllListeners()}- it('adds uploaded files to the form with inferred content types', async () => {- await upload([new File(['print("hi")'], 'setup.py'), new File(['# Guide'], 'guide.md')])+ it('adds uploaded files to the form, preserving folder paths and inferring content types', async () => {+ await upload([asUpload('print("hi")', 'scripts/setup.py'), asUpload('# Guide', 'references/guide.md')])expect(logic.values.skillForm.files).toEqual([- { path: 'setup.py', content: 'print("hi")', content_type: 'text/x-python' },- { path: 'guide.md', content: '# Guide', content_type: 'text/markdown' },+ { path: 'scripts/setup.py', content: 'print("hi")', content_type: 'text/x-python' },+ { path: 'references/guide.md', content: '# Guide', content_type: 'text/markdown' },])})- it('re-uploading a path replaces its row, but a replayed File object does not clobber later edits', async () => {- const firstUpload = new File(['v1'], 'notes.txt')- await upload([firstUpload])-- logic.actions.setSkillFormValues({- files: [{ path: 'notes.txt', content: 'edited by hand', content_type: 'text/plain' }],- })-- // LemonFileInput replays previously selected File objects alongside new ones- await upload([firstUpload, new File(['extra'], 'extra.txt')])- expect(logic.values.skillForm.files).toEqual([- { path: 'notes.txt', content: 'edited by hand', content_type: 'text/plain' },- { path: 'extra.txt', content: 'extra', content_type: 'text/plain' },- ])+ it('re-uploading a path replaces its row instead of duplicating it', async () => {+ await upload([asUpload('v1', 'notes.txt'), asUpload('extra', 'extra.txt')])+ await upload([asUpload('v2', 'notes.txt')])- await upload([new File(['v2'], 'notes.txt')])expect(logic.values.skillForm.files).toEqual([{ path: 'notes.txt', content: 'v2', content_type: 'text/plain' },{ path: 'extra.txt', content: 'extra', content_type: 'text/plain' },])})- it('rejects oversized and binary files with an error toast but keeps valid ones', async () => {+ it('rejects oversized, binary, and SKILL.md files with a toast but keeps valid ones', async () => {await upload([- new File([new ArrayBuffer(1_000_001)], 'big.txt'),- new File(['\u0000binary'], 'nul.txt'),- new File([new Uint8Array([0xc3, 0x28])], 'invalid-utf8.txt'),- new File(['has a \ufffd char'], 'replacement.txt'),- new File(['ok'], 'ok.txt'),+ { path: 'big.txt', file: new File([new ArrayBuffer(1_000_001)], 'big.txt') },+ asUpload('\u0000binary', 'nul.txt'),+ { path: 'invalid-utf8.txt', file: new File([new Uint8Array([0xc3, 0x28])], 'invalid-utf8.txt') },+ asUpload('has a \ufffd char', 'replacement.txt'),+ asUpload('# My skill', 'Skill.md'),+ asUpload('ok', 'ok.txt'),])expect(logic.values.skillForm.files).toEqual([@@ -77,5 +72,18 @@ describe('llmSkillLogic file uploads', () => {"Couldn't add nul.txt: only text files are supported","Couldn't add invalid-utf8.txt: only text files are supported",])+ expect(jest.mocked(lemonToast.info)).toHaveBeenCalledWith(+ "SKILL.md wasn't added as a bundled file. Its body belongs in the skill body field."+ )+ })++ it('caps a folder drop at 50 files and says so instead of silently failing on publish', async () => {+ await upload(Array.from({ length: 55 }, (_, i) => asUpload(`content ${i}`, `references/file-${i}.txt`)))++ expect(logic.values.skillForm.files).toHaveLength(50)+ expect(logic.values.skillForm.files[49].path).toBe('references/file-49.txt')+ expect(jest.mocked(lemonToast.error)).toHaveBeenCalledWith(+ "Some files weren't added: a skill can have at most 50 bundled files"+ )})})diff --git a/products/skills/frontend/llmSkillLogic.ts b/products/skills/frontend/llmSkillLogic.tsindex 5d94192baf0f..e9d6435cf845 100644--- a/products/skills/frontend/llmSkillLogic.ts+++ b/products/skills/frontend/llmSkillLogic.ts@@ -37,7 +37,13 @@ import type {} from 'products/skills/frontend/generated/api.schemas'import { exportAndDownloadSkill, llmSkillsLogic, LLM_SKILLS_FORCE_RELOAD_PARAM } from './llmSkillsLogic'-import { SKILL_DESCRIPTION_MAX_LENGTH, SKILL_FILE_MAX_BYTES, validateSkillName } from './skillConstants'+import {+ SKILL_DESCRIPTION_MAX_LENGTH,+ SKILL_FILE_MAX_BYTES,+ SKILL_FILE_MAX_COUNT,+ validateSkillName,+} from './skillConstants'+import type { SkillFileUpload } from './skillFileUpload'export enum SkillMode {View = 'view',@@ -202,8 +208,8 @@ export interface llmSkillLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmSkillLogicActions {- addUploadedFiles: (files: File[]) => {- files: File[]+ addUploadedFiles: (files: SkillFileUpload[]) => {+ files: SkillFileUpload[]}deleteSkill: () => {value: true@@ -354,7 +360,7 @@ export const llmSkillLogic = kea<llmSkillLogicType>([props({ skillName: 'new' } as SkillLogicProps),key(({ skillName, selectedVersion }) => `skill-${skillName}:${selectedVersion ?? 'latest'}`),actions({- addUploadedFiles: (files: File[]) => ({ files }),+ addUploadedFiles: (files: SkillFileUpload[]) => ({ files }),setSkill: (skill: ResolvedLLMSkill | SkillFormValues) => ({ skill }),deleteSkill: true,loadMoreVersions: true,@@ -656,19 +662,19 @@ export const llmSkillLogic = kea<llmSkillLogicType>([],}),- listeners(({ actions, cache, props, values }) => ({+ listeners(({ actions, props, values }) => ({addUploadedFiles: async ({ files }) => {- // LemonFileInput re-reports every previously selected File on each new selection,- // so track handled File objects to avoid clobbering content the user edited since.- cache.uploadedFiles = cache.uploadedFiles ?? new WeakSet<File>()const uploaded: SkillFormFileValues[] = []- for (const file of files) {- if (cache.uploadedFiles.has(file)) {+ for (const { path, file } of files) {+ // Case-insensitive to match the backend's reserved-path validation+ if (path.toLowerCase() === 'skill.md') {+ lemonToast.info(+ "SKILL.md wasn't added as a bundled file. Its body belongs in the skill body field."+ )continue}- cache.uploadedFiles.add(file)if (file.size > SKILL_FILE_MAX_BYTES) {- lemonToast.error(`Couldn't add ${file.name}: files must be 1 MB or smaller`)+ lemonToast.error(`Couldn't add ${path}: files must be 1 MB or smaller`)continue}// Strict decoding distinguishes real binary (invalid UTF-8, or NUL bytes) from@@ -677,14 +683,14 @@ export const llmSkillLogic = kea<llmSkillLogicType>([try {content = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())} catch {- lemonToast.error(`Couldn't add ${file.name}: only text files are supported`)+ lemonToast.error(`Couldn't add ${path}: only text files are supported`)continue}if (content.includes('\u0000')) {- lemonToast.error(`Couldn't add ${file.name}: only text files are supported`)+ lemonToast.error(`Couldn't add ${path}: only text files are supported`)continue}- uploaded.push({ path: file.name, content, content_type: inferFileContentType(file.name) })+ uploaded.push({ path, content, content_type: inferFileContentType(path) })}if (uploaded.length === 0) {return@@ -698,7 +704,13 @@ export const llmSkillLogic = kea<llmSkillLogicType>([}return existing})- actions.setSkillFormValues({ files: [...merged, ...uploadedByPath.values()] })+ const combined = [...merged, ...uploadedByPath.values()]+ if (combined.length > SKILL_FILE_MAX_COUNT) {+ lemonToast.error(+ `Some files weren't added: a skill can have at most ${SKILL_FILE_MAX_COUNT} bundled files`+ )+ }+ actions.setSkillFormValues({ files: combined.slice(0, SKILL_FILE_MAX_COUNT) })},downloadSkill: async () => {diff --git a/products/skills/frontend/skillConstants.ts b/products/skills/frontend/skillConstants.tsindex 522b1f12ed19..330f36ddf186 100644--- a/products/skills/frontend/skillConstants.ts+++ b/products/skills/frontend/skillConstants.ts@@ -1,7 +1,8 @@export const SKILL_NAME_MAX_LENGTH = 64export const SKILL_DESCRIPTION_MAX_LENGTH = 4096-// Kept in sync with MAX_SKILL_FILE_BYTES in the backend skill_serializers.+// Kept in sync with MAX_SKILL_FILE_BYTES and MAX_SKILL_FILE_COUNT in the backend skill_serializers.export const SKILL_FILE_MAX_BYTES = 1_000_000+export const SKILL_FILE_MAX_COUNT = 50// Names that collide with reserved /skills routes: 'new' (the create form) and the category-tab// slugs registered under /skills/<slug> in manifest.tsx. A skill with one of these names would bediff --git a/products/skills/frontend/skillFileUpload.test.ts b/products/skills/frontend/skillFileUpload.test.tsnew file mode 100644index 000000000000..5106253dea6c--- /dev/null+++ b/products/skills/frontend/skillFileUpload.test.ts@@ -0,0 +1,82 @@+import { collectFilesFromDrop } from './skillFileUpload'++function fileEntry(name: string, fullPath: string): FileSystemFileEntry {+ return {+ isFile: true,+ isDirectory: false,+ name,+ fullPath,+ file: (resolve: (file: File) => void) => resolve(new File([`content of ${name}`], name)),+ } as unknown as FileSystemFileEntry+}++function unreadableFileEntry(name: string, fullPath: string): FileSystemFileEntry {+ return {+ isFile: true,+ isDirectory: false,+ name,+ fullPath,+ file: (_resolve: (file: File) => void, reject: (error: Error) => void) => reject(new Error('not readable')),+ } as unknown as FileSystemFileEntry+}++function directoryEntry(name: string, fullPath: string, children: FileSystemEntry[]): FileSystemDirectoryEntry {+ return {+ isFile: false,+ isDirectory: true,+ name,+ fullPath,+ createReader: () => {+ // Serve children one per readEntries call, like Chrome batches large directories+ let served = 0+ return {+ readEntries: (resolve: (entries: FileSystemEntry[]) => void) => {+ resolve(served < children.length ? [children[served++]] : [])+ },+ }+ },+ } as unknown as FileSystemDirectoryEntry+}++function dropOf(entries: (FileSystemEntry | null)[]): DataTransfer {+ return {+ items: entries.map((entry) => ({+ webkitGetAsEntry: () => entry,+ getAsFile: () => null,+ })),+ files: [],+ } as unknown as DataTransfer+}++describe('collectFilesFromDrop', () => {+ it('recurses dropped folders, draining batched directory listings and skipping hidden or unreadable files', async () => {+ const scripts = directoryEntry('scripts', '/scripts', [+ fileEntry('setup.sh', '/scripts/setup.sh'),+ fileEntry('run.py', '/scripts/run.py'),+ fileEntry('.DS_Store', '/scripts/.DS_Store'),+ unreadableFileEntry('locked.txt', '/scripts/locked.txt'),+ directoryEntry('nested', '/scripts/nested', [fileEntry('deep.txt', '/scripts/nested/deep.txt')]),+ ])++ const uploads = await collectFilesFromDrop(dropOf([scripts, fileEntry('guide.md', '/guide.md')]))++ expect(uploads.map((u) => u.path)).toEqual([+ 'scripts/setup.sh',+ 'scripts/run.py',+ 'scripts/nested/deep.txt',+ 'guide.md',+ ])+ expect(uploads[0].file.name).toBe('setup.sh')+ })++ it('falls back to the flat file list when the entry API is unavailable', async () => {+ const dataTransfer = {+ items: [],+ files: [new File(['a'], 'a.txt'), new File(['b'], '.hidden')],+ } as unknown as DataTransfer++ const uploads = await collectFilesFromDrop(dataTransfer)++ expect(uploads.map((u) => u.path)).toEqual(['a.txt'])+ })+})diff --git a/products/skills/frontend/skillFileUpload.ts b/products/skills/frontend/skillFileUpload.tsnew file mode 100644index 000000000000..5b5af612f89e--- /dev/null+++ b/products/skills/frontend/skillFileUpload.ts@@ -0,0 +1,75 @@+export interface SkillFileUpload {+ path: string+ file: File+}++async function readAllDirectoryEntries(reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> {+ const entries: FileSystemEntry[] = []+ // readEntries returns results in batches (Chrome caps each call at 100 entries);+ // an empty batch signals the end of the directory.+ while (true) {+ const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => reader.readEntries(resolve, reject))+ if (batch.length === 0) {+ return entries+ }+ entries.push(...batch)+ }+}++async function collectEntry(entry: FileSystemEntry, uploads: SkillFileUpload[]): Promise<void> {+ if (entry.name.startsWith('.')) {+ return+ }+ // An unreadable entry (permissions, file vanished mid-drop) is skipped rather than+ // sinking everything collected so far.+ if (entry.isFile) {+ try {+ const file = await new Promise<File>((resolve, reject) =>+ (entry as FileSystemFileEntry).file(resolve, reject)+ )+ uploads.push({ path: entry.fullPath.replace(/^\//, ''), file })+ } catch {+ return+ }+ return+ }+ if (entry.isDirectory) {+ let children: FileSystemEntry[]+ try {+ children = await readAllDirectoryEntries((entry as FileSystemDirectoryEntry).createReader())+ } catch {+ return+ }+ for (const child of children) {+ await collectEntry(child, uploads)+ }+ }+}++/** Expand a drop into files, recursing into dropped folders. Must be called synchronously+ * from the drop event handler: DataTransferItems are unusable once the handler yields. */+export async function collectFilesFromDrop(dataTransfer: DataTransfer): Promise<SkillFileUpload[]> {+ const roots: (FileSystemEntry | File | null)[] = Array.from(dataTransfer.items ?? []).map(+ (item) => (typeof item.webkitGetAsEntry === 'function' ? item.webkitGetAsEntry() : null) ?? item.getAsFile()+ )+ if (roots.length === 0) {+ // Entry API entirely unavailable: fall back to the flat file list (no folder support)+ return Array.from(dataTransfer.files ?? [])+ .filter((file) => !file.name.startsWith('.'))+ .map((file) => ({ path: file.name, file }))+ }+ const uploads: SkillFileUpload[] = []+ for (const root of roots) {+ if (!root) {+ continue+ }+ if (root instanceof File) {+ if (!root.name.startsWith('.')) {+ uploads.push({ path: root.name, file: root })+ }+ } else {+ await collectEntry(root, uploads)+ }+ }+ return uploads+}