: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): run sql files and follow project folders (#105435)
Marius Andraf6bd68684c00
diff --git a/docs/published/handbook/engineering/project-structure.md b/docs/published/handbook/engineering/project-structure.mdindex 58a19f45e452..cdf42784bc3f 100644--- a/docs/published/handbook/engineering/project-structure.md+++ b/docs/published/handbook/engineering/project-structure.md@@ -47,6 +47,16 @@ The PostHog web application, built with React and TypeScript. Uses [Kea](https:/- `src/queries` – Query builder and data visualization components- `src/toolbar` – Code for the [PostHog Toolbar](https://posthog.com/docs/user-guides/toolbar)+The app-level terminal lives in `src/scenes/terminal`.+SQL insights appear as editable `.sql` files; their full JSON remains editable under `/posthog/api/insight`.+Saving SQL preserves the insight's other query options, and JSON saves send only changed fields through the existing APIs.+`run report.sql` executes a SQL file in the current project and prints a Markdown table; `--json`, `--csv`, and `--tsv` select export formats.+CSV and TSV exports escape text that spreadsheets could interpret as formulas.+Use `--json` to inspect result metadata, including `hasMore`, and `/tmp` for export files.+The interactive Bash shell completes `ph` command names, aliases, connected tools, and argument names with Tab.+The terminal follows the current resource's folder while its prompt is empty.+Running commands, editors, and partially typed input prevent a folder change.+### `posthog`The Django backend application. Key subdirectories:diff --git a/frontend/bin/build-terminal-tools.py b/frontend/bin/build-terminal-tools.pyindex 4a84b9a9f980..85a55b9f6128 100644--- a/frontend/bin/build-terminal-tools.py+++ b/frontend/bin/build-terminal-tools.py@@ -44,7 +44,7 @@ def build() -> None:data = download(f"{manifest['repository']}/{package['file']}", "sha256", package["sha256"])# APK signatures, metadata, and payload are concatenated tar streams.with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz", ignore_zeros=True) as archive:- members = [member for member in archive if member.name.startswith(("etc/", "lib/", "usr/"))]+ members = [member for member in archive if member.name.startswith(("bin/", "etc/", "lib/", "usr/"))]archive.extractall(tools, members=members, filter="data")licenses = tools / "licenses"@@ -68,13 +68,14 @@ def build() -> None:wrappers = root / "usr/bin"wrappers.mkdir(parents=True, exist_ok=True)- for command in ("nano", "tree", "ncdu", "mc", "mcview", "mcedit", "mcdiff"):+ for command in ("bash", "nano", "tree", "ncdu", "mc", "mcview", "mcedit", "mcdiff"):arguments = ""if command == "nano":arguments = f"--rcfile=/{PREFIX}/etc/nanorc "elif command.startswith("mc"):arguments = "-u "wrapper = wrappers / command+ binary = f"bin/{command}" if command == "bash" else f"usr/bin/{command}"# Isolate musl and ncurses from the guest's existing uClibc programs.wrapper.write_text("#!/bin/sh\n"@@ -82,7 +83,7 @@ def build() -> None:'export TZ="$(cat /etc/TZ)"\n'f"exec /{PREFIX}/lib/ld-musl-i386.so.1 "f"--library-path /{PREFIX}/lib:/{PREFIX}/usr/lib "- f'/{PREFIX}/usr/bin/{command} {arguments}"$@"\n'+ f'/{PREFIX}/{binary} {arguments}"$@"\n')wrapper.chmod(0o755)diff --git a/frontend/public/terminal/tools-manifest.json b/frontend/public/terminal/tools-manifest.jsonindex 719c3b9ed91a..539336004953 100644--- a/frontend/public/terminal/tools-manifest.json+++ b/frontend/public/terminal/tools-manifest.json@@ -1,6 +1,14 @@{"repository": "https://dl-cdn.alpinelinux.org/alpine/v3.22/main/x86","packages": [+ {+ "file": "bash-5.2.37-r0.apk",+ "sha256": "6a139a0072d450d3428b15798268871fbae2934a0c71b38784af9dc7b2d4e9c1"+ },+ {+ "file": "readline-8.2.13-r1.apk",+ "sha256": "29e35b5876481d0d1d4f60fdfdbd59a0c974d86e6355f7c38ea85518645ada6b"+ },{"file": "e2fsprogs-libs-1.47.2-r2.apk","sha256": "8a3009b0b395ea5a8677b7fe140348d2a7024cc92b87b0d6bff5c41f09fd95a9"@@ -91,6 +99,20 @@}],"sources": [+ {+ "name": "bash",+ "url": "https://ftp.gnu.org/gnu/bash/bash-5.2.tar.gz",+ "sha512": "5647636223ba336bf33e0c65e516d8ebcf6932de8b44f37bc468eedb87579c628ad44213f78534beb10f47aebb9c6fa670cb0bed3b4e7717e5faf7e9a1ef81ae",+ "recipe": "https://github.com/alpinelinux/aports/tree/dfdce3cefb431614e410ac9bc3665d33ea45020c/main/bash",+ "license_files": ["bash-5.2/COPYING"]+ },+ {+ "name": "readline",+ "url": "https://ftp.gnu.org/gnu/readline/readline-8.2.tar.gz",+ "sha512": "0a451d459146bfdeecc9cdd94bda6a6416d3e93abd80885a40b334312f16eb890f8618a27ca26868cebbddf1224983e631b1cbc002c1a4d1cd0d65fba9fea49a",+ "recipe": "https://github.com/alpinelinux/aports/tree/be0833caee3020f089f02c5d7223e971a9a11ffb/main/readline",+ "license_files": ["readline-8.2/COPYING"]+ },{"name": "nano","url": "https://distfiles.alpinelinux.org/distfiles/v3.22/nano-8.4.tar.xz",diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.tsindex f911c62aff46..df6a28a22c51 100644--- a/frontend/src/scenes/max/maxLogic.test.ts+++ b/frontend/src/scenes/max/maxLogic.test.ts@@ -55,7 +55,10 @@ describe('maxLogic', () => {initKeaTests()})- afterEach(() => {+ afterEach(async () => {+ if (logic?.isMounted()) {+ await expectLogic(logic).toFinishAllListeners()+ }threadLogic?.unmount()threadLogic = nullsidePanelStateLogic.unmount()diff --git a/frontend/src/scenes/terminal/TerminalScene.stories.tsx b/frontend/src/scenes/terminal/TerminalScene.stories.tsxindex 16f4a68f91a2..d94c1492a202 100644--- a/frontend/src/scenes/terminal/TerminalScene.stories.tsx+++ b/frontend/src/scenes/terminal/TerminalScene.stories.tsx@@ -106,8 +106,16 @@ const meta: Meta<typeof TerminalScene> = {{ id: item.ref, name: item.name, description: 'Terminal demo', user_access_level: 'editor' },]))+ objectData.set('demoinsight', {+ ...objectData.get('demoinsight'),+ query: { kind: 'DataTableNode', source: { kind: 'HogQLQuery', query: 'select 42 as answer' } },+ })useStorybookMocks({get: {+ '/api/projects/:projectId/insights/': [+ 200,+ { count: 1, results: [{ short_id: 'demoinsight' }], next: null },+ ],...Object.fromEntries(objects.map((item) => [`/api/projects/:projectId/${item.route}/${item.ref}/`,@@ -190,6 +198,10 @@ const meta: Meta<typeof TerminalScene> = {],},post: {+ '/api/projects/:projectId/query/:queryKind/': [+ 200,+ { columns: ['answer'], results: [[42]], types: ['Int64'], hasMore: false },+ ],'/api/projects/:projectId/file_system/': async ({ request }) => {const { path } = (await request.json()) as { path: string }const id = crypto.randomUUID()diff --git a/frontend/src/scenes/terminal/assets/hashes.json b/frontend/src/scenes/terminal/assets/hashes.jsonindex a97420ed4438..598d83d20d4c 100644--- a/frontend/src/scenes/terminal/assets/hashes.json+++ b/frontend/src/scenes/terminal/assets/hashes.json@@ -1,3 +1,3 @@{- "toolsSha256": "50c8d847c3811249d512245b0b506cfab5cc4b625cc5fa6079cb605a7681b2cc"+ "toolsSha256": "7c1fc7fed64aa0abc63bf257fbdbe607ed2ff7ae0afb7733ef03c3caefc6218f"}diff --git a/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin b/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.binindex 357b906fbf9b..893f047518f1 100644Binary files a/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin and b/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin differdiff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.tsindex 3e030a9facfe..1ddf866ff89e 100644--- a/frontend/src/scenes/terminal/posthogCommands.test.ts+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts@@ -2,6 +2,7 @@ import { waitFor } from '@testing-library/react'import { fileSystemList } from '~/generated/core/api'import type { FileSystemApi } from '~/generated/core/api.schemas'+import { performQuery } from '~/queries/query'import {mcpServerInstallationsAvailableToolsRetrieve,@@ -20,6 +21,9 @@ import { PosthogCommands } from './posthogCommands'import { PosthogFilesystem } from './posthogFilesystem'import { MAX_TERMINAL_FILE_BYTES } from './terminalFilesystem'+jest.mock('scenes/teamLogic', () => ({ teamLogic: { values: { currentTeamId: 42 } } }))+jest.mock('~/queries/query', () => ({ performQuery: jest.fn() }))+jest.mock('~/generated/core/api', () => ({ fileSystemList: jest.fn() }))jest.mock('products/notebooks/frontend/generated/api', () => ({notebooksList: jest.fn(),@@ -49,6 +53,67 @@ describe('PostHog terminal commands', () => {hedgehog_config: null,}+ it.each([+ ['--markdown', '| answer |\n| --- |\n| 42 |'],+ ['--csv', 'answer\n42'],+ ['--tsv', 'answer\n42'],+ ['--json', { columns: ['answer'], results: [[42]], types: ['Int64'], hasMore: true }],+ ])('runs local SQL with %s output', async (format, expected) => {+ jest.mocked(performQuery).mockResolvedValue({+ columns: ['answer'],+ results: [[42]],+ types: ['Int64'],+ hasMore: true,+ })+ expect(await commands.execute(['run', '/tmp/report.sql', 'select 42 as answer', format], cwd)).toEqual(expected)+ expect(performQuery).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'HogQLQuery', query: 'select 42 as answer' }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ 'force_blocking'+ )+ })++ it.each(['--csv', '--tsv'])(+ 'escapes spreadsheet formulas in %s exports while preserving numbers',+ async (format) => {+ jest.mocked(performQuery).mockResolvedValue({+ columns: ['=header'],+ results: [['=1+1'], ['+1+1'], ['-1+1'], ['@SUM(1)'], ['\t=1+1'], ['\r=1+1'], [-42], [null], ['a"b']],+ })+ expect(await commands.execute(['run', '/tmp/report.sql', 'select value', format], cwd)).toBe(+ [+ '"\'=header"',+ '"\'=1+1"',+ '"\'+1+1"',+ '"\'-1+1"',+ '"\'@SUM(1)"',+ '"\'\t=1+1"',+ '"\'\r=1+1"',+ '-42',+ '',+ '"a""b"',+ ].join('\n')+ )+ }+ )++ it('completes aliases and JSON arguments without invoking commands', async () => {+ expect(await commands.execute(['_complete', '1', 'op', 'ph', ''], cwd)).toBe('open')+ expect(await commands.execute(['_complete', '1', 'notebook-g', 'ph', ''], cwd)).toBe('notebook-get')+ expect(await commands.execute(['_complete', '2', '--ti', 'notebook-create', 'notebook-create'], cwd)).toBe(+ '--title'+ )+ expect(await commands.execute(['_complete', '2', '--j', 'notebook-create', 'notebook-create'], cwd)).toBe(+ '--json'+ )+ expect(await commands.execute(['_complete', '3', '', '--json', 'notebook-create'], cwd)).toBe('')+ for (const command of ['help', 'tools', 'refresh', 'open']) {+ expect(await commands.execute(['_complete', '2', '--', command, command], cwd)).toBe('')+ }+ expect(notebooksCreate).not.toHaveBeenCalled()+ expect(mcpServerInstallationsCallToolCreate).not.toHaveBeenCalled()+ })+it.each([['notebook-delete', 'shortnote'],['notebook-update', 'shortnote', '--deleted'],diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.tsindex f83971ff56d0..4aa3dcad355c 100644--- a/frontend/src/scenes/terminal/posthogCommands.ts+++ b/frontend/src/scenes/terminal/posthogCommands.ts@@ -1,5 +1,9 @@import { z } from 'zod'+import { teamLogic } from 'scenes/teamLogic'++import { performQuery } from '~/queries/query'+import { dashboardsList, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'import { featureFlagsList, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'import {@@ -16,8 +20,9 @@ import { NotebooksPartialUpdateBody } from 'products/notebooks/frontend/generateimport { insightsList, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'import { markdownNode, PosthogFilesystem, terminalFilename } from './posthogFilesystem'-import { TerminalCommands } from './terminalCommands'+import { RUN_HELP, TerminalCommands } from './terminalCommands'import { parseRemovalArguments, RM_SCRIPT } from './terminalRemove'+import { terminalQueryTable } from './terminalSql'interface Command {name: string@@ -46,6 +51,8 @@ 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+run <file.sql> Run SQL and print a Markdown table+run --help Show SQL export formats and examplesph open [path] Open a project file or folder in PostHog (defaults to .)Examples:@@ -60,6 +67,7 @@ or /posthog/api. JSON results go to stdout; errors go to stderr with a nonzero eConnected tools use server/tool names from ph tools and their existing MCP permissions.The built-in commands cover notebooks and reading insights, dashboards, and feature flags.Tool schemas are files under /posthog/tools. Run ph refresh after creating or deleting objects.+Tab completes ph commands and --arguments, including connected MCP tools.`function command<T extends z.ZodType>(@@ -366,6 +374,77 @@ export class PosthogCommands {async execute(argv: string[], cwd: string): Promise<unknown> {const [name = 'help', ...rest] = argv+ if (name === '_complete') {+ const [position, prefix = '', previous, commandName] = rest+ if (position === '1' || (position === '2' && commandName === 'help')) {+ try {+ await this.loadConnected()+ } catch {+ // Keep built-in completion available when the connected tool catalog is unavailable.+ }+ return [+ ...new Set([+ 'help',+ 'tools',+ 'refresh',+ 'run',+ 'open',+ ...Object.keys(aliases),+ ...this.commands.keys(),+ ]),+ ]+ .filter((candidate) => /^[A-Za-z0-9_@/.-]+$/.test(candidate) && candidate.startsWith(prefix))+ .sort()+ .join('\n')+ }+ if (prefix.startsWith('--') && previous !== '--json') {+ const flags = ['help', 'tools', 'refresh', 'open'].includes(commandName)+ ? []+ : commandName === 'run'+ ? ['--help', '--markdown', '--json', '--csv', '--tsv']+ : [+ '--help',+ '--json',+ ...Object.keys(object((await this.find(commandName)).inputSchema.properties)).map(+ (key) => `--${key}`+ ),+ ]+ return flags+ .filter((candidate) => /^[A-Za-z0-9_@/.-]+$/.test(candidate) && candidate.startsWith(prefix))+ .sort()+ .join('\n')+ }+ return ''+ }+ if (name === 'run') {+ if (rest.length === 1 && ['--help', '-h'].includes(rest[0])) {+ return RUN_HELP+ }+ if (rest.length < 2 || rest.length > 3 || !rest[0].endsWith('.sql')) {+ throw new Error('Usage: run <file.sql>. Run run --help for examples.')+ }+ const format = rest[2] ?? '--markdown'+ if (!['--markdown', '--json', '--csv', '--tsv'].includes(format)) {+ throw new Error('Unknown output format. Run run --help for formats.')+ }+ if (teamLogic.values.currentTeamId !== Number(this.projectId) || this.signal.aborted) {+ throw new Error('The current project changed. Restart the terminal before running SQL.')+ }+ const query = await this.filesystem.queryFor(rest[0], rest[1])+ if (teamLogic.values.currentTeamId !== Number(this.projectId) || this.signal.aborted) {+ throw new Error('The current project changed. Restart the terminal before running SQL.')+ }+ const result = await performQuery(query, { signal: this.signal }, 'force_blocking')+ if (format === '--json') {+ return {+ columns: result.columns,+ types: result.types,+ results: result.results,+ hasMore: result.hasMore,+ }+ }+ return terminalQueryTable(result, format === '--csv' ? 'csv' : format === '--tsv' ? 'tsv' : 'markdown')+ }if (name === 'terminal-remove') {if (rest.length !== 2 || rest[0] !== '--json') {throw new Error('Use rm to delete PostHog files.')@@ -393,6 +472,9 @@ export class PosthogCommands {if (!rest.length) {return help}+ if (rest[0] === 'run') {+ return RUN_HELP+ }const tool = await this.find(rest[0])const { invoke: _, ...description } = toolreturn descriptiondiff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.tsindex 4885757c6cf6..45bb4d6ada0c 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'+import { waitFor } from '@testing-library/react'import apiMutator from 'lib/api-orval-mutator'@@ -7,6 +9,7 @@ import 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 { insightsList } from 'products/product_analytics/frontend/generated/api'import { NinePReader, NinePWriter } from './ninepCodec'import { NinePServer } from './ninepServer'@@ -29,6 +32,11 @@ jest.mock('products/notebooks/frontend/generated/api', () => ({notebooksPartialUpdate: jest.fn(),}))+jest.mock('products/product_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/product_analytics/frontend/generated/api'),+ insightsList: jest.fn(),+}))+describe('PostHog filesystem projection', () => {const decoder = new TextDecoder()const entry = (id: string, path: string, type = 'notebook'): FileSystemApi => ({@@ -60,6 +68,7 @@ describe('PostHog filesystem projection', () => {beforeEach(() => {jest.clearAllMocks()+ jest.mocked(insightsList).mockResolvedValue({ count: 0, results: [] })jest.mocked(fileSystemList).mockResolvedValue({count: 1,next: null,@@ -73,6 +82,98 @@ describe('PostHog filesystem projection', () => {jest.mocked(notebooksRetrieve).mockResolvedValue(notebook)})+ it('edits SQL while preserving insight options and exposes editable JSON metadata', async () => {+ const signal = new AbortController().signal+ jest.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,+ },+ ],+ })+ const original = {+ name: 'Report',+ query: { kind: 'DataTableNode', source: { kind: 'HogQLQuery', query: 'select 1', limit: 10 }, full: true },+ }+ jest.mocked(apiMutator).mockResolvedValue(original)+ const fs = new PosthogFilesystem('42', signal)+ await fs.load()+ expect(apiMutator).not.toHaveBeenCalled()+ const sql =+ await fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Report.sql')!.open!()+ expect(decoder.decode(sql.bytes)).toBe('select 1')+ await sql.save!(new TextEncoder().encode('select 2'))+ expect(apiMutator).toHaveBeenLastCalledWith(+ '/api/projects/42/insights/sql1/',+ expect.objectContaining({+ method: 'PATCH',+ body: JSON.stringify({+ query: { ...original.query, source: { ...original.query.source, query: 'select 2' } },+ }),+ })+ )+ expect(await fs.queryFor('/posthog/files/Research/Report.sql', 'select 3')).toMatchObject({+ query: 'select 3',+ limit: 10,+ })+ const json = fs.root.children!.get('api')!.children!.get('insight')!.children!.get('sql1.json')!+ expect(json.writable).toBe(true)+ const opened = await json.open!()+ await opened.save!(new TextEncoder().encode(JSON.stringify({ ...original, name: 'Renamed' })))+ expect(apiMutator).toHaveBeenLastCalledWith(+ '/api/projects/42/insights/sql1/',+ expect.objectContaining({ method: 'PATCH', body: JSON.stringify({ name: 'Renamed' }) })+ )+ })++ it('resolves unvisited object folders without loading the project tree', async () => {+ const fs = new PosthogFilesystem('42', new AbortController().signal)+ expect(await fs.folderFor({ type: 'notebook', ref: 'note1' })).toBe('/posthog/files/Research')+ expect(fileSystemList).toHaveBeenCalledWith(+ '42',+ { type: 'notebook', ref: 'note1', limit: 1 },+ expect.anything()+ )+ jest.mocked(fileSystemList).mockClear()+ expect(await fs.folderFor({ type: 'folder', ref: "Research/A's notes" })).toBe(+ "/posthog/files/Research/A's notes"+ )+ expect(fileSystemList).not.toHaveBeenCalled()+ })+it('loads only browsed folders, shares pending requests, and refreshes visited directories', async () => {let entries = [entry('research', 'Research', 'folder'),diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex 84b57430d27c..e771cd20b5ec 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -11,6 +11,8 @@ import {import type { FileSystemApi, FileSystemListParams } from '~/generated/core/api.schemas'import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'import { fileSystemTypes } from '~/products'+import type { HogQLQuery } from '~/queries/schema/schema-general'+import type { ProjectTreeRef } from '~/types'import { actionsPartialUpdate, actionsRetrieve } from 'products/actions/frontend/generated/api'import { cohortsPartialUpdate, cohortsRetrieve } from 'products/cohorts/frontend/generated/api'@@ -19,7 +21,11 @@ import { experimentsPartialUpdate, experimentsRetrieve } from 'products/experimeimport { 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 { insightsPartialUpdate, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'+import {+ insightsList,+ insightsPartialUpdate,+ insightsRetrieve,+} from 'products/product_analytics/frontend/generated/api'import { surveysPartialUpdate, surveysRetrieve } from 'products/surveys/frontend/generated/api'import { ConfirmTerminalOperation, TerminalConfirmation } from './terminalConfirmation'@@ -30,6 +36,7 @@ import {TerminalFilesystem,TerminalNode,} from './terminalFilesystem'+import { hasTerminalSql, parseTerminalSql, terminalQuery, terminalSql } from './terminalSql'const encoder = new TextEncoder()const decoder = new TextDecoder('utf-8', { fatal: true })@@ -88,7 +95,7 @@ export const TERMINAL_README = `PostHog terminalThis is a Linux virtual machine running in your browser.-/posthog/files Your project tree. Markdown notebooks have a .md extension.+/posthog/files Your project tree. Markdown notebooks use .md; SQL insights use .sql./posthog/api JSON representations, grouped by object type and ID./posthog/tools Command descriptions and argument schemas. Run ph tools to discover MCP tools./posthog/recovery Edits that could not be saved. Copy them before leaving this page.@@ -114,6 +121,10 @@ 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.+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.+The terminal follows the current resource's folder while its prompt is empty. Active commands and typed input stay intact.+Saving an existing .md notebook updates PostHog using your current permissions.JSON files for notebooks, dashboards, insights, feature flags, cohorts, actions,surveys, and experiments are editable in both mounts when you have edit access.@@ -124,7 +135,7 @@ Writes commit on fsync or close. Notebook saves use version checks; other objectuse their API's update behavior. Invalid JSON and API failures fail the save.Check the browser's save error banner and /posthog/recovery for failed edits.Use mkdir to create project folders and mv to move or rename files and folders-inside /posthog/files. Keep .md or .json extensions when renaming files.+inside /posthog/files. Keep .md, .sql, or .json extensions when renaming files.Moves preserve object IDs and folder contents. Existing destinations cannot bereplaced. Folders inferred from file paths cannot be moved; move their files instead.Use rm to remove files, rmdir for empty folders, and rm -r for folder trees.@@ -144,6 +155,7 @@ loads 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 notebookindex loads when you first browse notebooks, without fetching their bodies.+SQL insight detection loads a metadata index when you first browse insights.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@@ -170,6 +182,7 @@ Project file sizes stay zero until opened; ncdu does not download their contentsBundled tool licenses and source links are in /opt/posthog-tools/licenses.ph runs project commands and tools from connected MCP servers with your permissions.Run ph help <command> for its arguments. Notebook commands accept IDs or file paths.+The interactive Bash shell completes ph commands and their --arguments with Tab.Use --json @file.json or --json - for arguments from a file or stdin.Commands such as ph notebook-delete change real data. Errors exit nonzero.Selecting text copies it automatically. You can also copy with Cmd+C (macOS) or@@ -194,6 +207,40 @@ export class PosthogFilesystem extends TerminalFilesystem {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) {+ return null+ }+ if (ref.type === 'folder') {+ return this.folderPath(ref.ref ?? '')+ }+ if (!ref.ref) {+ return null+ }+ // The filesystem endpoint accepts type/ref filters that its generated schema omits.+ const params = { type: ref.type, ref: ref.ref, limit: 1 }+ const page = await fileSystemList(this.projectId, params, { signal: this.signal })+ const entry = page.results.find(+ (entry) => entry.type === ref.type && entry.ref === ref.ref && entry.user_access_level !== 'none'+ )+ return entry ? this.folderPath(joinPath(splitPath(entry.path).slice(0, -1))) : null+ }++ folderPath(path: string): string {+ return ['/posthog/files', ...splitPath(path).map(terminalFilename)].join('/')+ }++ async queryFor(path: string, text: string): Promise<HogQLQuery> {+ await this.loadReference(path, '/posthog/files')+ const entry = this.references.get(path)+ const original =+ entry?.type === 'insight'+ ? await insightsRetrieve(this.projectId, entry.ref!, undefined, { signal: this.signal })+ : undefined+ return terminalQuery(text, original as Record<string, unknown> | undefined)+ }async navigationUrl(value: string, cwd: string): Promise<string> {const parts = (value.startsWith('/') ? value : `${cwd}/${value}`).split('/').filter(Boolean)@@ -233,7 +280,7 @@ export class PosthogFilesystem extends TerminalFilesystem {}async loadReference(value: string, cwd: string): Promise<void> {- if (!value.includes('/') && !/\.(md|json)$/.test(value)) {+ if (!value.includes('/') && !/\.(md|json|sql)$/.test(value)) {return}const parts = (value.startsWith('/') ? value : `${cwd}/${value}`).split('/').filter(Boolean)@@ -273,7 +320,7 @@ export class PosthogFilesystem extends TerminalFilesystem {}return entry.ref}- if (value.includes('/') || /\.(md|json)$/.test(value)) {+ if (value.includes('/') || /\.(md|json|sql)$/.test(value)) {throw new Error(`No project file at ${value}. Run ph refresh if the file was just created.`)}return value@@ -602,23 +649,37 @@ export class PosthogFilesystem extends TerminalFilesystem {}}- private async json(entry: FileSystemApi, writable: boolean, signal?: AbortSignal): Promise<TerminalFile> {+ private async document(+ entry: FileSystemApi,+ writable: boolean,+ signal?: AbortSignal,+ sql = false+ ): Promise<TerminalFile> {const endpoint = this.objectApi(entry, signal)let value = endpoint? await endpoint.read(): await fileSystemRetrieve(this.projectId, entry.id, {signal: signal ?? this.signal,})+ if (sql && !hasTerminalSql(value)) {+ throw new Error('This insight no longer contains SQL. Run ph refresh to reload its filename.')+ }return {- ...jsonFile(value),+ ...(sql ? { bytes: bytes(terminalSql(value as Record<string, unknown>)) } : jsonFile(value)),save:writable && endpoint? async (data) => {let update: unknowntry {- update = JSON.parse(decoder.decode(data))+ update = sql+ ? parseTerminalSql(decoder.decode(data), value as Record<string, unknown>)+ : JSON.parse(decoder.decode(data))} catch {- throw new Error('Invalid JSON. Fix the JSON syntax before saving.')+ throw new Error(+ sql+ ? 'Invalid SQL text. Save the file as UTF-8 before trying again.'+ : 'Invalid JSON. Fix the JSON syntax before saving.'+ )}if (!update || typeof update !== 'object' || Array.isArray(update)) {throw new Error('The JSON must contain an object with the fields to update.')@@ -759,6 +820,33 @@ export class PosthogFilesystem extends TerminalFilesystem {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 } {@@ -796,6 +884,9 @@ 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>())@@ -841,7 +932,11 @@ export class PosthogFilesystem extends TerminalFilesystem {merged.set(entry.id, entry)}this.markdownNotebooks = undefined+ this.sqlInsights = undefinedconst 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>()@@ -886,7 +981,7 @@ export class PosthogFilesystem extends TerminalFilesystem {this.mountApiDirectories(directories)} else {for (const entry of entries) {- const extension = entry.type === 'notebook' && markdownNotebooks.has(entry.ref ?? '') ? '.md' : '.json'+ const extension = this.extension(entry, markdownNotebooks)const existing = files.get(this.fileIdentity(entry, extension))if (existing) {existing.parent!.children!.delete(existing.name)@@ -907,7 +1002,7 @@ export class PosthogFilesystem extends TerminalFilesystem {const parts = splitPath(entry.path)const basename = terminalFilename(parts.pop() ?? 'Untitled')const parent = this.parent(parts, this.files, directories)- const extension = notebook ? '.md' : '.json'+ const extension = this.extension(entry, markdownNotebooks)let name = basename.endsWith(extension) ? basename : `${basename}${extension}`if (parent.children!.has(name)) {name = `${basename}~${entry.id}${extension}`@@ -924,7 +1019,9 @@ export class PosthogFilesystem extends TerminalFilesystem {const file = this.mountFile(name,parent,- notebook ? (signal) => this.notebook(entry, signal) : (signal) => this.json(entry, writable, signal),+ notebook+ ? (signal) => this.notebook(entry, signal)+ : (signal) => this.document(entry, writable, signal, extension === '.sql'),writable,files.get(this.fileIdentity(entry, extension)))@@ -943,7 +1040,7 @@ export class PosthogFilesystem extends TerminalFilesystem {const apiFile = this.mountFile(apiName,type,- (signal) => this.json(entry, writable, signal),+ (signal) => this.document(entry, writable, signal),writable,apiFiles.get(apiPath) ?? type.children!.get(apiName))@@ -966,6 +1063,14 @@ 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 ?? '')+ ? '.md'+ : entry.type === 'insight' && this.sqlInsights?.has(entry.ref ?? '')+ ? '.sql'+ : '.json'+ }+private mountedNodes(): Set<TerminalNode> {const nodes = new Set<TerminalNode>([this.files, this.api])for (const node of nodes) {diff --git a/frontend/src/scenes/terminal/terminalCommands.ts b/frontend/src/scenes/terminal/terminalCommands.tsindex c50157f77766..8fd3d7bc0090 100644--- a/frontend/src/scenes/terminal/terminalCommands.ts+++ b/frontend/src/scenes/terminal/terminalCommands.ts@@ -25,9 +25,13 @@ temporary=$(mktemp -d)trap 'rm -rf "$temporary"' EXITtrap 'exit 130' HUP INT TERMprevious=''+command=''+if [ "$#" -gt 0 ]; then command="$1"; fifor argument in "$@"; dooriginal="$argument"- { case "$argument" in+ { if [ "$command" = '_complete' ]; then+ printf '%s' "$argument"+ else case "$argument" in@*) cat -- "$(printf '%s' "$argument" | cut -c2-)" ;;-)if [ "$previous" = '--json' ]; then@@ -37,7 +41,7 @@ for argument in "$@"; dofi;;*) printf '%s' "$argument" ;;- esac; } | base64 | tr -d '\n'+ esac; fi; } | base64 | tr -d '\n'previous="$original"printf '\n'done > "$temporary/args"@@ -55,6 +59,83 @@ elsefi`+export const SHELL_RC = `+alias ls='ls --color=auto'+if [ -n "$BASH_VERSION" ]; then+ _ph_complete() {+ mapfile -t COMPREPLY < <(ph _complete "$COMP_CWORD" "$2" "$3" "\${COMP_WORDS[1]}" 2>/dev/null)+ if [ "\${#COMPREPLY[@]}" -eq 1 ] && [ -z "\${COMPREPLY[0]}" ]; then COMPREPLY=(); fi+ }+ complete -o bashdefault -o default -F _ph_complete ph+fi+`++export const RUN_HELP = `Usage: run [format] <file[.sql]>++Run a SQL file in the current PostHog project.+If the file is missing, run also looks for <file>.sql.++Formats (choose one, before or after the filename):+ --markdown Markdown table with headers and rows (default)+ --json Full query result as JSON, including metadata+ --csv Comma-separated headers and rows+ --tsv Tab-separated headers and rows+ --help, -h Show this help++Markdown, CSV, and TSV contain only the returned table. Use --json+to check hasMore for additional rows. CSV and TSV quote fields containing+delimiters, quotes, or newlines; null values are empty fields.++Examples:+ run report.sql+ run report > results.md+ run --json report.sql > /tmp/results.json+ run report.sql --csv > /tmp/results.csv++Use /tmp for exports.+Query errors go to stderr and exit nonzero.+`++const RUN_SCRIPT = String.raw`#!/bin/sh+set -eu+usage() {+ cat <<'HELP'+${RUN_HELP}+HELP+}+format=''+file=''+while [ "$#" -gt 0 ]; do+ case "$1" in+ --help|-h) usage; exit 0 ;;+ --markdown|--json|--csv|--tsv)+ [ -z "$format" ] || { echo 'Choose one output format. Run run --help for formats.' >&2; exit 1; }+ format="$1"+ ;;+ --)+ shift+ [ "$#" -eq 1 ] && [ -z "$file" ] || { usage >&2; exit 1; }+ file="$1"+ break+ ;;+ -*) echo "Unknown option: $1. Run run --help for options." >&2; exit 1 ;;+ *) [ -z "$file" ] || { usage >&2; exit 1; }; file="$1" ;;+ esac+ shift+done+[ -n "$file" ] || { usage >&2; exit 1; }+if [ ! -e "$file" ] && [ -f "$file.sql" ]; then file="$file.sql"; fi+case "$file" in+ *.sql) ;;+ *.md) echo 'Running Markdown notebooks is not supported yet. Use run <file.sql>.' >&2; exit 1 ;;+ *) echo 'Only .sql files can be run. Use run <file.sql>.' >&2; exit 1 ;;+esac+[ -f "$file" ] || { echo "SQL file not found: $file" >&2; exit 1; }+target=$(readlink -f -- "$file")+[ -n "$format" ] || format='--markdown'+exec ph run "$target" "@$target" "$format"+`+export class TerminalCommands {constructor(filesystem: TerminalFilesystem, execute: (argv: string[], cwd: string) => Promise<unknown>) {const encoder = new TextEncoder()@@ -106,7 +187,10 @@ export class TerminalCommands {}),true)- filesystem.text('ph', filesystem.directory('bin', filesystem.root), PH_SCRIPT)- filesystem.text('open', filesystem.directory('bin', filesystem.root), OPEN_SCRIPT)+ const bin = filesystem.directory('bin', filesystem.root)+ filesystem.text('ph', bin, PH_SCRIPT)+ filesystem.text('run', bin, RUN_SCRIPT)+ filesystem.text('shellrc', bin, SHELL_RC)+ filesystem.text('open', bin, OPEN_SCRIPT)}}diff --git a/frontend/src/scenes/terminal/terminalDockLogic.ts b/frontend/src/scenes/terminal/terminalDockLogic.tsindex 5630251ede04..370e365e4da3 100644--- a/frontend/src/scenes/terminal/terminalDockLogic.ts+++ b/frontend/src/scenes/terminal/terminalDockLogic.ts@@ -13,6 +13,7 @@ export interface terminalDockLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicdockOpen: booleanhasOpened: boolean+ requestedFolder: string | nullterminalEnabled: boolean}@@ -21,9 +22,15 @@ export interface terminalDockLogicActions {focusTerminal: () => {value: true}+ openInTerminal: (folder: string) => {+ folder: string+ }setDockOpen: (open: boolean) => {open: boolean}+ setRequestedFolder: (folder: string | null) => {+ folder: string | null+ }toggleTerminal: () => {value: true}@@ -47,11 +54,14 @@ export const terminalDockLogic = kea<terminalDockLogicType>([path(['scenes', 'terminal', 'terminalDockLogic']),connect({ values: [featureFlagLogic, ['featureFlags']] }),actions({+ openInTerminal: (folder: string) => ({ folder }),+ setRequestedFolder: (folder: string | null) => ({ folder }),toggleTerminal: true,focusTerminal: true,setDockOpen: (open: boolean) => ({ open }),}),reducers({+ requestedFolder: [null as string | null, { setRequestedFolder: (_, { folder }) => folder }],dockOpen: [false, { setDockOpen: (_, { open }) => open }],hasOpened: [false, { setDockOpen: (state, { open }) => state || open }],}),@@ -62,6 +72,14 @@ export const terminalDockLogic = kea<terminalDockLogicType>([],}),listeners(({ actions, values, cache }) => ({+ openInTerminal: ({ folder }) => {+ if (!values.terminalEnabled) {+ return+ }+ actions.setRequestedFolder(folder)+ actions.setDockOpen(true)+ actions.focusTerminal()+ },toggleTerminal: () => {if (!values.terminalEnabled) {returndiff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.tsindex da0e6ff32a40..92bb46f7dc9f 100644--- a/frontend/src/scenes/terminal/terminalLogic.test.ts+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts@@ -7,6 +7,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'+import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'import { initKeaTests } from '~/test/init'import { PosthogFilesystem } from './posthogFilesystem'@@ -15,12 +16,15 @@ import { terminalDockLogic } from './terminalDockLogic'import { terminalLogic } from './terminalLogic'import { TerminalRuntime } from './terminalRuntime'+const mockFolderFor = jest.fn<Promise<string | null>, []>()+jest.mock('./terminalRuntime', () => ({TerminalRuntime: jest.fn().mockImplementation(() => ({start: jest.fn(async (_server, _signal, ready) => ready()),dispose: jest.fn(),resize: jest.fn(),syncClock: jest.fn(),+ changeDirectory: jest.fn(() => true),read: jest.fn(() => ''),write: jest.fn(),})),@@ -30,23 +34,32 @@ jest.mock('./TerminalSession', () => ({attach: jest.fn(),detach: jest.fn(),dispose: jest.fn(),- view: { clear: jest.fn(), write: jest.fn(), cols: 80, rows: 24 },+ view: { clear: jest.fn(), write: jest.fn(), cols: 80, rows: 24, focus: jest.fn() },})),}))jest.mock('./posthogFilesystem', () => ({- PosthogFilesystem: jest.fn().mockImplementation(() => ({ load: jest.fn(async () => {}) })),+ PosthogFilesystem: jest.fn().mockImplementation(() => ({+ load: jest.fn(async () => {}),+ folderFor: mockFolderFor,+ folderPath: (path: string) => '/posthog/files/' + path,+ })),}))jest.mock('./posthogCommands', () => ({ PosthogCommands: jest.fn() }))describe('terminal lifecycle', () => {beforeEach(() => {jest.clearAllMocks()+ mockFolderFor.mockReset().mockResolvedValue(null)initKeaTests()featureFlagLogic.mount()featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: true })+ breadcrumbsLogic.mount()+ jest.spyOn(breadcrumbsLogic.selectors, 'projectTreeRef').mockReturnValue(null)terminalLogic.mount()})+ afterEach(() => jest.restoreAllMocks())+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'))@@ -72,6 +85,26 @@ describe('terminal lifecycle', () => {expect(terminalLogic.values.runRequested).toBe(false)})+ it('opens the selected folder on first boot and changes it in an existing terminal', async () => {+ terminalDockLogic.actions.openInTerminal('Research')+ terminalLogic.actions.attach(document.createElement('div'))+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))+ const runtime = jest.mocked(TerminalRuntime).mock.results[0].value+ expect(runtime.start).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.any(Function),+ '/posthog/files/Research'+ )+ terminalDockLogic.actions.openInTerminal('Research/Reports')+ await waitFor(() => expect(runtime.changeDirectory).toHaveBeenCalledWith('/posthog/files/Research/Reports'))+ expect(TerminalRuntime).toHaveBeenCalledTimes(1)+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })+ terminalDockLogic.actions.openInTerminal('Hidden')+ expect(terminalDockLogic.values.dockOpen).toBe(false)+ expect(terminalDockLogic.values.requestedFolder).toBe(null)+ })+it('retries a requested start when the project arrives', async () => {teamLogic.actions.loadCurrentTeamSuccess(null)terminalLogic.actions.attach(document.createElement('div'))@@ -81,6 +114,50 @@ describe('terminal lifecycle', () => {expect(TerminalRuntime).toHaveBeenCalledTimes(1)})+ it.each([+ ['lookup', 'request'],+ ['lookup', 'navigation'],+ ['boot', 'request'],+ ['boot', 'navigation'],+ ])('keeps a newer folder from %s during %s', async (phase, source) => {+ let resolveFolder!: (folder: string) => void+ mockFolderFor.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFolder = resolve+ })+ )+ const projectTreeRef = jest.spyOn(breadcrumbsLogic.selectors, 'projectTreeRef')+ projectTreeRef.mockReturnValue({ type: 'folder', ref: 'Original' })+ terminalDockLogic.actions.setDockOpen(true)+ terminalLogic.actions.attach(document.createElement('div'))+ const runtime = jest.mocked(TerminalRuntime).mock.results[0].value+ let ready!: () => void+ runtime.start.mockImplementationOnce(async (_server: unknown, _signal: AbortSignal, onReady: () => void) => {+ ready = onReady+ if (phase === 'lookup') {+ ready()+ }+ })+ if (phase === 'boot') {+ resolveFolder('/posthog/files/Original')+ await waitFor(() => expect(runtime.start).toHaveBeenCalled())+ }+ if (source === 'request') {+ terminalDockLogic.actions.openInTerminal('Latest')+ } else {+ projectTreeRef.mockReturnValue({ type: 'folder', ref: 'Latest' })+ mockFolderFor.mockResolvedValue('/posthog/files/Latest')+ }+ if (phase === 'lookup') {+ resolveFolder('/posthog/files/Original')+ } else {+ ready()+ }+ await waitFor(() => expect(runtime.changeDirectory).toHaveBeenCalledWith('/posthog/files/Latest'))+ expect(terminalDockLogic.values.requestedFolder).toBeNull()+ })+it('restores the command menu opener after the dialog element disappears', () => {commandLogic.mount()const opener = document.createElement('button')diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.tsindex 96e56d2cd452..54d18d212882 100644--- a/frontend/src/scenes/terminal/terminalLogic.ts+++ b/frontend/src/scenes/terminal/terminalLogic.ts@@ -1,10 +1,15 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, connect, isBreakpoint, kea, listeners, path, reducers } from 'kea'import { router } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { teamLogic } from 'scenes/teamLogic'+import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'+import type { ProjectTreeRef } from '~/types'+import { NinePServer } from './ninepServer'import { PosthogCommands } from './posthogCommands'import { PosthogFilesystem } from './posthogFilesystem'@@ -28,7 +33,10 @@ export type TerminalStatus = 'idle' | 'loading' | 'booting' | 'ready' | 'error'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface terminalLogicValues {+ projectTreeRef: ProjectTreeRef | null // breadcrumbsLogiccurrentTeamId: number | null // teamLogic+ dockOpen: boolean // terminalDockLogic+ requestedFolder: string | null // terminalDockLogicterminalEnabled: boolean // terminalDockLogicclipboardError: string | nullconfirmation: TerminalConfirmation | null@@ -46,6 +54,9 @@ export interface terminalLogicActions {focusTerminal: () => {value: true} // terminalDockLogic+ setRequestedFolder: (folder: string | null) => {+ folder: string | null+ } // terminalDockLogicanswerConfirmation: (confirmation: TerminalConfirmation,approved: boolean@@ -65,6 +76,9 @@ export interface terminalLogicActions {focus: () => {value: true}+ followFolder: () => {+ value: true+ }insertCommand: (command: string) => {command: string}@@ -105,13 +119,21 @@ export type terminalLogicType = MakeLogicType<terminalLogicValues, terminalLogicexport const terminalLogic = kea<terminalLogicType>([path(['scenes', 'terminal', 'terminalLogic']),connect({- values: [teamLogic, ['currentTeamId'], terminalDockLogic, ['terminalEnabled']],- actions: [terminalDockLogic, ['focusTerminal']],+ values: [+ breadcrumbsLogic,+ ['projectTreeRef'],+ teamLogic,+ ['currentTeamId'],+ terminalDockLogic,+ ['terminalEnabled', 'dockOpen', 'requestedFolder'],+ ],+ actions: [terminalDockLogic, ['focusTerminal', 'setRequestedFolder']],}),actions({setConfirmation: (confirmation: TerminalConfirmation | null) => ({ confirmation }),answerConfirmation: (confirmation: TerminalConfirmation, approved: boolean) => ({ confirmation, approved }),start: true,+ followFolder: true,attach: (container: HTMLElement) => ({ container }),detach: (container: HTMLElement) => ({ container }),focus: true,@@ -145,6 +167,40 @@ export const terminalLogic = kea<terminalLogicType>([],}),listeners(({ actions, values, cache }) => ({+ followFolder: async (_, breakpoint) => {+ const runtime: TerminalRuntime | undefined = cache.runtime+ const filesystem: PosthogFilesystem | undefined = cache.filesystem+ if (!values.terminalEnabled || values.status !== 'ready' || !runtime || !filesystem) {+ return+ }+ const requested = values.requestedFolder+ try {+ const folder =+ requested !== null+ ? filesystem.folderPath(requested)+ : await filesystem.folderFor(values.projectTreeRef)+ breakpoint()+ if (folder && cache.runtime === runtime) {+ if (!runtime.changeDirectory(folder) && requested !== null) {+ lemonToast.info('The terminal is busy. Finish the command or clear the prompt, then try again.')+ }+ }+ } catch (error) {+ if (error instanceof Error && isBreakpoint(error)) {+ throw error+ }+ lemonToast.error('Could not find the terminal folder. Navigate to another resource and try again.')+ } finally {+ if (values.requestedFolder === requested) {+ actions.setRequestedFolder(null)+ }+ }+ },+ [terminalDockLogic.actionTypes.setDockOpen]: ({ open }) => {+ if (open) {+ actions.followFolder()+ }+ },answerConfirmation: ({ confirmation, approved }) => {if (values.confirmation === confirmation) {cache.answerConfirmation?.(approved)@@ -305,17 +361,42 @@ export const terminalLogic = kea<terminalLogicType>([actions.setSaveError(error)}})- await runtime.start(server, controller.signal, () => {- if (!controller.signal.aborted) {- window.posthogTerminal = agent- actions.setStatus('ready')- disposables.add(() => {- runtime.syncClock()- const interval = setInterval(() => runtime.syncClock(), 30_000)- return () => clearInterval(interval)- }, 'clock-sync')- }- })+ const requested = values.requestedFolder+ const projectTreeRef = values.projectTreeRef+ const folder =+ requested !== null+ ? filesystem.folderPath(requested)+ : await filesystem.folderFor(projectTreeRef).catch(() => null)+ if (controller.signal.aborted) {+ return+ }+ if (values.requestedFolder === requested) {+ actions.setRequestedFolder(null)+ }+ await runtime.start(+ server,+ controller.signal,+ () => {+ if (!controller.signal.aborted) {+ window.posthogTerminal = agent+ actions.setStatus('ready')+ if (+ values.requestedFolder !== null ||+ (values.dockOpen &&+ (values.projectTreeRef?.type !== projectTreeRef?.type ||+ values.projectTreeRef?.ref !== projectTreeRef?.ref))+ ) {+ actions.followFolder()+ }+ disposables.add(() => {+ runtime.syncClock()+ const interval = setInterval(() => runtime.syncClock(), 30_000)+ return () => clearInterval(interval)+ }, 'clock-sync')+ }+ },+ folder ?? undefined+ )if (controller.signal.aborted) {return}@@ -348,4 +429,12 @@ export const terminalLogic = kea<terminalLogicType>([cache.disposables.dispose('boot-timeout')},})),+ subscriptions(({ actions, values }) => ({+ // Each scene derives this reference from its own state, so no single navigation action covers it.+ projectTreeRef: () => {+ if (values.dockOpen) {+ actions.followFolder()+ }+ },+ })),])diff --git a/frontend/src/scenes/terminal/terminalRuntime.test.ts b/frontend/src/scenes/terminal/terminalRuntime.test.tsindex ab2cea238582..9ee18ce6b990 100644--- a/frontend/src/scenes/terminal/terminalRuntime.test.ts+++ b/frontend/src/scenes/terminal/terminalRuntime.test.ts@@ -56,6 +56,46 @@ describe('terminal VM lifecycle', () => {}})+ it('changes folders only at an empty prompt and quotes folder names', async () => {+ const listeners = new Map<string, (value?: number) => void>()+ const emulator = {+ add_listener: jest.fn((event, callback) => listeners.set(event, callback)),+ serial0_send: jest.fn(),+ serial_send_bytes: jest.fn(),+ }+ jest.mocked(V86).mockImplementation(() => emulator as unknown as V86)+ const runtime = new TerminalRuntime(jest.fn())+ await runtime.start(+ new NinePServer(new TerminalFilesystem(), jest.fn()),+ new AbortController().signal,+ jest.fn()+ )+ const output = (text: string): void => {+ for (const byte of new TextEncoder().encode(text)) {+ listeners.get('serial0-output-byte')!(byte)+ }+ }+ output('~% ')+ listeners.get('serial1-output-byte')!(30)+ expect(runtime.changeDirectory('/posthog/files/Research')).toBe(true)+ output('\x1b]133;B\x07')+ expect(new TextDecoder().decode(emulator.serial_send_bytes.mock.calls.at(-1)![1])).toBe(+ "cd -- '/posthog/files/Research'\n"+ )+ output('\x1b]133;B\x07')+ expect(runtime.changeDirectory("/posthog/files/A's notes")).toBe(true)+ expect(new TextDecoder().decode(emulator.serial_send_bytes.mock.calls.at(-1)![1])).toBe(+ "cd -- '/posthog/files/A'\\''s notes'\n"+ )+ expect(runtime.changeDirectory('/posthog/files/Other')).toBe(false)+ output('\x1b]133;B\x07')+ runtime.write('nano ')+ expect(runtime.changeDirectory('/posthog/files/Other')).toBe(false)+ runtime.write('report.sql\n')+ output('Editor output')+ expect(runtime.changeDirectory('/posthog/files/Other')).toBe(false)+ })+it.each(['initializing', 'loaded'])('stops a VM that is %s without allowing late output or startup',async (phase) => {diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.tsindex c9745b93c748..c712a78d84e9 100644--- a/frontend/src/scenes/terminal/terminalRuntime.ts+++ b/frontend/src/scenes/terminal/terminalRuntime.ts@@ -54,10 +54,19 @@ export class TerminalRuntime {private disposed = falseprivate columns = 80private rows = 24+ private promptTail = ''+ private atPrompt = false+ private hasPrompt = false+ private pendingDirectory?: stringconstructor(private onOutput: (bytes: Uint8Array) => void) {}- async start(server: NinePServer, signal: AbortSignal, onReady: () => void): Promise<void> {+ async start(+ server: NinePServer,+ signal: AbortSignal,+ onReady: () => void,+ folder = '/posthog/files'+ ): Promise<void> {const { V86 } = await import('v86')if (signal.aborted || this.disposed) {return@@ -127,6 +136,17 @@ export class TerminalRuntime {if (this.disposed) {return}+ this.atPrompt = false+ this.promptTail = (this.promptTail + String.fromCharCode(byte)).slice(-8)+ if (this.promptTail.endsWith('\x1b]133;B\x07')) {+ this.hasPrompt = true+ this.atPrompt = true+ if (this.pendingDirectory) {+ const folder = this.pendingDirectory+ this.pendingDirectory = undefined+ this.changeDirectory(folder)+ }+ }this.outputBuffer[this.outputLength++] = byteif (this.outputLength === this.outputBuffer.length) {this.flushOutput()@@ -158,6 +178,8 @@ 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/run /usr/bin/run && chmod +x /usr/bin/run || exit',+ '[ -e /dev/fd ] || ln -s /proc/self/fd /dev/fd','mkdir -p /usr/local/bin && cp /posthog/bin/rm /usr/local/bin/rm && chmod +x /usr/local/bin/rm || exit','export PATH=/usr/local/bin:$PATH','cp /posthog/bin/open /usr/bin/open && chmod +x /usr/bin/open || exit',@@ -171,12 +193,13 @@ export class TerminalRuntime {// Detach the control helper so the shell's wait command only waits for user jobs.'(while read -r command first second; do case "$command" in resize) stty -F /dev/ttyS0 rows "$first" cols "$second";; clock) date -s "@$first" > /dev/null; printf "%s\\n" "$second" > /etc/TZ;; esac; done < /dev/ttyS1 &)',"alias ls='ls --color=auto'",- "export PS1='\\[\\033[32m\\]posthog\\[\\033[0m\\]:\\[\\033[34m\\]\\w\\[\\033[0m\\] $ '",- 'cd /posthog/files',+ "export PS1='\\[\\033[32m\\]posthog\\[\\033[0m\\]:\\[\\033[34m\\]\\w\\[\\033[0m\\] $ \\[\\e]133;B\\a\\]'",+ `cd -- '${folder.replaceAll("'", "'\\''")}' || cd /posthog/files`,'clear',"printf 'PostHog terminal\\n\\nTry:\\n mc\\n tree -C -L 3\\n nano Unfiled/Notebooks/Foobar.md\\n vi Unfiled/Notebooks/Foobar.md\\n ncdu -r /posthog/files\\n mkdir Research\\n ph tools\\n ph notebooks-list --limit 10 | jq .\\n cat /posthog/README.txt\\n\\nUse your own notebook path. In nano, Ctrl+S saves and Ctrl+X exits.\\nIn vi, save with :wq; quit with :q!. Selecting text copies it.\\nFolder creation and moves update PostHog.\\n\\n'",'stty echo',"printf '\\036' > /dev/ttyS1",+ 'exec /usr/bin/bash --rcfile /posthog/bin/shellrc -i',].join('\n') + '\n')server.filesystem.file('init.sh', bin, async () => ({ bytes: setup })).size = setup.byteLength@@ -191,10 +214,24 @@ export class TerminalRuntime {write(data: string): void {if (this.ready) {+ this.atPrompt = false+ this.promptTail = ''this.emulator?.serial_send_bytes(0, new TextEncoder().encode(data))}}+ changeDirectory(folder: string): boolean {+ if (!this.disposed && !this.hasPrompt) {+ this.pendingDirectory = folder+ return true+ }+ if (!this.ready || this.disposed || !this.atPrompt) {+ return false+ }+ this.write(`cd -- '${folder.replaceAll("'", "'\\''")}'\n`)+ return true+ }+read(): string {this.flushOutput()return this.output.slice(-1_000_000)diff --git a/frontend/src/scenes/terminal/terminalSql.ts b/frontend/src/scenes/terminal/terminalSql.tsnew file mode 100644index 000000000000..fa9fad5cd7bc--- /dev/null+++ b/frontend/src/scenes/terminal/terminalSql.ts@@ -0,0 +1,115 @@+import Papa from 'papaparse'++import { HogQLQuery, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'++function queryCell(value: unknown): string {+ const text = typeof value === 'string' ? value : (JSON.stringify(value) ?? 'null')+ return text.replace(+ /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`+ )+}++export function terminalQueryTable(+ result: Pick<HogQLQueryResponse<unknown[][]>, 'columns' | 'results'>,+ format: 'markdown' | 'csv' | 'tsv'+): string {+ const columns = result.columns ?? result.results[0]?.map((_, index) => `Column ${index + 1}`) ?? []+ const rows: unknown[][] = [columns, ...result.results]+ if (format !== 'markdown') {+ return Papa.unparse(+ rows.map((row) =>+ row.map((value) =>+ value === null || value === undefined ? '' : typeof value === 'number' ? value : queryCell(value)+ )+ ),+ { delimiter: format === 'csv' ? ',' : '\t', newline: '\n', escapeFormulae: true }+ )+ }+ if (!columns.length) {+ return ''+ }+ const lines = rows.map(+ (row) =>+ `| ${row+ .map((value) =>+ queryCell(value)+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replace(/[\\|`*_[\]~]/g, '\\$&')+ .replace(/\r\n|\r|\n/g, '<br>')+ )+ .join(' | ')} |`+ )+ lines.splice(1, 0, `| ${columns.map(() => '---').join(' | ')} |`)+ return lines.join('\n')+}++function sqlPaths(value: Record<string, unknown>): string[][] {+ const paths: string[][] = []+ let node = value.query+ const path = ['query']+ while (node && typeof node === 'object' && !Array.isArray(node)) {+ const query = node as Record<string, unknown>+ if (query.kind === 'HogQLQuery' && typeof query.query === 'string') {+ paths.push([...path, 'query'])+ break+ }+ node = query.source+ path.push('source')+ }+ const filters = value.filters as Record<string, unknown> | undefined+ if (filters && typeof filters.hogql === 'string') {+ paths.push(['filters', 'hogql'])+ }+ return paths+}++export function hasTerminalSql(value: unknown): boolean {+ return !!value && typeof value === 'object' && sqlPaths(value as Record<string, unknown>).length > 0+}++export function terminalSql(value: Record<string, unknown>): string {+ const path = sqlPaths(value)[0]+ if (!path) {+ return ''+ }+ let parent = value+ for (const key of path.slice(0, -1)) {+ parent = parent[key] as Record<string, unknown>+ }+ return parent[path[path.length - 1]] as string+}++export function parseTerminalSql(text: string, original: Record<string, unknown>): Record<string, unknown> {+ const metadata: Record<string, unknown> = {}+ for (const path of sqlPaths(original)) {+ metadata[path[0]] ??= structuredClone(original[path[0]])+ let parent = metadata+ for (const key of path.slice(0, -1)) {+ parent = parent[key] as Record<string, unknown>+ }+ parent[path[path.length - 1]] = text+ }+ return metadata+}++export function terminalQuery(text: string, original?: Record<string, unknown>): HogQLQuery {+ let options: Record<string, unknown> = {}+ if (original) {+ let node = original.query+ while (node && typeof node === 'object' && !Array.isArray(node)) {+ const source = node as Record<string, unknown>+ if (source.kind === NodeKind.HogQLQuery) {+ options = source+ break+ }+ node = source.source+ }+ }+ if (!text.trim()) {+ throw new Error('The SQL file is empty. Add a query before running it.')+ }+ return { ...options, kind: NodeKind.HogQLQuery, query: text, tags: { productKey: 'sql_editor', scene: 'Terminal' } }+}diff --git a/frontend/src/scenes/userLogic.test.ts b/frontend/src/scenes/userLogic.test.tsindex cd3d269a4929..baa603c289c5 100644--- a/frontend/src/scenes/userLogic.test.ts+++ b/frontend/src/scenes/userLogic.test.ts@@ -20,12 +20,12 @@ describe('userLogic', () => {...window.POSTHOG_APP_CONTEXT,current_user: userWithLightTheme,} as any- initKeaTests()useMocks({get: {'/api/users/@me/': () => [200, userWithLightTheme],},})+ initKeaTests()userLogic.mount()})@@ -103,9 +103,11 @@ describe('userLogic', () => {beforeEach(() => {updateUserSpy = jest.spyOn(userLogic.actions, 'updateUser')+ useMocks({ patch: { '/api/users/@me/': [200, userWithLightTheme] } })})- afterEach(() => {+ afterEach(async () => {+ await expectLogic(userLogic).toFinishAllListeners()updateUserSpy.mockRestore()})