: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(terminal): open project files and folders in posthog (#105371)
Marius Andraab794ddc737f
diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.tsindex 2f692e6c6a88..9bbe733c0551 100644--- a/frontend/src/scenes/terminal/posthogCommands.test.ts+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts@@ -37,6 +37,7 @@ jest.mock('products/product_analytics/frontend/generated/api', () => ({describe('PostHog terminal commands', () => {let commands: PosthogCommandslet filesystem: PosthogFilesystem+ const navigate = jest.fn()const cwd = '/posthog/files/Research'const author = {id: 1,@@ -123,7 +124,37 @@ describe('PostHog terminal commands', () => {const signal = new AbortController().signalfilesystem = new PosthogFilesystem('42', signal)await filesystem.load()- commands = new PosthogCommands('42', signal, filesystem)+ commands = new PosthogCommands('42', signal, filesystem, navigate)+ })++ it.each([+ [[], '/files?folder=Research'],+ [['.'], '/files?folder=Research'],+ [['..'], '/files'],+ [['Notes.md'], '/notebooks/shortnote'],+ [['/posthog/api/notebook/shortnote.json'], '/notebooks/shortnote'],+ ])('opens %j in PostHog', async (args, url) => {+ await commands.execute(['open', ...args], cwd)+ expect(navigate).toHaveBeenCalledWith(url)+ expect(notebooksRetrieve).not.toHaveBeenCalled()+ expect(mcpServerInstallationsAvailableToolsRetrieve).not.toHaveBeenCalled()+ })++ it.each([['missing.md'], ['/tmp/local.json'], ['Notes.md', 'another.md']])(+ 'does not navigate for invalid open arguments %j',+ async (...args) => {+ await expect(commands.execute(['open', ...args], cwd)).rejects.toThrow()+ expect(navigate).not.toHaveBeenCalled()+ }+ )++ it('does not navigate after the terminal stops while resolving a path', async () => {+ const controller = new AbortController()+ commands = new PosthogCommands('42', controller.signal, filesystem, navigate)+ const opening = commands.execute(['open', 'Notes.md'], cwd)+ controller.abort()+ await expect(opening).rejects.toThrow('terminal stopped')+ expect(navigate).not.toHaveBeenCalled()})it.each([diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.tsindex 7151052cb419..021120b288fb 100644--- a/frontend/src/scenes/terminal/posthogCommands.ts+++ b/frontend/src/scenes/terminal/posthogCommands.ts@@ -45,6 +45,7 @@ ph <command> --json '{...}' Supply a JSON arguments objectph <command> --json @args.json Read arguments from a Linux fileph <command> --json - Read arguments from stdinph refresh Reload the project tree and connected tool catalog+ph open [path] Open a project file or folder in PostHog (defaults to .)Examples:ph notebooks-list --limit 10 | jq .results@@ -135,7 +136,8 @@ export class PosthogCommands {constructor(private projectId: string,private signal: AbortSignal,- private filesystem: PosthogFilesystem+ private filesystem: PosthogFilesystem,+ private navigate: (url: string) => void) {this.toolDirectory = filesystem.directory('tools', filesystem.root)const options = { signal }@@ -362,6 +364,17 @@ export class PosthogCommands {async execute(argv: string[], cwd: string): Promise<unknown> {const [name = 'help', ...rest] = argv+ if (name === 'open') {+ if (rest.length > 1) {+ throw new Error('Use open with one file or folder path. Quote paths containing spaces.')+ }+ const url = await this.filesystem.navigationUrl(rest[0] ?? '.', cwd)+ if (this.signal.aborted) {+ throw new Error('The terminal stopped. Start it again before opening a file.')+ }+ this.navigate(url)+ return `Opened ${rest[0] ?? '.'} in PostHog.`+ }if (name === 'help' || name === '--help') {if (!rest.length) {return helpdiff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.tsindex 8c18dc094346..835475381943 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts@@ -210,6 +210,44 @@ describe('PostHog filesystem projection', () => {})+ it('resolves navigation from lazy folders and file identities without reading their contents', async () => {+ const folder = 'Research & notes'+ const entries = [+ entry('folder', folder, 'folder'),+ entry('note1', `${folder}/Notes`),+ { ...entry('query', `${folder}/Query.sql`, 'insight'), href: '/insights/query' },+ entry('12', `${folder}/Overview`, 'dashboard'),+ ]+ jest.mocked(fileSystemList).mockImplementation(async (_, params) => {+ const { parent, depth } = params as { parent?: string; depth?: number }+ const results = entries.filter(+ (item) =>+ item.path.split('/').length === depth && item.path.split('/').slice(0, -1).join('/') === parent+ )+ return { count: results.length, results }+ })+ const fs = new PosthogFilesystem('42', new AbortController().signal)+ expect(await fs.navigationUrl(folder, '/posthog/files')).toBe('/files?folder=Research%20%26%20notes')+ expect(fileSystemList).toHaveBeenCalledTimes(1)+ expect(await fs.navigationUrl('Notes.md', `/posthog/files/${folder}`)).toBe('/notebooks/note1')+ expect(await fs.navigationUrl('Query.sql.json', `/posthog/files/${folder}`)).toBe('/insights/query')+ expect(await fs.navigationUrl('Overview.json', `/posthog/files/${folder}`)).toBe('/dashboard/12')+ expect(notebooksRetrieve).not.toHaveBeenCalled()+ expect(fileSystemRetrieve).not.toHaveBeenCalled()+ })++ it.each(['https://example.com', '//example.com', '/\\example.com', 'javascript:alert(1)', '/\n/example.com'])(+ 'rejects a file destination outside PostHog: %j',+ async (href) => {+ jest.mocked(fileSystemList).mockResolvedValue({+ count: 1,+ results: [{ ...entry('link', 'Link', 'unknown'), href }],+ })+ const fs = new PosthogFilesystem('42', new AbortController().signal)+ await expect(fs.navigationUrl('Link.json', '/posthog/files')).rejects.toThrow('no PostHog page')+ }+ )+it('projects markdown without changing the stored path and saves with the version it read', async () => {const session = new AbortController()const read = new AbortController()diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex 17a58e370e27..cf52b86b5033 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -1,4 +1,5 @@import apiMutator from 'lib/api-orval-mutator'+import { urls } from 'scenes/urls'import {fileSystemCreate,@@ -106,6 +107,11 @@ Try:ph helpph tools notebookph notebook-get '/posthog/files/Unfiled/Notebooks/My notebook.md'+ open .+ open '/posthog/files/Unfiled/Notebooks/My notebook.md'++open [path] opens a project file or folder in PostHog. With no path, it opens the+current folder. JSON files open their PostHog item, including files in /posthog/api.Saving an existing .md notebook updates PostHog using your current permissions.JSON files for notebooks, dashboards, insights, feature flags, cohorts, actions,@@ -183,6 +189,43 @@ export class PosthogFilesystem extends TerminalFilesystem {private directoryQueue: Promise<void> = Promise.resolve()private markdownNotebooks?: Map<string, NotebookMinimalApi>+ async navigationUrl(value: string, cwd: string): Promise<string> {+ const parts = (value.startsWith('/') ? value : `${cwd}/${value}`).split('/').filter(Boolean)+ if (parts.shift() !== 'posthog') {+ throw new Error('Open a project file or folder under /posthog/files or /posthog/api.')+ }+ let node: TerminalNode | undefined = this.root+ for (const part of parts) {+ if (!node) {+ break+ }+ if (part === '..') {+ node = node.parent+ } else if (part !== '.') {+ await node.loadChildren?.()+ node = node.children?.get(part) ?? node.lookupChild?.(part)+ }+ }+ if (!node || node.removed) {+ throw new Error(`No project file or folder at ${value}. Run ph refresh if it was just created.`)+ }+ const projectNode = this.projectNodes.get(node)+ if (node.children && projectNode) {+ return urls.projectFiles(joinPath(projectNode.parts))+ }+ const entry = this.references.get(this.mountedPath(node))+ const type = entry?.type+ const definition =+ type && Object.hasOwn(fileSystemTypes, type)+ ? fileSystemTypes[type as keyof typeof fileSystemTypes]+ : undefined+ const href = entry?.href || (entry?.ref && definition?.href(entry.ref))+ if (!href || !href.startsWith('/') || href.startsWith('//') || /[\\\x00-\x20]/.test(href)) {+ throw new Error('This path has no PostHog page. Use cat to read the file in the terminal.')+ }+ return href+ }+async loadReference(value: string, cwd: string): Promise<void> {if (!value.includes('/') && !/\.(md|json)$/.test(value)) {returndiff --git a/frontend/src/scenes/terminal/terminalCommands.ts b/frontend/src/scenes/terminal/terminalCommands.tsindex 9ce7a4ff0c4c..c50157f77766 100644--- a/frontend/src/scenes/terminal/terminalCommands.ts+++ b/frontend/src/scenes/terminal/terminalCommands.ts@@ -1,5 +1,23 @@import { MAX_TERMINAL_FILE_BYTES, TerminalFilesystem } from './terminalFilesystem'+const OPEN_SCRIPT = String.raw`#!/bin/sh+set -eu+if [ "$#" -gt 1 ]; then+ printf '%s\n' 'Use open with one file or folder path. Quote paths containing spaces.' >&2+ exit 1+fi+if [ "$#" -eq 0 ]; then+ set -- .+fi+target="$1"+case "$target" in+ /*) ;;+ *) target="$PWD/$target" ;;+esac+target=$(realpath "$target")+exec ph open "$target"+`+export const PH_SCRIPT = String.raw`#!/bin/shset -euset -o pipefail@@ -89,5 +107,6 @@ export class TerminalCommands {true)filesystem.text('ph', filesystem.directory('bin', filesystem.root), PH_SCRIPT)+ filesystem.text('open', filesystem.directory('bin', filesystem.root), OPEN_SCRIPT)}}diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.tsindex af617d1c37b3..7d57b4ce0f79 100644--- a/frontend/src/scenes/terminal/terminalLogic.ts+++ b/frontend/src/scenes/terminal/terminalLogic.ts@@ -1,4 +1,5 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { router } from 'kea-router'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -227,7 +228,7 @@ export const terminalLogic = kea<terminalLogicType>([try {const filesystem = new PosthogFilesystem(String(projectId), controller.signal)cache.filesystem = filesystem- new PosthogCommands(String(projectId), controller.signal, filesystem)+ new PosthogCommands(String(projectId), controller.signal, filesystem, (url) => router.actions.push(url))actions.setStatus('booting')const server = new NinePServer(filesystem, (error) => {if (!controller.signal.aborted) {diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.tsindex 2b8031602edc..018d42cd6934 100644--- a/frontend/src/scenes/terminal/terminalRuntime.ts+++ b/frontend/src/scenes/terminal/terminalRuntime.ts@@ -158,6 +158,7 @@ export class TerminalRuntime {'ln -sf /opt/posthog-tools/lib/ld-musl-i386.so.1 /lib/ld-musl-i386.so.1','cp /posthog/bin/jq /usr/bin/jq && chmod +x /usr/bin/jq || exit','cp /posthog/bin/ph /usr/bin/ph && chmod +x /usr/bin/ph || exit',+ 'cp /posthog/bin/open /usr/bin/open && chmod +x /usr/bin/open || exit',...Object.values(packageManifest.packages).flatMap((pkg) =>Object.keys(pkg.commands).map((command) =>