: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 drag and drop uploads for skill bundled files (#75883)
Juraj Majerik9eda607c695a
diff --git a/products/skills/frontend/LLMSkillScene.tsx b/products/skills/frontend/LLMSkillScene.tsxindex 5d6e3270db02..b65b1c170289 100644--- a/products/skills/frontend/LLMSkillScene.tsx+++ b/products/skills/frontend/LLMSkillScene.tsx@@ -11,9 +11,10 @@ import {IconPencil,IconPlus,IconTrash,+ IconUpload,IconX,} from '@posthog/icons'-import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonFileInput, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'@@ -672,6 +673,10 @@ 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' },@@ -691,7 +696,8 @@ function SkillEditForm({fileContentsLoading: boolean}): JSX.Element {const { isNewSkill, skillForm } = useValues(llmSkillLogic)- const { setSkillFormValues } = useActions(llmSkillLogic)+ const { setSkillFormValues, addUploadedFiles } = useActions(llmSkillLogic)+ const filesDropTargetRef = useRef<HTMLDivElement | null>(null)const addFile = (): void => {setSkillFormValues({@@ -781,8 +787,8 @@ function SkillEditForm({/></LemonField>- <div>- <div className="mb-2 flex items-center justify-between">+ <div ref={filesDropTargetRef}>+ <div className="mb-2 flex items-center justify-between gap-2"><div><label className="text-sm font-semibold">Bundled files</label><p className="text-xs text-secondary">@@ -790,15 +796,35 @@ function SkillEditForm({the skill body.</p></div>- <LemonButton- type="secondary"- icon={<IconPlus />}- size="small"- onClick={addFile}- data-attr="llma-skill-add-file-button"- >- Add file- </LemonButton>+ <div className="flex shrink-0 items-center gap-2">+ <LemonFileInput+ 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>+ }+ />+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ size="small"+ onClick={addFile}+ data-attr="llma-skill-add-file-button"+ >+ Add file+ </LemonButton>+ </div></div>{fileContentsLoading ? (@@ -809,7 +835,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. Click "Add file" to include scripts or references.+ No bundled files. Upload files, drag and drop them 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.tsnew file mode 100644index 000000000000..657368a266c1--- /dev/null+++ b/products/skills/frontend/llmSkillLogic.test.ts@@ -0,0 +1,81 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { initKeaTests } from '~/test/init'++import { llmSkillLogic } from './llmSkillLogic'++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { error: jest.fn(), success: jest.fn(), info: jest.fn() },+}))++describe('llmSkillLogic file uploads', () => {+ let logic: ReturnType<typeof llmSkillLogic.build>++ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ logic = llmSkillLogic({ skillName: 'new' })+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ const upload = async (files: File[]): 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')])++ 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' },+ ])+ })++ 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' },+ ])++ 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 () => {+ 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'),+ ])++ expect(logic.values.skillForm.files).toEqual([+ { path: 'replacement.txt', content: 'has a \ufffd char', content_type: 'text/plain' },+ { path: 'ok.txt', content: 'ok', content_type: 'text/plain' },+ ])+ expect(jest.mocked(lemonToast.error).mock.calls.map(([message]) => message)).toEqual([+ "Couldn't add big.txt: files must be 1 MB or smaller",+ "Couldn't add nul.txt: only text files are supported",+ "Couldn't add invalid-utf8.txt: only text files are supported",+ ])+ })+})diff --git a/products/skills/frontend/llmSkillLogic.ts b/products/skills/frontend/llmSkillLogic.tsindex b6d7a8eef305..5d94192baf0f 100644--- a/products/skills/frontend/llmSkillLogic.ts+++ b/products/skills/frontend/llmSkillLogic.ts@@ -37,7 +37,7 @@ import type {} from 'products/skills/frontend/generated/api.schemas'import { exportAndDownloadSkill, llmSkillsLogic, LLM_SKILLS_FORCE_RELOAD_PARAM } from './llmSkillsLogic'-import { SKILL_DESCRIPTION_MAX_LENGTH, validateSkillName } from './skillConstants'+import { SKILL_DESCRIPTION_MAX_LENGTH, SKILL_FILE_MAX_BYTES, validateSkillName } from './skillConstants'export enum SkillMode {View = 'view',@@ -74,6 +74,31 @@ export function isSkill(skill: LLMSkillApi | ResolvedLLMSkill | SkillFormValuesreturn skill !== null && 'id' in skill}+// Values must stay within COMMON_CONTENT_TYPES in LLMSkillScene, so the content-type+// select can display whatever gets inferred here.+const CONTENT_TYPE_BY_EXTENSION: Record<string, string> = {+ md: 'text/markdown',+ markdown: 'text/markdown',+ py: 'text/x-python',+ sh: 'text/x-shellscript',+ bash: 'text/x-shellscript',+ zsh: 'text/x-shellscript',+ json: 'application/json',+ yaml: 'text/yaml',+ yml: 'text/yaml',+ js: 'text/javascript',+ mjs: 'text/javascript',+ cjs: 'text/javascript',+ jsx: 'text/javascript',+ ts: 'text/typescript',+ tsx: 'text/typescript',+}++function inferFileContentType(fileName: string): string {+ const extension = fileName.toLowerCase().split('.').pop() ?? ''+ return CONTENT_TYPE_BY_EXTENSION[extension] ?? 'text/plain'+}+const DEFAULT_SKILL_FORM_VALUES: SkillFormValues = {name: '',description: '',@@ -177,6 +202,9 @@ 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[]+ }deleteSkill: () => {value: true}@@ -326,6 +354,7 @@ export const llmSkillLogic = kea<llmSkillLogicType>([props({ skillName: 'new' } as SkillLogicProps),key(({ skillName, selectedVersion }) => `skill-${skillName}:${selectedVersion ?? 'latest'}`),actions({+ addUploadedFiles: (files: File[]) => ({ files }),setSkill: (skill: ResolvedLLMSkill | SkillFormValues) => ({ skill }),deleteSkill: true,loadMoreVersions: true,@@ -627,7 +656,51 @@ export const llmSkillLogic = kea<llmSkillLogicType>([],}),- listeners(({ actions, props, values }) => ({+ listeners(({ actions, cache, 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)) {+ 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`)+ continue+ }+ // Strict decoding distinguishes real binary (invalid UTF-8, or NUL bytes) from+ // text that legitimately contains a U+FFFD replacement character.+ let content: string+ 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`)+ continue+ }+ if (content.includes('\u0000')) {+ lemonToast.error(`Couldn't add ${file.name}: only text files are supported`)+ continue+ }+ uploaded.push({ path: file.name, content, content_type: inferFileContentType(file.name) })+ }+ if (uploaded.length === 0) {+ return+ }+ const uploadedByPath = new Map(uploaded.map((f) => [f.path, f]))+ const merged = values.skillForm.files.map((existing) => {+ const replacement = uploadedByPath.get(existing.path)+ if (replacement) {+ uploadedByPath.delete(existing.path)+ return replacement+ }+ return existing+ })+ actions.setSkillFormValues({ files: [...merged, ...uploadedByPath.values()] })+ },+downloadSkill: async () => {if (props.skillName === 'new') {returndiff --git a/products/skills/frontend/skillConstants.ts b/products/skills/frontend/skillConstants.tsindex 91697cf3bdcc..522b1f12ed19 100644--- a/products/skills/frontend/skillConstants.ts+++ b/products/skills/frontend/skillConstants.ts@@ -1,5 +1,7 @@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.+export const SKILL_FILE_MAX_BYTES = 1_000_000// 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 be