: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
fix(terminal): fix file browsing, folder links, and doom controls (#105711)
Marius Andra251b0c38b248
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8bb7fb55eb3e..5e6f25ff6a04 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3820,6 +3820,10 @@ snapshots:hash: v1.k794b7964.88bb1c5716f71d0bec9e72d9f0eb3357242893c005dd4fe51b4623d4a914a630.MpyezT0JDw30KglY7NzLugWmyjn_FEqtPOGfhFzrvEolayout-apps-and-files--no-results--light:hash: v1.k794b7964.c5bd4fab104b89d30f36184d8fbaeeec5c5b5868da1e9cc210fbcf00871e9454.ydynNa6_mx3tOqZX3b6YDtIRUT7_lOyeSLv_LDtzF8o+ layout-apps-and-files--open-folder--dark:+ hash: v1.k794b7964.32274fcb3c9a7956285be7ee7d957ebe3bb3e7b4f1b43a8d580bd3ef0c5fd669.aqcnzaSb_BU0A1akwyAGsEi9RRuzOtQXJPJ5Wdo9CYw+ layout-apps-and-files--open-folder--light:+ hash: v1.k794b7964.22fd482f64ea49fd1090c0add5984fbd2cb9e68ae3bc2361c3153396c91ac21c.dPJASLY-SsDpL_bEKqNSR0eyVjeFx1qolOFVRkVqpdklayout-apps-and-files--search--dark:hash: v1.k794b7964.0d5dac8468bbf845be2be38b812086592d4be9574f4ced65e36648f71bc751cb.h6TF74-gkqhaI9nKbbdCNRZc_BpVsz4NK0wq1BBCCcUlayout-apps-and-files--search--light:@@ -8812,6 +8816,10 @@ snapshots:hash: v1.k794b7964.45cc8cf59cd8b897fe3291f58539e52d380acb59ee791d15ac20fa3f4d035e9a.CFUlQtyS7jBKX3o3QXiGm3uHwMLaRnzL1wxvAybM4Xsscenes-app-files--folder--light:hash: v1.k794b7964.989df5b185b5ea838de882e2191fdd728b9da6f9f9f793377daad5ad29bb9a39.Y5uv2I9EWNkMdIMA9WV8as-78tZ5zw8XF2o4BD9y3u8+ scenes-app-files--folder-from-url--dark:+ hash: v1.k794b7964.241af4167dd02891ee3b26da7a34cbebe252f9040857ebcf82d77dddef669d79.Bcqfz0asysbfhaPixJzN9o99GghrTd1b8MqLt0OpUWw+ scenes-app-files--folder-from-url--light:+ hash: v1.k794b7964.fbcce5cea1f4b2941cb3637c516d9928d33f6186624bd2fcf39c650c739162f3.QI_N6fDLNo-UDw5okRgkXPOx7Da7otRWwWsbrkQpDAoscenes-app-files--long-folder--dark:hash: v1.k794b7964.ed667e6feaa110372303685473302f35df77d45ff7de8a8cf543c05fd5fb1b6d.pCp00dSRWiBYosznbnBy2gzp8FZ5iXNJEsgNsGJKtf8scenes-app-files--long-folder--light:@@ -11593,9 +11601,9 @@ snapshots:scenes-app-terminal--docked--light:hash: v1.k794b7964.a34850192db6d63249686b7ef1922b1b479312471ce974d91295757a4fce059b.2_jI8KKm2oYMSRxI2Fo5n-3tOzjyxTJ3t_YS8iAH1I0scenes-app-terminal--framebuffer--dark:- hash: v1.k794b7964.f4b78afd6b1a02a2707edf5b786b418008d12e482d7c931bba7e91261426edbe.-GAYIgMuZUP3lwqpoTb886Ak-9OoKYM3qY4_uIBaZL0+ hash: v1.k794b7964.9ef178a4201b6cf281b8832cc7862430c1129268217b2e1910613b6956e38aa0.oAMSaPpYkgMPxmGbBzUbMfvIkSxzAVh6J1uBxr6FYzwscenes-app-terminal--framebuffer--light:- hash: v1.k794b7964.71f85fee0826d17254ad9b106e64ccf0d74e7ba7c1cd6a50e8b3bf6497c3748e.hGAR67OvjYRK8o0J1xK7XNt6xkWAITkqoDCmryF1Ab0+ hash: v1.k794b7964.58823621cdfcdfd56eee0611758c30646885a202836a2508fed186c968c5f216.oMMYoKiPGFmJ8yRG_uLpZ3JVdUG5sv1GwgUcFuC9dKcscenes-app-terminal--narrow--dark:hash: v1.k794b7964.36aebe98c0f44e2bfd0b6223bfc7fc33ece3cf81d6391d9baaaef157a06693f5.88obmOSvpcyTNe5SBWsYApI9WFSS4pyaJF68cZQ2MU4scenes-app-terminal--narrow--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 00210309d8c5..f6bf53c6cc78 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5353,6 +5353,10 @@ export type ExportsListParams = {}export type FileSystemListParams = {+ /**+ * Include meta.content_type for notebooks and insights on this page, without their contents.+ */+ include_content_type?: boolean/*** Number of results to return per page.*/diff --git a/frontend/src/layout/panel-layout/navbar/AppsAndFiles.stories.tsx b/frontend/src/layout/panel-layout/navbar/AppsAndFiles.stories.tsxindex b4ec42834ee5..246a094ce0de 100644--- a/frontend/src/layout/panel-layout/navbar/AppsAndFiles.stories.tsx+++ b/frontend/src/layout/panel-layout/navbar/AppsAndFiles.stories.tsx@@ -57,6 +57,7 @@ function SidebarStory({overlay = false,empty = false,recentsCollapsed = false,+ folderToOpen,}: {tab?: NavExperimentTabsearch?: string@@ -64,6 +65,7 @@ function SidebarStory({overlay?: booleanempty?: booleanrecentsCollapsed?: boolean+ folderToOpen?: string}): JSX.Element {const { setNavExperimentTab, toggleLayoutNavCollapsed, clearActivePanelIdentifier, setNavOverlayOpen } =useActions(panelLayoutLogic)@@ -82,6 +84,9 @@ function SidebarStory({}setRecentsCollapsed(recentsCollapsed)loadShortcutsSuccess(empty ? [] : starred)+ if (folderToOpen !== undefined) {+ navFilesTabLogic.actions.openFolder(folderToOpen)+ }})return <NavBar />}@@ -138,6 +143,7 @@ export default metatype Story = StoryObj<typeof SidebarStory>export const Apps: Story = {}export const Files: Story = { args: { tab: 'files' } }+export const OpenFolder: Story = { args: { collapsed: true, folderToOpen: 'Product research' } }export const Chat: Story = {args: { tab: 'chat' },decorators: [diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsxindex 1bbfe8bb501a..d259cfb9952f 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx@@ -13,7 +13,7 @@ import { NavTabSection } from './NavTabSection'export function NavTabFiles(): JSX.Element {const { navExperimentActiveTab } = useValues(panelLayoutLogic)const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)- const { searchTerm } = useValues(navFilesTabLogic)+ const { searchTerm, folderRevealCount } = useValues(navFilesTabLogic)const { fullFileSystemFiltered: starredFiles } = useValues(projectTreeLogic({ key: FILES_STARRED_TREE_KEY, root: 'shortcuts://', shortcutScope: 'files' }))@@ -59,7 +59,7 @@ export function NavTabFiles(): JSX.Element {<NavTabSectionlabel="Files"dataAttr="nav-files-project-toggle"- key={`files-${!!searchTerm.trim()}`}+ key={`files-${!!searchTerm.trim()}-${folderRevealCount}`}>{tree}</NavTabSection>diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.test.ts b/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.test.tsindex f2e7ec3a8c10..15eddf1b3406 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.test.ts+++ b/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.test.ts@@ -1,5 +1,8 @@+import { expectLogic } from 'kea-test-utils'+import { initKeaTests } from '~/test/init'+import { panelLayoutLogic } from '../../panelLayoutLogic'import { projectTreeDataLogic } from '../../ProjectTree/projectTreeDataLogic'import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'import { FILES_STARRED_TREE_KEY, FILES_TREE_KEY, navFilesTabLogic } from './navFilesTabLogic'@@ -27,4 +30,43 @@ describe('navFilesTabLogic', () => {files.actions.clearSearch()expect(starred.values.fullFileSystemFiltered.map((item) => item.name)).toEqual(['Overview', 'Research'])})++ it('reveals a folder in the files tab even when the navigation and folder are collapsed', async () => {+ const files = projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' })+ panelLayoutLogic.actions.setNavExperimentTab('home')+ panelLayoutLogic.actions.toggleLayoutNavCollapsed(true)+ panelLayoutLogic.actions.setActivePanelIdentifier('DataAndPeople')+ panelLayoutLogic.actions.showLayoutPanel(true)+ files.actions.setSearchTerm('unrelated')+ files.actions.setSortMethod('recent')+ files.actions.setOnlyFolders(true)++ navFilesTabLogic.actions.openFolder('Research/Reports')++ expect(panelLayoutLogic.values.navExperimentActiveTab).toBe('files')+ expect(panelLayoutLogic.values.isNavOverlayOpen).toBe(true)+ expect(panelLayoutLogic.values.activePanelIdentifier).toBe('')+ expect(panelLayoutLogic.values.isLayoutPanelVisible).toBe(false)+ expect(files.values.searchTerm).toBe('')+ expect(files.values.sortMethod).toBe('folder')+ expect(files.values.onlyFolders).toBe(false)+ expect(files.values.expandedFolders).toEqual(+ expect.arrayContaining(['project://Research', 'project://Research/Reports'])+ )+ expect(files.values.scrollTargetId).toBe('')+ await expectLogic(files, () => {+ projectTreeDataLogic.actions.loadFolderSuccess(+ 'Research',+ [{ id: 'reports', path: 'Research/Reports', type: 'folder', ref: 'Research/Reports' }],+ false,+ 1+ )+ }).toMatchValues({ scrollTargetId: 'project://Research/Reports' })+ files.actions.clearScrollTarget()+ projectTreeDataLogic.actions.loadFolderSuccess('Research/Reports', [], false, 0)+ expect(files.values.scrollTargetId).toBe('')+ navFilesTabLogic.actions.openFolder('Research/Reports')+ expect(files.values.expandedFolders).toContain('project://Research/Reports')+ expect(files.values.scrollTargetId).toBe('project://Research/Reports')+ })})diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.ts b/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.tsindex df42c7f38722..68b834191b60 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.ts+++ b/frontend/src/layout/panel-layout/navbar/tabs/navFilesTabLogic.ts@@ -1,5 +1,9 @@-import { MakeLogicType, connect, kea, listeners, path } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { subscriptions } from 'kea-subscriptions'+import { FileSystemEntry } from '~/queries/schema/schema-general'++import { panelLayoutLogic } from '../../panelLayoutLogic'import { projectTreeLogic } from '../../ProjectTree/projectTreeLogic'export const FILES_TREE_KEY = 'navbar-files'@@ -8,17 +12,58 @@ export const FILES_STARRED_TREE_KEY = 'navbar-files-starred'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface navFilesTabLogicValues {searchTerm: string // projectTreeLogic+ viableItems: FileSystemEntry[] // projectTreeLogic+ folderRevealCount: number+ folderToReveal: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface navFilesTabLogicActions {+ openFolder: (folder: string) => {+ folder: string+ }}-export type navFilesTabLogicType = MakeLogicType<navFilesTabLogicValues, {}>+export type navFilesTabLogicType = MakeLogicType<navFilesTabLogicValues, navFilesTabLogicActions>export const navFilesTabLogic = kea<navFilesTabLogicType>([path(['layout', 'panel-layout', 'navbar', 'tabs', 'navFilesTabLogic']),connect(() => ({- values: [projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }), ['searchTerm']],+ values: [projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }), ['searchTerm', 'viableItems']],logic: [projectTreeLogic({ key: FILES_STARRED_TREE_KEY, root: 'shortcuts://', shortcutScope: 'files' })],})),+ actions({ openFolder: (folder: string) => ({ folder }) }),+ reducers({+ folderRevealCount: [0, { openFolder: (state) => state + 1 }],+ folderToReveal: [+ null as string | null,+ {+ openFolder: (_, { folder }) => folder || null,+ [projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }).actionTypes.scrollToView]: (+ state,+ { item }: { item: FileSystemEntry }+ ) => (item.type === 'folder' && item.path === state ? null : state),+ },+ ],+ }),listeners(() => ({+ openFolder: ({ folder }) => {+ panelLayoutLogic.actions.setNavExperimentTab('files')+ panelLayoutLogic.actions.showLayoutNavBar(true)+ panelLayoutLogic.actions.clearActivePanelIdentifier()+ panelLayoutLogic.actions.showLayoutPanel(false)+ if (panelLayoutLogic.values.isLayoutNavCollapsed) {+ panelLayoutLogic.actions.setNavOverlayOpen(true)+ }+ const tree = projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' })+ tree.actions.clearSearch()+ tree.actions.setSortMethod('folder')+ tree.actions.setOnlyFolders(false)+ tree.actions.assureVisibility({ type: 'folder', ref: folder })+ if (!tree.values.expandedFolders.includes(`project://${folder}`)) {+ tree.actions.toggleFolderOpen(`project://${folder}`, true)+ }+ },[projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }).actionTypes.setSearchTerm]: ({searchTerm,}: {@@ -38,4 +83,12 @@ export const navFilesTabLogic = kea<navFilesTabLogicType>([}).actions.clearSearch()},})),+ subscriptions(({ values }) => ({+ viableItems: (items: FileSystemEntry[]) => {+ const folder = items.find((item) => item.type === 'folder' && item.path === values.folderToReveal)+ if (folder) {+ projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }).actions.scrollToView(folder)+ }+ },+ })),])diff --git a/frontend/src/scenes/project-files/ProjectFilesScene.stories.tsx b/frontend/src/scenes/project-files/ProjectFilesScene.stories.tsxindex af6b59878b02..f25f46bc26c6 100644--- a/frontend/src/scenes/project-files/ProjectFilesScene.stories.tsx+++ b/frontend/src/scenes/project-files/ProjectFilesScene.stories.tsx@@ -1,4 +1,5 @@import type { Meta, StoryObj } from '@storybook/react'+import { router } from 'kea-router'import { useStorybookMocks } from '~/mocks/browser'@@ -41,6 +42,16 @@ export default metaexport const Folder: StoryObj<typeof ProjectFilesScene> = { args: { folder: 'Research' } }export const ProjectRoot: StoryObj<typeof ProjectFilesScene> = {}+export const FolderFromUrl: StoryObj<typeof ProjectFilesScene> = {+ decorators: [+ (Story) => (+ <div className="w-[800px] max-w-full">+ <Story />+ </div>+ ),+ ],+ play: () => router.actions.push('/files?folder=Research'),+}export const LongFolder: StoryObj<typeof ProjectFilesScene> = {args: { folder: 'Research' },parameters: { fileCount: 80 },diff --git a/frontend/src/scenes/project-files/ProjectFilesScene.test.tsx b/frontend/src/scenes/project-files/ProjectFilesScene.test.tsxnew file mode 100644index 000000000000..198bee1be5dd--- /dev/null+++ b/frontend/src/scenes/project-files/ProjectFilesScene.test.tsx@@ -0,0 +1,32 @@+import '@testing-library/jest-dom'++import { render, screen, waitFor } from '@testing-library/react'+import { router } from 'kea-router'++import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'++import { ProjectFilesScene } from './ProjectFilesScene'++jest.mock('~/layout/panel-layout/ProjectTree/ProjectTree', () => ({+ ProjectTree: ({ root }: { root: string }) => <div>{root}</div>,+}))++describe('project files scene', () => {+ it('opens the URL folder and follows query changes without remounting', async () => {+ initKeaTests()+ router.actions.push(urls.projectFiles('Research & notes/Reports'))+ render(<ProjectFilesScene />)+ expect(screen.getByText('Research & notes/Reports')).toBeInTheDocument()+ expect(screen.getByText('project://Research & notes/Reports')).toBeInTheDocument()+ expect(screen.getByLabelText('Parent folder')).toHaveAttribute(+ 'href',+ expect.stringContaining('folder=Research%20%26%20notes')+ )+ router.actions.push(urls.projectFiles())+ await waitFor(() => expect(screen.getByText('Project')).toBeInTheDocument())+ expect(screen.getByText('project://')).toBeInTheDocument()+ expect(screen.queryByLabelText('Parent folder')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/project-files/ProjectFilesScene.tsx b/frontend/src/scenes/project-files/ProjectFilesScene.tsxindex 7570e41c1487..c07121921cb1 100644--- a/frontend/src/scenes/project-files/ProjectFilesScene.tsx+++ b/frontend/src/scenes/project-files/ProjectFilesScene.tsx@@ -1,3 +1,6 @@+import { useValues } from 'kea'+import { router } from 'kea-router'+import { LemonButton } from '@posthog/lemon-ui'import { SceneExport } from 'scenes/sceneTypes'@@ -12,12 +15,12 @@ export interface ProjectFilesSceneProps {export const scene: SceneExport<ProjectFilesSceneProps> = {component: ProjectFilesScene,- paramsToProps: ({ searchParams }) => ({- folder: typeof searchParams.folder === 'string' ? searchParams.folder.replace(/^\/+|\/+$/g, '') : '',- }),}-export function ProjectFilesScene({ folder = '' }: ProjectFilesSceneProps): JSX.Element {+export function ProjectFilesScene({ folder: folderProp }: ProjectFilesSceneProps): JSX.Element {+ const { searchParams } = useValues(router)+ const folder =+ folderProp ?? (typeof searchParams.folder === 'string' ? searchParams.folder.replace(/^\/+|\/+$/g, '') : '')return (<SceneContent className="h-full min-h-0 flex-1 overflow-hidden gap-y-2 pb-1"><div className="flex shrink-0 items-center gap-2">diff --git a/frontend/src/scenes/terminal/TerminalFramebufferWindow.tsx b/frontend/src/scenes/terminal/TerminalFramebufferWindow.tsxindex 2cc6b53b12a2..effc57ca4b17 100644--- a/frontend/src/scenes/terminal/TerminalFramebufferWindow.tsx+++ b/frontend/src/scenes/terminal/TerminalFramebufferWindow.tsx@@ -183,7 +183,7 @@ export function TerminalFramebufferWindow(): JSX.Element | null {<divref={screenRef}role="application"- aria-label="Game display. Arrow keys move, Ctrl fires, Space opens doors, Escape opens the game menu. Shift+Tab releases keyboard focus."+ aria-label="Game display. W and S move, A and D strafe, left and right arrows turn, Space fires, E opens doors. Shift+Tab releases keyboard focus."tabIndex={0}className="TerminalFramebufferWindow__screen ph-no-capture ph-replay-block flex-1 min-h-0 bg-black focus-visible:ring-2 focus-visible:ring-inset"data-attr="terminal-display-screen"@@ -233,8 +233,8 @@ export function TerminalFramebufferWindow(): JSX.Element | null {/><div className="text-xs text-secondary pl-3 pr-6 py-2 border-t shrink-0"><span>- Arrows move · Ctrl fires · Space opens doors · Shift runs · Esc opens the menu or releases the- mouse · Shift+Tab releases keyboard focus+ W/S move · A/D strafe · ←/→ turn · Space or click fires · E opens doors · Shift runs · Capture+ mouse to turn · Esc opens the menu or releases the mouse · Shift+Tab releases keyboard focus</span>{error && (<p className="text-danger mb-0 mt-1" role="status">diff --git a/frontend/src/scenes/terminal/TerminalScene.stories.tsx b/frontend/src/scenes/terminal/TerminalScene.stories.tsxindex 8c1e70cfda6d..05ac4373ca5a 100644--- a/frontend/src/scenes/terminal/TerminalScene.stories.tsx+++ b/frontend/src/scenes/terminal/TerminalScene.stories.tsx@@ -134,6 +134,7 @@ const meta: Meta<typeof TerminalScene> = {type: 'notebook',ref: item.short_id,user_access_level: 'editor',+ meta: { content_type: 'text/markdown' },})).concat([...folders].map(([id, path]) => ({@@ -142,6 +143,7 @@ const meta: Meta<typeof TerminalScene> = {type: 'folder',ref: '',user_access_level: 'editor',+ meta: { content_type: 'inode/directory' },}))).concat(@@ -151,6 +153,9 @@ const meta: Meta<typeof TerminalScene> = {type: item.type,ref: item.ref,user_access_level: 'editor',+ meta: {+ content_type: item.type === 'insight' ? 'application/sql' : 'application/json',+ },}))),},@@ -369,6 +374,7 @@ export const DeleteConfirmation: StoryObj<typeof TerminalScene> = {}export const Framebuffer: StoryObj<typeof TerminalScene> = {+ parameters: { testOptions: { snapshotTargetSelector: 'body' } },play: async () => {await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))terminalLogic.actions.setDisplayOpen(true)diff --git a/frontend/src/scenes/terminal/TerminalView.tsx b/frontend/src/scenes/terminal/TerminalView.tsxindex c4a4a75b9316..8f0cfd72993c 100644--- a/frontend/src/scenes/terminal/TerminalView.tsx+++ b/frontend/src/scenes/terminal/TerminalView.tsx@@ -24,7 +24,7 @@ const examples = ['busybox',],},- { title: 'Optional tools', commands: ['doom', 'node --version', 'pi --help'] },+ { title: 'Optional tools', commands: ['node --version', 'pi --help', 'nyancat', 'doom'] },{ title: 'PostHog tools', commands: ['ph tools', 'ph tools notebook', 'ph help notebooks-retrieve', 'ph refresh'] },{title: 'Edit and organize',diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.tsindex 7efe625d3072..5936521c1062 100644--- a/frontend/src/scenes/terminal/posthogCommands.test.ts+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts@@ -153,6 +153,7 @@ describe('PostHog terminal commands', () => {ref: 'shortnote',type: 'notebook',path: 'Research/Notes',+ meta: { content_type: 'text/markdown' },user_access_level: 'editor',} as FileSystemApi,],diff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.tsindex 1e94f9c6504f..889c3c05428e 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts@@ -1,5 +1,3 @@-import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'-import { waitFor } from '@testing-library/react'import apiMutator from 'lib/api-orval-mutator'@@ -8,7 +6,7 @@ import { fileSystemCreate, fileSystemDestroy, fileSystemList, fileSystemRetrieveimport type { FileSystemApi } from '~/generated/core/api.schemas'import { notebooksList, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'-import type { NotebookApi, NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'+import type { NotebookApi } from 'products/notebooks/frontend/generated/api.schemas'import { insightsList } from 'products/product_analytics/frontend/generated/api'import { NinePReader, NinePWriter } from './ninepCodec'@@ -49,6 +47,7 @@ describe('PostHog filesystem projection', () => {created_by: null,last_viewed_at: null,user_access_level: 'editor',+ meta: type === 'notebook' ? { content_type: 'text/markdown' } : {},})const notebook = {short_id: 'note1',@@ -59,13 +58,6 @@ describe('PostHog filesystem projection', () => {content: [{ type: 'ph-markdown-notebook', attrs: { markdown: '# Hello 🦔', nodeId: 'preserved' } }],},} as NotebookApi- const notebookIndex: NotebookMinimalApi = {- ...notebook,- title: 'Notes',- deleted: false,- user_access_level: 'editor',- }-beforeEach(() => {jest.clearAllMocks()jest.mocked(insightsList).mockResolvedValue({ count: 0, results: [] })@@ -74,11 +66,6 @@ describe('PostHog filesystem projection', () => {next: null,results: [entry('note1', 'Research/Notes')],})- jest.mocked(notebooksList).mockResolvedValue({- count: 2,- next: null,- results: [notebookIndex, { ...notebookIndex, short_id: 'note2' }],- })jest.mocked(notebooksRetrieve).mockResolvedValue(notebook)})@@ -86,43 +73,7 @@ describe('PostHog filesystem projection', () => {const signal = new AbortController().signaljest.mocked(fileSystemList).mockResolvedValue({count: 1,- results: [entry('sql1', 'Research/Report', 'insight')],- })- jest.mocked(insightsList).mockResolvedValue({- count: 1,- results: [- {- id: 1,- short_id: 'sql1',- dashboard_tiles: [],- last_refresh: null,- cache_target_age: null,- next_allowed_client_refresh: null,- result: null,- hasMore: null,- columns: null,- created_at: null,- created_by: { ...MOCK_DEFAULT_BASIC_USER, hedgehog_config: null, role_at_organization: null },- updated_at: '2026-01-01T00:00:00Z',- last_modified_at: '2026-01-01T00:00:00Z',- last_modified_by: { ...MOCK_DEFAULT_BASIC_USER, hedgehog_config: null, role_at_organization: null },- is_sample: false,- effective_restriction_level: 21,- effective_privilege_level: 37,- user_access_level: 'editor',- timezone: 'UTC',- is_cached: false,- query_status: null,- hogql: null,- types: null,- resolved_date_range: {},- query_scan: null,- alerts: [],- filter_override_context: null,- last_viewed_at: null,- search_match_type: null,- },- ],+ results: [{ ...entry('sql1', 'Research/Report', 'insight'), meta: { content_type: 'application/sql' } }],})const original = {name: 'Report',@@ -131,6 +82,7 @@ describe('PostHog filesystem projection', () => {jest.mocked(apiMutator).mockResolvedValue(original)const fs = new PosthogFilesystem('42', signal)await fs.load()+ expect(insightsList).not.toHaveBeenCalled()expect(apiMutator).not.toHaveBeenCalled()const sql =await fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Report.sql')!.open!()@@ -181,6 +133,8 @@ describe('PostHog filesystem projection', () => {entry('nested', 'Research/Nested', 'folder'),entry('note1', 'Research/Notes'),entry('12', 'Other/Dashboard', 'dashboard'),+ { ...entry('sql1', 'Research/Query', 'insight'), meta: { content_type: 'application/sql' } },+ entry('trend1', 'Research/Trend', 'insight'),]jest.mocked(fileSystemList).mockImplementation(async (_, params) => {const { parent, depth, type } = params as { parent?: string; depth?: number; type?: string }@@ -208,7 +162,7 @@ describe('PostHog filesystem projection', () => {expect(fileSystemList).toHaveBeenCalledTimes(1)expect(fileSystemList).toHaveBeenLastCalledWith('42',- { parent: '', depth: 1, limit: 500, offset: 0 },+ { parent: '', depth: 1, include_content_type: true, limit: 500, offset: 0 },expect.anything())expect(notebooksList).not.toHaveBeenCalled()@@ -219,10 +173,10 @@ describe('PostHog filesystem projection', () => {expect(fileSystemList).toHaveBeenCalledTimes(2)expect(fileSystemList).toHaveBeenLastCalledWith('42',- { parent: 'Research', depth: 2, limit: 500, offset: 0 },+ { parent: 'Research', depth: 2, include_content_type: true, limit: 500, offset: 0 },expect.anything())- expect([...research.children!.keys()]).toEqual(['Nested', 'Notes.md'])+ expect([...research.children!.keys()]).toEqual(['Nested', 'Notes.md', 'Query.sql', 'Trend.json'])expect(notebooksRetrieve).not.toHaveBeenCalled()const note = research.children!.get('Notes.md')!await request(@@ -247,6 +201,9 @@ describe('PostHog filesystem projection', () => {expect(research.children!.has('New.md')).toBe(true)expect(files.children!.get('Other')!.children!.has('Dashboard.json')).toBe(true)expect(research.children!.get('Nested')!.children!.size).toBe(0)+ expect(insightsList).not.toHaveBeenCalled()+ expect(notebooksList).not.toHaveBeenCalled()+ expect(apiMutator).not.toHaveBeenCalled()expect(notebooksRetrieve).not.toHaveBeenCalled()entries = entries.map((item) => ({ ...item, path: item.path.replace(/^Research/, 'Published') }))await fs.load()@@ -295,10 +252,10 @@ describe('PostHog filesystem projection', () => {expect(fs.resolveReference(`/posthog/api/${name}/13.json`, '/', type)).toBe('13')expect([...directory.children!.keys()]).toEqual(['12.json', '13.json'])expect(jest.mocked(fileSystemList).mock.calls.map(([, params]) => params)).toEqual([- { type, limit: 500, offset: 0 },- { type, limit: 500, offset: 1 },- { type, limit: 500, offset: 0 },- { type, limit: 500, offset: 1 },+ { type, include_content_type: true, limit: 500, offset: 0 },+ { type, include_content_type: true, limit: 500, offset: 1 },+ { type, include_content_type: true, limit: 500, offset: 0 },+ { type, include_content_type: true, limit: 500, offset: 1 },])expect(notebooksList).not.toHaveBeenCalled()expect(apiMutator).not.toHaveBeenCalled()@@ -362,11 +319,7 @@ describe('PostHog filesystem projection', () => {'Expected a dashboard')expect(notebooksRetrieve).not.toHaveBeenCalled()- expect(notebooksList).toHaveBeenCalledWith(- '42',- { contains: 'markdown-notebook', limit: 500, offset: 0 },- expect.anything()- )+ expect(notebooksList).not.toHaveBeenCalled()const file = fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!expect(file.writable).toBe(true)const opened = await file.open!(read.signal)@@ -744,7 +697,10 @@ describe('PostHog filesystem projection', () => {.mockResolvedValueOnce({count: 3,next: null,- results: [entry('note2', 'Research/Notes'), entry('legacy', 'Research/Legacy')],+ results: [+ entry('note2', 'Research/Notes'),+ { ...entry('legacy', 'Research/Legacy'), meta: { content_type: 'application/json' } },+ ],})jest.mocked(notebooksRetrieve).mockImplementation(async (_, id) =>id === 'legacy' ? { ...notebook, content: { type: 'doc', content: [{ type: 'paragraph' }] } } : notebook@@ -762,11 +718,10 @@ describe('PostHog filesystem projection', () => {it('does not offer writes on viewer notebooks or expose entries without read access', async () => {jest.mocked(fileSystemList).mockResolvedValue({count: 2,- results: [entry('note1', 'Notes'), { ...entry('hidden', 'Hidden'), user_access_level: 'none' }],- })- jest.mocked(notebooksList).mockResolvedValue({- count: 1,- results: [{ ...notebookIndex, user_access_level: 'viewer' }],+ results: [+ { ...entry('note1', 'Notes'), user_access_level: 'viewer' },+ { ...entry('hidden', 'Hidden'), user_access_level: 'none' },+ ],})const fs = new PosthogFilesystem('42', new AbortController().signal)await fs.load()@@ -850,6 +805,22 @@ describe('PostHog filesystem projection', () => {expect(type.children!.get('12.json')).toBe(apiFile)})+ it('renames a file when its content type changes while browsing an overlapping API type', async () => {+ const note = entry('note1', 'Notes')+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [note] })+ const fs = new PosthogFilesystem('42', new AbortController().signal)+ const files = fs.root.children!.get('files')!+ await files.loadChildren!()+ const markdown = files.children!.get('Notes.md')!+ jest.mocked(fileSystemList).mockResolvedValue({+ count: 1,+ results: [{ ...note, meta: { content_type: 'application/json' } }],+ })+ await fs.root.children!.get('api')!.children!.get('notebook')!.loadChildren!()+ expect([...files.children!.keys()]).toEqual(['Notes.json'])+ await expect(markdown.open!()).rejects.toMatchObject({ errno: 116 })+ })+it('rejects invalid JSON and propagates API failures without retrying a failed update', async () => {jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [entry('12', 'Object', 'dashboard')] })jest.mocked(apiMutator).mockResolvedValue({ id: 12, name: 'Original' })diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex 39b2dc7c806b..798ef97f4091 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -19,13 +19,8 @@ import { cohortsPartialUpdate, cohortsRetrieve } from 'products/cohorts/frontendimport { dashboardsPartialUpdate, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'import { experimentsPartialUpdate, experimentsRetrieve } from 'products/experiments/frontend/generated/api'import { featureFlagsPartialUpdate, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'-import { notebooksList, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'-import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'-import {- insightsList,- insightsPartialUpdate,- insightsRetrieve,-} from 'products/product_analytics/frontend/generated/api'+import { notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'+import { insightsPartialUpdate, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'import { surveysPartialUpdate, surveysRetrieve } from 'products/surveys/frontend/generated/api'import { ConfirmTerminalOperation, TerminalConfirmation } from './terminalConfirmation'@@ -120,6 +115,11 @@ Try:open [path] opens a project file or folder in PostHog. With no path, it opens thecurrent folder. JSON files open their PostHog item, including files in /posthog/api.+Folders open in the Files tab when the simple side panel is enabled.++Optional tools download on first use: node, pi, nyancat, and doom.+In Doom, W/S move, A/D strafe, left/right arrows turn, Space fires, E opens doors,+and Shift runs. Use Capture mouse to turn with the mouse; left-click fires.Saving a .sql insight updates its query and preserves its query options.Use run report.sql to execute SQL, or run --help for JSON, CSV, and TSV exports.@@ -152,9 +152,9 @@ Directories load when you browse them and stay cached until ph refresh.The terminal starts without downloading the project tree. Browsing /posthog/filesloads one folder at a time; /posthog/api loads one object type at a time.Listing directories never downloads object contents. File contents load on open.-Sizes are zero until a file is opened, then show its last known size. The notebook-index loads when you first browse notebooks, without fetching their bodies.-SQL insight detection loads a metadata index when you first browse insights.+Sizes are zero until a file is opened, then show its last known size.+Filenames use content types from the filesystem listing. Notebook and insight+contents load only when you open a file.Run ph refresh to discover new or renamed objects. Unsupported object typesexpose their filesystem record as JSON. Legacy rich-text notebooks stay JSON.Characters that cannot appear in Unix filenames are percent-encoded. Duplicate@@ -215,8 +215,6 @@ export class PosthogFilesystem extends TerminalFilesystem {private readonly loadedDirectories = new Set<TerminalNode>()private readonly pendingDirectories = new Map<TerminalNode, Promise<void>>()private directoryQueue: Promise<void> = Promise.resolve()- private markdownNotebooks?: Map<string, NotebookMinimalApi>- private sqlInsights?: Set<string>async folderFor(ref: ProjectTreeRef | null): Promise<string | null> {if (!ref) {@@ -830,60 +828,6 @@ export class PosthogFilesystem extends TerminalFilesystem {return request}- private async loadNotebookIndex(): Promise<Map<string, NotebookMinimalApi>> {- if (this.markdownNotebooks) {- return this.markdownNotebooks- }- const notebooks = new Map<string, NotebookMinimalApi>()- let offset = 0- while (true) {- const page = await notebooksList(- this.projectId,- { contains: 'markdown-notebook', limit: 500, offset },- { signal: this.signal }- )- for (const notebook of page.results) {- notebooks.set(notebook.short_id, notebook)- }- if (!page.next) {- break- }- if (!page.results.length || offset > 50_000) {- throw new Error('This notebook index is too large for the terminal experiment.')- }- offset += page.results.length- }- this.markdownNotebooks = notebooks- return notebooks- }-- private async loadSqlIndex(): Promise<Set<string>> {- if (this.sqlInsights) {- return this.sqlInsights- }- const insights = new Set<string>()- let offset = 0- while (true) {- const page = await insightsList(- this.projectId,- { basic: true, insight: 'SQL', limit: 500, offset },- { signal: this.signal }- )- for (const insight of page.results) {- insights.add(insight.short_id)- }- if (!page.next) {- break- }- if (!page.results.length || offset > 50_000) {- throw new Error('This SQL insight index is too large for the terminal.')- }- offset += page.results.length- }- this.sqlInsights = insights- return insights- }-private directoryParams(node: TerminalNode): FileSystemListParams & { parent?: string; depth?: number; type?: string } {@@ -905,7 +849,7 @@ export class PosthogFilesystem extends TerminalFilesystem {while (true) {const page = await fileSystemList(this.projectId,- { ...params, limit: 500, offset },+ { ...params, include_content_type: true, limit: 500, offset },{ signal: this.signal })entries.push(...page.results)@@ -921,13 +865,7 @@ export class PosthogFilesystem extends TerminalFilesystem {private async loadDirectory(node: TerminalNode): Promise<void> {const entries = await this.directoryEntries(this.directoryParams(node))- if (entries.some((entry) => entry.type === 'insight')) {- await this.loadSqlIndex()- }- const markdownNotebooks = entries.some((entry) => entry.type === 'notebook')- ? await this.loadNotebookIndex()- : (this.markdownNotebooks ?? new Map<string, NotebookMinimalApi>())- this.mountEntries(entries, markdownNotebooks, true)+ this.mountEntries(entries, true)this.loadedDirectories.add(node)}@@ -968,16 +906,7 @@ export class PosthogFilesystem extends TerminalFilesystem {for (const entry of refreshed.values()) {merged.set(entry.id, entry)}- this.markdownNotebooks = undefined- this.sqlInsights = undefined- const entries = [...merged.values()]- if (entries.some((entry) => entry.type === 'insight')) {- await this.loadSqlIndex()- }- const markdownNotebooks = entries.some((entry) => entry.type === 'notebook')- ? await this.loadNotebookIndex()- : new Map<string, NotebookMinimalApi>()- this.mountEntries(entries, markdownNotebooks)+ this.mountEntries([...merged.values()])for (const node of directories) {if (!node.removed) {this.loadedDirectories.add(node)@@ -991,11 +920,7 @@ export class PosthogFilesystem extends TerminalFilesystem {return request}- private mountEntries(- entries: FileSystemApi[],- markdownNotebooks: Map<string, NotebookMinimalApi>,- incremental = false- ): void {+ private mountEntries(entries: FileSystemApi[], incremental = false): void {entries.sort((a, b) => a.path.localeCompare(b.path) || a.id.localeCompare(b.id))const previousNodes = incremental ? new Set<TerminalNode>() : this.mountedNodes()const directories = new Map(@@ -1018,11 +943,22 @@ export class PosthogFilesystem extends TerminalFilesystem {this.mountApiDirectories(directories)} else {for (const entry of entries) {- const extension = this.extension(entry, markdownNotebooks)- const existing = files.get(this.fileIdentity(entry, extension))- if (existing) {+ const extension = this.extension(entry)+ // A content-type change gives the entry a new extension, so the node under the old+ // extension is not reused below and must be retired here to avoid a stale duplicate.+ for (const candidate of ['.md', '.sql', '.json']) {+ const identity = this.fileIdentity(entry, candidate)+ const existing = files.get(identity)+ if (!existing) {+ continue+ }existing.parent!.children!.delete(existing.name)this.references.delete(this.mountedPath(existing))+ if (candidate !== extension) {+ files.delete(identity)+ this.projectNodes.delete(existing)+ existing.removed = true+ }}}}@@ -1035,11 +971,10 @@ export class PosthogFilesystem extends TerminalFilesystem {if (entry.type === 'folder' || entry.user_access_level === 'none') {continue}- const notebook = entry.type === 'notebook' ? markdownNotebooks.get(entry.ref ?? '') : undefinedconst parts = splitPath(entry.path)const basename = terminalFilename(parts.pop() ?? 'Untitled')const parent = this.parent(parts, this.files, directories)- const extension = this.extension(entry, markdownNotebooks)+ const extension = this.extension(entry)let name = basename.endsWith(extension) ? basename : `${basename}${extension}`if (parent.children!.has(name)) {name = `${basename}~${entry.id}${extension}`@@ -1048,15 +983,13 @@ export class PosthogFilesystem extends TerminalFilesystem {while (parent.children!.has(name)) {name = `${basename}~${entry.id}-${duplicate++}${extension}`}- const access = notebook?.user_access_level ?? entry.user_access_level+ const access = entry.user_access_levelconst writable =- !!this.objectApi(entry) &&- entry.user_access_level !== 'viewer' &&- (access === null || ['editor', 'manager'].includes(access ?? ''))+ !!this.objectApi(entry) && (access === null || ['editor', 'manager'].includes(access ?? ''))const file = this.mountFile(name,parent,- notebook+ extension === '.md'? (signal) => this.notebook(entry, signal): (signal) => this.document(entry, writable, signal, extension === '.sql'),writable,@@ -1100,10 +1033,17 @@ export class PosthogFilesystem extends TerminalFilesystem {return JSON.stringify([entry.id, entry.type, entry.ref, extension])}- private extension(entry: FileSystemApi, notebooks: Map<string, NotebookMinimalApi>): string {- return entry.type === 'notebook' && notebooks.has(entry.ref ?? '')+ private extension(entry: FileSystemApi): string {+ if (!this.validReference(entry)) {+ return '.json'+ }+ const contentType =+ entry.meta && typeof entry.meta === 'object' && 'content_type' in entry.meta+ ? entry.meta.content_type+ : undefined+ return entry.type === 'notebook' && contentType === 'text/markdown'? '.md'- : entry.type === 'insight' && this.sqlInsights?.has(entry.ref ?? '')+ : entry.type === 'insight' && contentType === 'application/sql'? '.sql': '.json'}diff --git a/frontend/src/scenes/terminal/terminal-packages.json b/frontend/src/scenes/terminal/terminal-packages.jsonindex bcb6fcda8e17..16b391979450 100644--- a/frontend/src/scenes/terminal/terminal-packages.json+++ b/frontend/src/scenes/terminal/terminal-packages.json@@ -28,14 +28,14 @@},"doom": {"name": "Doom (Freedoom)",- "version": "0.13.0-1",- "file": "archives/doom-0.13.0-1-linux-i386.tar.gz",- "sha256": "470aefa7b775d738b21377b9e764c37c006f730fa665f30acf65258fd42492b0",- "size": 10479126,- "archiveSize": 29480960,+ "version": "0.13.0-2",+ "file": "archives/doom-0.13.0-2-linux-i386.tar.gz",+ "sha256": "4943c6d37922eac98473d9d20554d02dd8cc01948fb81edc150ba30d2f0ae6c6",+ "size": 10501917,+ "archiveSize": 29552640,"dependencies": [],"commands": {- "doom": "/opt/posthog-packages/doom-0.13.0-1/bin/doom"+ "doom": "/opt/posthog-packages/doom-0.13.0-2/bin/doom"}},"sl": {@@ -87,7 +87,7 @@}}},- "baseUrl": "https://raw.githubusercontent.com/PostHog/terminal-assets/31fc564def31b2e90d863218ffd040c9dff0e0ed",+ "baseUrl": "https://raw.githubusercontent.com/PostHog/terminal-assets/745b60735f92fd480ff3aaf712b28c99ddd3221d","kernel": {"file": "images/linux-fb-bzimage.bin","sha256": "33ca60bd4832f0cf202845fa7ac1a60776c0215e8a20d21a3f07d3722f99e415"diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.tsindex 1bf1a1f32d22..5a75f6081bd8 100644--- a/frontend/src/scenes/terminal/terminalLogic.test.ts+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts@@ -1,13 +1,18 @@import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'import { waitFor } from '@testing-library/react'+import { router } from 'kea-router'import { commandLogic } from 'lib/components/Command/commandLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'+import { FILES_TREE_KEY } from '~/layout/panel-layout/navbar/tabs/navFilesTabLogic'+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'+import { projectTreeLogic } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { initKeaTests } from '~/test/init'import { PosthogFilesystem } from './posthogFilesystem'@@ -62,6 +67,43 @@ describe('terminal lifecycle', () => {afterEach(() => jest.restoreAllMocks())+ it.each([false, true])('opens folders with the simple side panel enabled: %s', (enabled) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.POSTHOG_TERMINAL]: true,+ [FEATURE_FLAGS.SIMPLE_SIDEPANEL]: enabled,+ })+ const push = jest.spyOn(router.actions, 'push')+ const url = urls.projectFiles('Research & notes/Reports')+ terminalLogic.actions.openUrl(url)+ if (enabled) {+ expect(push).not.toHaveBeenCalled()+ expect(panelLayoutLogic.values.navExperimentActiveTab).toBe('files')+ expect(projectTreeLogic({ key: FILES_TREE_KEY, root: 'project://' }).values.expandedFolders).toContain(+ 'project://Research & notes/Reports'+ )+ } else {+ expect(push).toHaveBeenCalledWith(url)+ }+ terminalLogic.actions.openUrl('/insights/example')+ expect(push).toHaveBeenCalledWith('/insights/example')+ })++ it.each([true, false])('keeps project-qualified folder links in their own project: %s', (sameProject) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.POSTHOG_TERMINAL]: true,+ [FEATURE_FLAGS.SIMPLE_SIDEPANEL]: true,+ })+ const push = jest.spyOn(router.actions, 'push')+ const projectId = MOCK_DEFAULT_TEAM.id + (sameProject ? 0 : 1)+ const url = `/project/${projectId}/files?folder=Reports`+ terminalLogic.actions.openUrl(url)+ if (sameProject) {+ expect(push).not.toHaveBeenCalled()+ } else {+ expect(push).toHaveBeenCalledWith(url)+ }+ })+it('does not boot without the flag and stops an active session on revocation', async () => {featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })terminalLogic.actions.attach(document.createElement('div'))diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.tsindex d484a9dca89b..72ccdc5edc3d 100644--- a/frontend/src/scenes/terminal/terminalLogic.ts+++ b/frontend/src/scenes/terminal/terminalLogic.ts@@ -2,13 +2,16 @@ import { MakeLogicType, actions, connect, isBreakpoint, kea, listeners, path, reimport { router } from 'kea-router'import { subscriptions } from 'kea-subscriptions'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { getProjectIdentifierInPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'+import { navFilesTabLogic } from '~/layout/panel-layout/navbar/tabs/navFilesTabLogic'import type { ProjectTreeRef } from '~/types'import { NinePServer } from './ninepServer'@@ -114,6 +117,9 @@ export interface terminalLogicActions {insertCommand: (command: string) => {command: string}+ openUrl: (url: string) => {+ url: string+ }paste: () => {value: true}@@ -177,6 +183,7 @@ export const terminalLogic = kea<terminalLogicType>([actions: [terminalDockLogic, ['focusTerminal', 'setRequestedFolder']],}),actions({+ openUrl: (url: string) => ({ url }),setConfirmation: (confirmation: TerminalConfirmation | null) => ({ confirmation }),answerConfirmation: (confirmation: TerminalConfirmation, approved: boolean) => ({ confirmation, approved }),setDisplayFullscreen: (fullscreen: boolean) => ({ fullscreen }),@@ -261,6 +268,21 @@ export const terminalLogic = kea<terminalLogicType>([],}),listeners(({ actions, values, cache }) => ({+ openUrl: ({ url }) => {+ const target = new URL(url, window.location.origin)+ const targetProjectId = getProjectIdentifierInPath(target.pathname)+ if (+ featureFlagLogic.values.featureFlags[FEATURE_FLAGS.SIMPLE_SIDEPANEL] &&+ target.origin === window.location.origin &&+ (targetProjectId === null || targetProjectId === String(values.currentTeamId)) &&+ removeProjectIdIfPresent(target.pathname) === urls.projectFiles()+ ) {+ cache.disposables.add(() => navFilesTabLogic.mount(), 'files-navigation')+ navFilesTabLogic.actions.openFolder(target.searchParams.get('folder') ?? '')+ } else {+ router.actions.push(url)+ }+ },followFolder: async (_, breakpoint) => {const runtime: TerminalRuntime | undefined = cache.runtimeconst filesystem: PosthogFilesystem | undefined = cache.filesystem@@ -485,7 +507,7 @@ export const terminalLogic = kea<terminalLogicType>([true)cache.filesystem = filesystem- new PosthogCommands(String(projectId), controller.signal, filesystem, (url) => router.actions.push(url))+ new PosthogCommands(String(projectId), controller.signal, filesystem, actions.openUrl)new TerminalAI(filesystem, String(projectId), controller.signal)actions.setStatus('booting')const server = new NinePServer(filesystem, (error) => {diff --git a/frontend/src/scenes/terminal/terminalPackages.ts b/frontend/src/scenes/terminal/terminalPackages.tsindex 07e6461b2d83..59cccb96a560 100644--- a/frontend/src/scenes/terminal/terminalPackages.ts+++ b/frontend/src/scenes/terminal/terminalPackages.ts@@ -15,6 +15,23 @@ export interface TerminalPackage {const CACHE_NAME = 'posthog-terminal-packages-v1'+// Doom configuration stores keyboard bindings as PC scancodes.+const DOOM_CONFIG = `key_up 17+key_down 31+key_strafeleft 30+key_straferight 32+key_left 75+key_right 77+key_fire 57+key_use 18+key_speed 42+use_mouse 1+mouseb_fire 0+mouseb_strafe -1+mouseb_forward -1+mouse_sensitivity 5+`+export class TerminalPackages {private downloads = new Map<string, Promise<Uint8Array>>()@@ -73,6 +90,8 @@ export class TerminalPackages {mount(): void {const directory = this.filesystem.directory('packages', this.filesystem.root)const bin = this.filesystem.directory('bin', this.filesystem.root)+ const config = this.filesystem.directory('config', this.filesystem.root)+ this.filesystem.text('doom.cfg', config, DOOM_CONFIG)const cases: string[] = []for (const [id, pkg] of Object.entries(this.packages)) {this.filesystem.file(`${id}.tar`, directory, async () => {@@ -93,7 +112,13 @@ export class TerminalPackages {...[...pkg.dependencies, id].map((dependency) => `sh /posthog/bin/install-tool ${dependency} || exit $?`),- `exec ${entrypoint} "$@"`,+ ...(command === 'doom'+ ? [+ 'mkdir -p /tmp/doom',+ '[ -f /tmp/doom/posthog-controls.cfg ] || cp /posthog/config/doom.cfg /tmp/doom/posthog-controls.cfg',+ `exec ${entrypoint} "$@" -config /tmp/doom/posthog-controls.cfg`,+ ]+ : [`exec ${entrypoint} "$@"`]),'',].join('\n'))diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.pyindex 78b43372bd7a..1c0f72a5d77a 100644--- a/posthog/api/file_system/file_system.py+++ b/posthog/api/file_system/file_system.py@@ -7,8 +7,9 @@ from functools import cached_propertyfrom typing import Any, Optional, castfrom uuid import UUID+from django.apps import appsfrom django.db import transaction-from django.db.models import Case, Exists, F, IntegerField, Q, QuerySet, Value, When+from django.db.models import Case, CharField, Exists, F, Func, IntegerField, Q, QuerySet, Value, Whenfrom django.db.models.functions import Concat, Lowerfrom drf_spectacular.utils import extend_schema@@ -87,6 +88,13 @@ def validate_file_system_path(path: Any) -> str:return path+class FileSystemListQuerySerializer(serializers.Serializer):+ include_content_type = serializers.BooleanField(+ default=False,+ help_text="Include meta.content_type for notebooks and insights on this page, without their contents.",+ )++class FileSystemDeleteQuerySerializer(serializers.Serializer):recursive = serializers.BooleanField(default=True,@@ -551,15 +559,88 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return queryset- def list(self, request, *args, **kwargs):+ def _add_content_types(self, results: builtins.list[dict[str, object]]) -> None:+ entry_teams = {+ str(entry_id): team_id+ for entry_id, team_id in FileSystem.objects.filter(+ team__project_id=self.team.project_id,+ id__in=[item["id"] for item in results if item.get("type") in ("notebook", "insight")],+ ).values_list("id", "team_id")+ }+ denied: set[tuple[str, str, int]] = set()+ for team_id in set(entry_teams.values()):+ entries = [+ (str(item["type"]), str(item["ref"]), team_id)+ for item in results+ if item.get("ref") and entry_teams.get(str(item["id"])) == team_id+ ]+ denied.update(+ (entry_type, ref, team_id)+ for entry_type, ref in entries_missing_access_level(+ entries, self.user_access_control, self.team.project_id, "viewer"+ )+ )+ content_types: dict[tuple[str, int, str], str] = {}+ for entry_type, app_label, model_name in (+ ("notebook", "notebooks", "Notebook"),+ ("insight", "product_analytics", "Insight"),+ ):+ refs = {+ item["ref"]+ for item in results+ if item.get("type") == entry_type+ and item.get("user_access_level") != "none"+ and isinstance(item.get("ref"), str)+ and item["ref"]+ }+ if not refs:+ continue+ model = apps.get_model(app_label, model_name)+ queryset = model.objects.filter(team__project_id=self.team.project_id, short_id__in=refs, deleted=False)+ if entry_type == "notebook":+ queryset = queryset.alias(+ _markdown_type=Func(+ F("content__content__0__attrs__markdown"), function="jsonb_typeof", output_field=CharField()+ )+ ).filter(+ visibility="default",+ content__content__0__type="ph-markdown-notebook",+ content__content__1__isnull=True,+ _markdown_type="string",+ )+ content_type = "text/markdown"+ else:+ queryset = queryset.filter(query__source__kind="HogQLQuery")+ content_type = "application/sql"+ for team_id, ref in queryset.values_list("team_id", "short_id"):+ if (entry_type, ref, team_id) not in denied:+ content_types[(entry_type, team_id, ref)] = content_type+ for item in results:+ if item.get("type") not in ("notebook", "insight"):+ continue+ meta = item.get("meta")+ item["meta"] = {+ **(meta if isinstance(meta, dict) else {}),+ "content_type": content_types.get(+ (str(item["type"]), entry_teams.get(str(item["id"]), -1), str(item.get("ref"))),+ "application/json",+ ),+ }++ @extend_schema(parameters=[FileSystemListQuerySerializer])+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ query_serializer = FileSystemListQuerySerializer(data=request.query_params)+ query_serializer.is_valid(raise_exception=True)order_by_param = request.query_params.get("order_by")# Recents (the high-volume, timeout-prone path) is served view-log-first, with or without a# search term — one query function, no join, no COUNT(*).if order_by_param in ("-last_viewed_at", "last_viewed_at") and request.user.is_authenticated:- return self._list_recents(request, descending=order_by_param == "-last_viewed_at")-- response = super().list(request, *args, **kwargs)- response.data["users"] = self._created_by_users(response.data.get("results", []))+ response = self._list_recents(request, descending=order_by_param == "-last_viewed_at")+ else:+ response = super().list(request, *args, **kwargs)+ response.data["users"] = self._created_by_users(response.data.get("results", []))+ if query_serializer.validated_data["include_content_type"]:+ self._add_content_types(response.data.get("results", []))return responsedef _created_by_users(self, results: builtins.list[dict[str, Any]]) -> builtins.list[dict[str, Any]]:diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.pyindex f205b78ed4fc..4a3493f1e8a9 100644--- a/posthog/api/file_system/test/test_file_system.py+++ b/posthog/api/file_system/test/test_file_system.py@@ -5,7 +5,7 @@ from typing import Any, TypedDict, castimport pytestimport time_machinefrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.core.cache import cachefrom django.db import connection@@ -68,6 +68,81 @@ class TestFileSystemAPI(APIBaseTest):self.assertEqual(response_data["count"], 0)self.assertEqual(response_data["results"], [])+ @parameterized.expand([(False,), (True,)])+ def test_list_content_types_without_object_contents(self, include_content_type: bool) -> None:+ markdown = Notebook.objects.create(+ team=self.team,+ short_id="markdown",+ content={+ "type": "doc",+ "content": [{"type": "ph-markdown-notebook", "attrs": {"markdown": "# Example"}}],+ },+ )+ legacy = Notebook.objects.create(+ team=self.team, short_id="legacy", content={"type": "doc", "content": [{"type": "paragraph"}]}+ )+ sql = Insight.objects.create(+ team=self.team,+ short_id="sqlquery",+ query={"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},+ )+ standard = Insight.objects.create(team=self.team, short_id="standard")+ sibling_team = Team.objects.create(project=self.project, organization=self.organization)+ Notebook.objects.create(team=sibling_team, short_id=markdown.short_id, content=legacy.content)+ Insight.objects.create(team=sibling_team, short_id=sql.short_id)+ for name, entry_type, ref in (+ ("Other notebook", "notebook", markdown.short_id),+ ("Other insight", "insight", sql.short_id),+ ):+ FileSystem.objects.create(team=sibling_team, path=f"Reports/{name}", depth=2, type=entry_type, ref=ref)+ other_team = Team.objects.create(organization=self.organization)+ Notebook.objects.create(team=other_team, short_id="foreign", content=markdown.content)+ entries = [+ ("Markdown", "notebook", markdown.short_id, "text/markdown"),+ ("Legacy", "notebook", legacy.short_id, "application/json"),+ ("SQL", "insight", sql.short_id, "application/sql"),+ ("Standard", "insight", standard.short_id, "application/json"),+ ("Missing", "notebook", "foreign", "application/json"),+ ]+ for name, entry_type, ref, _ in entries:+ FileSystem.objects.create(+ team=self.team, path=f"Reports/{name}", depth=2, type=entry_type, ref=ref, meta={"label": "example"}+ )+ response = self.client.get(+ f"/api/projects/{self.team.id}/file_system/",+ {"parent": "Reports", "depth": "2", "include_content_type": str(include_content_type).lower()},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = {item["path"]: item for item in response.json()["results"]}+ self.assertEqual(+ set(results),+ {f"Reports/{name}" for name, _, _, _ in entries} | {"Reports/Other notebook", "Reports/Other insight"},+ )+ for name, _, _, content_type in entries:+ expected_meta = {"label": "example"}+ if include_content_type:+ expected_meta["content_type"] = content_type+ self.assertEqual(results[f"Reports/{name}"]["meta"], expected_meta)+ self.assertNotIn("content", results[f"Reports/{name}"])+ self.assertNotIn("query", results[f"Reports/{name}"])+ for name in ("Other notebook", "Other insight"):+ self.assertEqual(+ results[f"Reports/{name}"]["meta"],+ {"content_type": "application/json"} if include_content_type else {},+ )+ if include_content_type:+ markdown.content = legacy.content+ markdown.save()+ refreshed = self.client.get(+ f"/api/projects/{self.team.id}/file_system/",+ {"ref": str(markdown.short_id), "include_content_type": "true"},+ )+ self.assertEqual(refreshed.json()["results"][0]["meta"]["content_type"], "application/json")++ def test_list_rejects_invalid_content_type_parameter(self) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"include_content_type": "invalid"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_create_file(self):"""Ensure that we can create a FileSystem object for our team.@@ -1505,6 +1580,40 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):delete_response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")self.assertEqual(delete_response.status_code, status.HTTP_404_NOT_FOUND, delete_response.content)+ @parameterized.expand([("notebook", "text/markdown"), ("insight", "application/sql")])+ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_content_type_requires_access_to_the_backing_object(+ self, entry_type: str, content_type: str, mock_flag: MagicMock+ ) -> None:+ obj: Notebook | Insight+ if entry_type == "notebook":+ obj = Notebook.objects.create(+ team=self.team,+ created_by=self.other_user,+ content={"type": "doc", "content": [{"type": "ph-markdown-notebook", "attrs": {"markdown": "# Note"}}]},+ )+ else:+ obj = Insight.objects.create(+ team=self.team,+ created_by=self.other_user,+ query={"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},+ )+ self._create_access_control(resource=entry_type, resource_id=str(obj.pk), access_level="none")+ entry = FileSystem.objects.create(+ team=self.team, path="Docs/Shortcut", depth=2, type=entry_type, ref=obj.short_id, created_by=self.user+ )+ response = self.client.get(+ f"/api/projects/{self.team.id}/file_system/", {"path": entry.path, "include_content_type": "true"}+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"][0]["meta"]["content_type"], "application/json")++ self._grant_to_user(entry_type, str(obj.pk), "viewer")+ response = self.client.get(+ f"/api/projects/{self.team.id}/file_system/", {"path": entry.path, "include_content_type": "true"}+ )+ self.assertEqual(response.json()["results"][0]["meta"]["content_type"], content_type)+def test_undo_delete_refuses_an_object_that_is_not_deleted(self):flag = FeatureFlag.objects.create(team=self.team,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 674a24e0f081..d0b0bb9ef8be 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -109314,6 +109314,10 @@ export namespace Schemas {};export type FileSystemListParams = {+ /**+ * Include meta.content_type for notebooks and insights on this page, without their contents.+ */+ include_content_type?: boolean;/*** Number of results to return per page.*/