: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): install node and pi on first use (#105235)
Marius Andra432588575510
diff --git a/docs/published/handbook/engineering/project-structure.md b/docs/published/handbook/engineering/project-structure.mdindex 8350a76840a2..4c40e8af177a 100644--- a/docs/published/handbook/engineering/project-structure.md+++ b/docs/published/handbook/engineering/project-structure.md@@ -70,6 +70,14 @@ Browsing `/posthog/files` loads and caches each folder's immediate children; `/pLoading another folder leaves cached folders untouched, and API type directories can be opened directly even if they are not listed yet.Notebook format detection waits until notebooks are browsed, and object contents load only when opened.`ph refresh` reloads the directories already visited, rebuilds the cached tree once, and reloads the connected tool catalog.+Running `node`, `nodejs`, or `pi` installs the tool on first use; `pi` also installs Node.js.+Optional tools come from commit-pinned archives in [PostHog/terminal-assets](https://github.com/PostHog/terminal-assets), separate from the boot assets.+The browser verifies each archive's SHA-256 and size before making it available to the VM, and caches verified downloads when browser storage is available.+Failed installations can be retried by running the command again.+The VM uses 512 MiB of memory and a separate 256 MiB temporary filesystem for installed tools.+Stopping the terminal discards the installed tools and local files; verified downloads can be reused from the browser cache.+The VM has no network bridge, so pi can run locally but cannot call models, log in, or download packages.+Add future tools to `terminal-packages.json` with pinned archive metadata, dependencies, and command entrypoints, and publish their reproducible build recipes in the assets repository.### `posthog`diff --git a/frontend/src/scenes/terminal/TerminalScene.stories.tsx b/frontend/src/scenes/terminal/TerminalScene.stories.tsxindex 73efae2e1ed7..ad2c2239f6a4 100644--- a/frontend/src/scenes/terminal/TerminalScene.stories.tsx+++ b/frontend/src/scenes/terminal/TerminalScene.stories.tsx@@ -48,7 +48,10 @@ const meta: Meta<typeof TerminalScene> = {title: 'Scenes-App/Terminal',component: TerminalScene,parameters: { layout: 'padded', featureFlags: [FEATURE_FLAGS.POSTHOG_TERMINAL] },- beforeEach: () => {+ beforeEach: ({ parameters }) => {+ if (parameters.liveRuntime) {+ return+ }// Visual snapshots must not depend on firmware downloads or Linux boot timing.const start = spyOn(TerminalRuntime.prototype, 'start').mockImplementation(async (_server, _signal, onReady) => {@@ -292,6 +295,11 @@ const meta: Meta<typeof TerminalScene> = {export default metaexport const Default: StoryObj<typeof TerminalScene> = {}++export const LiveRuntime: StoryObj<typeof TerminalScene> = {+ tags: ['!test'],+ parameters: { liveRuntime: true },+}export const Docked: StoryObj<typeof TerminalScene> = {parameters: {docked: true,diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex 0df35c3ae54a..17a58e370e27 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -148,6 +148,12 @@ mc opens Midnight Commander. Tab switches panels; F3 views, F4 edits, F10 quits.Use Escape then a digit if your browser or keyboard captures function keys.mcview, mcedit, and mcdiff also run directly from the shell.tree lists folders and files. ncdu -r browses disk usage without allowing deletion.+node (or nodejs) installs Node.js on first use. pi installs the pi coding harness+and Node.js on first use. Try node --version or pi --help.+The browser downloads verified packages from GitHub and caches them when storage+is available. Stopping the terminal discards the installed files and local sessions.+pi runs offline: model calls, login, and package downloads need a network bridge.+Use /tmp for local scripts and pi sessions; mounted PostHog files keep their API rules.Project file sizes stay zero until opened; ncdu does not download their contents.Bundled tool licenses and source links are in /opt/posthog-tools/licenses.ph runs project commands and tools from connected MCP servers with your permissions.diff --git a/frontend/src/scenes/terminal/terminal-packages.json b/frontend/src/scenes/terminal/terminal-packages.jsonnew file mode 100644index 000000000000..afa62f60e9af--- /dev/null+++ b/frontend/src/scenes/terminal/terminal-packages.json@@ -0,0 +1,30 @@+{+ "packages": {+ "node": {+ "name": "Node.js",+ "version": "22.23.2",+ "file": "archives/node-22.23.2-linux-i386.tar.gz",+ "sha256": "558d910595883054c928aba5c8e46beeb888a37175f007ef5ce3e7508dbd87ca",+ "size": 28385805,+ "archiveSize": 73256960,+ "dependencies": [],+ "commands": {+ "node": "/opt/posthog-packages/node-22.23.2/bin/node",+ "nodejs": "/opt/posthog-packages/node-22.23.2/bin/node"+ }+ },+ "pi": {+ "name": "pi",+ "version": "0.87.1",+ "file": "archives/pi-0.87.1.tar.gz",+ "sha256": "95ffd3dac5996b471b7d5d3495128c403d3240202913156efb255f2045b4fb8e",+ "size": 20421625,+ "archiveSize": 76257280,+ "dependencies": ["node"],+ "commands": {+ "pi": "/opt/posthog-packages/pi-0.87.1/bin/pi"+ }+ }+ },+ "baseUrl": "https://raw.githubusercontent.com/PostHog/terminal-assets/852063f5a2ebf979ac834680dcfb1bb3ee985d08"+}diff --git a/frontend/src/scenes/terminal/terminalCommands.ts b/frontend/src/scenes/terminal/terminalCommands.tsindex 5ffb63aec98c..9ce7a4ff0c4c 100644--- a/frontend/src/scenes/terminal/terminalCommands.ts+++ b/frontend/src/scenes/terminal/terminalCommands.ts@@ -70,7 +70,7 @@ export class TerminalCommands {response = encoded} catch (error) {// A failed tool can put its whole payload in the message, and the guest reads- // this file into a shell variable inside a 128 MiB virtual machine.+ // this file into a shell variable inside the virtual machine.const encoded = envelope({ok: false,error: error instanceof Error ? error.message : 'The command failed. Try ph help.',diff --git a/frontend/src/scenes/terminal/terminalPackages.test.ts b/frontend/src/scenes/terminal/terminalPackages.test.tsnew file mode 100644index 000000000000..74d62edfc1b0--- /dev/null+++ b/frontend/src/scenes/terminal/terminalPackages.test.ts@@ -0,0 +1,143 @@+import { createHash } from 'node:crypto'++import { TerminalFilesystem } from './terminalFilesystem'+import { TerminalPackage, TerminalPackages } from './terminalPackages'++describe('optional terminal packages', () => {+ const originalGlobals = {+ fetch: globalThis.fetch,+ caches: globalThis.caches,+ Blob: globalThis.Blob,+ Response: globalThis.Response,+ DecompressionStream: globalThis.DecompressionStream,+ }+ const originalAny = Object.getOwnPropertyDescriptor(AbortSignal, 'any')+ const originalSubtle = Object.getOwnPropertyDescriptor(crypto, 'subtle')+ const compressed = new Uint8Array([1, 2, 3])+ const archive = new Uint8Array([4, 5, 6, 7])+ const pkg: TerminalPackage = {+ name: 'Example tool',+ version: '1.0.0',+ file: 'example.tar.gz',+ sha256: createHash('sha256').update(compressed).digest('hex'),+ size: compressed.length,+ archiveSize: archive.length,+ dependencies: [],+ commands: { example: '/opt/posthog-packages/example-1.0.0/bin/example' },+ }+ const response = (): Response => ({ ok: true, arrayBuffer: async () => compressed.slice().buffer }) as Response+ let cached: Response | undefined+ const cache = {+ match: jest.fn(async () => cached),+ put: jest.fn(async (_url: string, value: Response) => {+ cached = value+ }),+ delete: jest.fn(async () => {+ cached = undefined+ return true+ }),+ }+ const mount = (signal = new AbortController().signal): TerminalFilesystem => {+ const filesystem = new TerminalFilesystem()+ new TerminalPackages(+ filesystem,+ signal,+ { example: pkg },+ 'https://raw.githubusercontent.com/example/tools/pinned'+ ).mount()+ return filesystem+ }+ const open = (filesystem: TerminalFilesystem): Promise<{ bytes: Uint8Array }> =>+ filesystem.root.children!.get('packages')!.children!.get('example.tar')!.open!()++ beforeEach(() => {+ cached = undefined+ jest.clearAllMocks()+ Object.defineProperty(AbortSignal, 'any', { configurable: true, value: (signals: AbortSignal[]) => signals[0] })+ Object.defineProperty(crypto, 'subtle', {+ configurable: true,+ value: {+ digest: jest.fn(async (_algorithm: string, data: ArrayBuffer) =>+ createHash('sha256').update(new Uint8Array(data)).digest()+ ),+ },+ })+ Object.assign(globalThis, {+ fetch: jest.fn(async () => response()),+ caches: { open: jest.fn(async () => cache) },+ Blob: jest.fn(() => ({ stream: () => ({ pipeThrough: () => ({}) }) })),+ Response: jest.fn((bytes?: ArrayBuffer) => ({+ arrayBuffer: async () => (bytes instanceof ArrayBuffer ? bytes : archive.slice().buffer),+ ok: true,+ })),+ DecompressionStream: jest.fn(),+ })+ })++ afterEach(() => {+ Object.assign(globalThis, originalGlobals)+ if (originalAny) {+ Object.defineProperty(AbortSignal, 'any', originalAny)+ } else {+ Reflect.deleteProperty(AbortSignal, 'any')+ }+ if (originalSubtle) {+ Object.defineProperty(crypto, 'subtle', originalSubtle)+ } else {+ Reflect.deleteProperty(crypto, 'subtle')+ }+ })++ it('downloads only when opened, shares concurrent reads, and reuses verified downloads across sessions', async () => {+ const filesystem = mount()+ expect(fetch).not.toHaveBeenCalled()+ const [first, second] = await Promise.all([open(filesystem), open(filesystem)])+ expect(first.bytes).toEqual(archive)+ expect(second.bytes).toEqual(archive)+ expect(fetch).toHaveBeenCalledTimes(1)+ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/pinned/example.tar.gz'),+ expect.objectContaining({ credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer' })+ )+ expect((await open(mount())).bytes).toEqual(archive)+ expect(fetch).toHaveBeenCalledTimes(1)+ })++ it.each(['network', 'checksum', 'size', 'cached checksum'])(+ 'allows retry after a %s failure without exposing unverified bytes',+ async (failure) => {+ const filesystem = mount()+ if (failure === 'network') {+ jest.mocked(fetch).mockRejectedValueOnce(new Error('offline'))+ } else {+ const bad = {+ ok: true,+ arrayBuffer: async () => new Uint8Array(failure === 'size' ? [1] : [0, 0, 0]).buffer,+ } as Response+ if (failure === 'cached checksum') {+ cached = bad+ } else {+ jest.mocked(fetch).mockResolvedValueOnce(bad)+ }+ }+ await expect(open(filesystem)).rejects.toThrow()+ expect(cache.put).not.toHaveBeenCalled()+ expect((await open(filesystem)).bytes).toEqual(archive)+ }+ )++ it('installs when browser storage is unavailable', async () => {+ jest.mocked(caches.open).mockRejectedValue(new Error('Storage disabled'))+ expect((await open(mount())).bytes).toEqual(archive)+ })++ it('does not expose or cache a download after the terminal closes', async () => {+ const controller = new AbortController()+ jest.mocked(fetch).mockImplementationOnce(async () => {+ controller.abort()+ return response()+ })+ await expect(open(mount(controller.signal))).rejects.toThrow()+ expect(cache.put).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/terminal/terminalPackages.ts b/frontend/src/scenes/terminal/terminalPackages.tsnew file mode 100644index 000000000000..e44a10e3ec95--- /dev/null+++ b/frontend/src/scenes/terminal/terminalPackages.ts@@ -0,0 +1,141 @@+import manifest from './terminal-packages.json'+import { TerminalFilesystem } from './terminalFilesystem'++export interface TerminalPackage {+ name: string+ version: string+ file: string+ sha256: string+ size: number+ archiveSize: number+ dependencies: string[]+ commands: Record<string, string>+}++const CACHE_NAME = 'posthog-terminal-packages-v1'++export class TerminalPackages {+ private downloads = new Map<string, Promise<Uint8Array>>()++ constructor(+ private filesystem: TerminalFilesystem,+ private signal: AbortSignal,+ private packages: Record<string, TerminalPackage> = manifest.packages,+ private baseUrl: string = manifest.baseUrl+ ) {}++ private async download(pkg: TerminalPackage): Promise<Uint8Array> {+ const url = `${this.baseUrl}/${pkg.file}`+ let cache: Cache | undefined+ try {+ cache = await globalThis.caches?.open(CACHE_NAME)+ } catch {+ // Private browsing and storage quotas must not prevent installation.+ }+ const cached = await cache?.match(url).catch(() => undefined)+ const response =+ cached ??+ (await fetch(url, {+ signal: AbortSignal.any([this.signal, AbortSignal.timeout(120_000)]),+ credentials: 'omit',+ referrerPolicy: 'no-referrer',+ redirect: 'error',+ }))+ if (!response.ok) {+ throw new Error(`Could not download ${pkg.name}. Run the command again to retry.`)+ }+ const compressed = await response.arrayBuffer()+ const digest = await crypto.subtle.digest('SHA-256', compressed)+ const actual = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')+ if (compressed.byteLength !== pkg.size || actual !== pkg.sha256) {+ await cache?.delete(url).catch(() => false)+ throw new Error(`Could not verify ${pkg.name}. Run the command again to download a fresh copy.`)+ }+ if (this.signal.aborted) {+ throw new DOMException('Terminal closed', 'AbortError')+ }+ const archive = await new Response(+ new Blob([compressed]).stream().pipeThrough(new DecompressionStream('gzip'))+ ).arrayBuffer()+ if (archive.byteLength !== pkg.archiveSize) {+ throw new Error(`Could not unpack ${pkg.name}. Reload PostHog and try again.`)+ }+ if (this.signal.aborted) {+ throw new DOMException('Terminal closed', 'AbortError')+ }+ if (!cached) {+ await cache?.put(url, new Response(compressed)).catch(() => undefined)+ }+ return new Uint8Array(archive)+ }++ mount(): void {+ const directory = this.filesystem.directory('packages', this.filesystem.root)+ const bin = this.filesystem.directory('bin', this.filesystem.root)+ const cases: string[] = []+ for (const [id, pkg] of Object.entries(this.packages)) {+ this.filesystem.file(`${id}.tar`, directory, async () => {+ let download = this.downloads.get(id)+ if (!download) {+ download = this.download(pkg).finally(() => this.downloads.delete(id))+ this.downloads.set(id, download)+ }+ return { bytes: await download }+ }).size = pkg.archiveSize+ cases.push(`${id}) name='${pkg.name}'; version='${pkg.version}';;`)+ for (const [command, entrypoint] of Object.entries(pkg.commands)) {+ this.filesystem.text(+ command,+ bin,+ [+ '#!/bin/sh',+ ...[...pkg.dependencies, id].map(+ (dependency) => `sh /posthog/bin/install-tool ${dependency} || exit $?`+ ),+ `exec ${entrypoint} "$@"`,+ '',+ ].join('\n')+ )+ }+ }+ this.filesystem.text(+ 'install-tool',+ bin,+ `#!/bin/sh+set -eu+id="$1"+case "$id" in+${cases.join('\n')}+*) echo 'Unknown terminal tool. Reload PostHog and try again.' >&2; exit 1;;+esac+root=/opt/posthog-packages+target="$root/$id-$version"+[ -d "$target" ] && exit 0+mkdir -p "$root"+lock="$root/.$id.lock"+attempt=0+while ! mkdir "$lock" 2>/dev/null; do+ [ -d "$target" ] && exit 0+ attempt=$((attempt + 1))+ if [ "$attempt" -ge 120 ]; then+ echo 'Another installation is still running. Close and reopen the terminal to retry.' >&2+ exit 1+ fi+ sleep 1+done+stage="$root/.$id-$$"+trap 'rm -rf "$stage"; rmdir "$lock"' EXIT+trap 'exit 130' INT+trap 'exit 143' TERM HUP+[ -d "$target" ] && exit 0+printf 'Installing %s %s...\\n' "$name" "$version" >&2+mkdir "$stage"+if ! tar -xf "/posthog/packages/$id.tar" -C "$stage"; then+ echo 'Installation failed. Run the command again to retry.' >&2+ exit 1+fi+mv "$stage" "$target"+`+ )+ }+}diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.tsindex 05252d75bd79..2b8031602edc 100644--- a/frontend/src/scenes/terminal/terminalRuntime.ts+++ b/frontend/src/scenes/terminal/terminalRuntime.ts@@ -8,6 +8,8 @@ import biosUrl from './assets/seabios.bin?url'import toolsUrl from './assets/tools-linux-i386.tar.gz.bin?url'import vgaBiosUrl from './assets/vgabios.bin?url'import { NinePServer } from './ninepServer'+import packageManifest from './terminal-packages.json'+import { TerminalPackages } from './terminalPackages'function browserClock(): { timestamp: number; timezone: string } {const now = new Date()@@ -82,6 +84,7 @@ export class TerminalRuntime {if (signal.aborted || this.disposed) {return}+ new TerminalPackages(server.filesystem, signal).mount()const bin = server.filesystem.directory('bin', server.filesystem.root)server.filesystem.file('jq', bin, async () => ({ bytes: new Uint8Array(jq) })).size = jq.byteLengthserver.filesystem.file('tools.tar', bin, async () => ({ bytes: new Uint8Array(toolsArchive) })).size =@@ -91,7 +94,7 @@ export class TerminalRuntime {bios: { buffer: bios },vga_bios: { buffer: vgaBios },bzimage: { buffer: kernel },- memory_size: 128 * 1024 * 1024,+ memory_size: 512 * 1024 * 1024,filesystem: { handle9p: server.handle },cmdline: 'tsc=reliable mitigations=off random.trust_cpu=on',disable_keyboard: true,@@ -151,8 +154,16 @@ export class TerminalRuntime {`date -s @${clock.timestamp} > /dev/null`,'tar -xf /posthog/bin/tools.tar -C / || exit','export EDITOR=nano VISUAL=nano',+ 'mkdir -p /opt/posthog-packages && mount -t tmpfs -o size=256m tmpfs /opt/posthog-packages || exit',+ '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',+ ...Object.values(packageManifest.packages).flatMap((pkg) =>+ Object.keys(pkg.commands).map(+ (command) =>+ `cp /posthog/bin/${command} /usr/bin/${command} && chmod +x /usr/bin/${command} || exit`+ )+ ),'stty -F /dev/ttyS1 raw -echo',// 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 &)',diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 6cbdda0562f0..672b0a836f7a 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1614,7 +1614,7 @@ class CSPMiddleware:frame_ancestors,# The live debugger's repo browser reads PostHog/posthog from the GitHub API. The path keeps# the rest of the API, and every other repository, out of reach of injected script.- f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/",+ f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/",# https: lets heatmaps frame a customer's site. 'self' is for the replay player# frame, whose document is same-origin: an http origin does not match https:."frame-src 'self' https:",