Skip to content

: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.

fix(terminal): load project directories on demand (#105086)

Marius Andraf7ba60dd8d82
diff --git a/docs/published/handbook/engineering/project-structure.md b/docs/published/handbook/engineering/project-structure.md
index 434f52740557..9ff468d61352 100644
--- a/docs/published/handbook/engineering/project-structure.md
+++ b/docs/published/handbook/engineering/project-structure.md
@@ -62,6 +62,13 @@ App tooltips reuse the product descriptions from the scene configuration.
Opening Apps or Files from the collapsed sidebar temporarily expands the navigation over the page without changing the saved collapsed setting.
Selecting a destination, clicking outside, or pressing Escape closes the temporary navigation.
+The app-level terminal lives in `src/scenes/terminal` and opens with Ctrl+backtick when enabled.
+It starts without fetching the project tree.
+Browsing `/posthog/files` loads and caches each folder's immediate children; `/posthog/api` loads objects by type.
+Loading 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.
+
### `posthog`
The Django backend application. Key subdirectories:
diff --git a/frontend/src/scenes/terminal/TerminalView.tsx b/frontend/src/scenes/terminal/TerminalView.tsx
index c8dfe1d1e3ab..a6e472591f0d 100644
--- a/frontend/src/scenes/terminal/TerminalView.tsx
+++ b/frontend/src/scenes/terminal/TerminalView.tsx
@@ -152,7 +152,7 @@ export function TerminalView({
</LemonMenu>
<span role="status" className="text-secondary ml-auto text-xs">
{status === 'loading'
- ? 'Loading project files…'
+ ? 'Starting terminal…'
: status === 'booting'
? 'Starting Linux…'
: status === 'ready'
diff --git a/frontend/src/scenes/terminal/ninepServer.test.ts b/frontend/src/scenes/terminal/ninepServer.test.ts
index 339bf99daef4..84ee6774b791 100644
--- a/frontend/src/scenes/terminal/ninepServer.test.ts
+++ b/frontend/src/scenes/terminal/ninepServer.test.ts
@@ -117,7 +117,9 @@ describe('PostHog 9P filesystem', () => {
it('rejects nonempty folders, mismatched removal flags, and read-only mount entries', async () => {
const folder = filesystem.directory('folder', filesystem.root)
folder.remove = jest.fn(async () => {})
- filesystem.text('child', folder, '')
+ folder.loadChildren = async () => {
+ filesystem.text('child', folder, '')
+ }
const remove = (name: string, flags: number): Promise<{ type: number; body: NinePReader }> =>
request(76, new NinePWriter().number(1, 4).string(name).number(flags, 4))
expect((await remove('folder', 0x200)).body.number(4)).toBe(39)
@@ -128,6 +130,21 @@ describe('PostHog 9P filesystem', () => {
expect(folder.remove).not.toHaveBeenCalled()
})
+ it('checks an unloaded destination before renaming over an existing file', async () => {
+ const folder = filesystem.directory('folder', filesystem.root)
+ folder.mkdir = jest.fn()
+ folder.loadChildren = async () => {
+ filesystem.text('taken.json', folder, '{}')
+ }
+ const note = filesystem.root.children!.get('note.md')!
+ note.rename = jest.fn()
+ await walk('folder', 3)
+ const response = await request(20, new NinePWriter().number(2, 4).number(3, 4).string('taken.json'))
+ expect(response.type).toBe(7)
+ expect(response.body.number(4)).toBe(17)
+ expect(note.rename).not.toHaveBeenCalled()
+ })
+
it.each([50, 120])('commits complete, truncated content on message %i', async (operation) => {
expect(await open(513)).toBe(13)
await write('short')
diff --git a/frontend/src/scenes/terminal/ninepServer.ts b/frontend/src/scenes/terminal/ninepServer.ts
index 278b5eac6904..722038afb87b 100644
--- a/frontend/src/scenes/terminal/ninepServer.ts
+++ b/frontend/src/scenes/terminal/ninepServer.ts
@@ -212,6 +212,7 @@ export class NinePServer {
if (node.parent === parent && node.name === name) {
return
}
+ await parent.loadChildren?.()
this.validateDestination(parent, name)
for (let ancestor: TerminalNode | undefined = parent; ancestor; ancestor = ancestor.parent) {
if (ancestor === node) {
@@ -234,6 +235,7 @@ export class NinePServer {
if (!node.remove) {
throw new FilesystemError(30)
}
+ await node.loadChildren?.()
if (node.children?.size) {
throw new FilesystemError(39)
}
@@ -271,7 +273,15 @@ export class NinePServer {
const walked: TerminalNode[] = []
for (let i = 0; i < count; i++) {
const name = reader.string()
- const next = name === '..' ? (node.parent ?? node) : name === '.' ? node : node.children?.get(name)
+ if (name !== '.' && name !== '..') {
+ await node.loadChildren?.()
+ }
+ const next =
+ name === '..'
+ ? (node.parent ?? node)
+ : name === '.'
+ ? node
+ : (node.children?.get(name) ?? node.lookupChild?.(name))
if (!next) {
if (!walked.length) {
throw new FilesystemError(2)
@@ -294,6 +304,7 @@ export class NinePServer {
case 72: {
const parent = this.fid(reader.number(4)).node
const name = reader.string()
+ await parent.loadChildren?.()
this.validateDestination(parent, name)
if (!parent.mkdir) {
throw new FilesystemError(30)
@@ -310,6 +321,7 @@ export class NinePServer {
if (!parent.children) {
throw new FilesystemError(20)
}
+ await parent.loadChildren?.()
const node = parent.children.get(name)
if (!node) {
throw new FilesystemError(2)
@@ -338,6 +350,7 @@ export class NinePServer {
}
case 74: {
const source = this.fid(reader.number(4)).node
+ await source.loadChildren?.()
const node = source.children?.get(reader.string())
const parent = this.fid(reader.number(4)).node
const name = reader.string()
@@ -376,6 +389,7 @@ export class NinePServer {
if (!node.children) {
throw new FilesystemError(20)
}
+ await node.loadChildren?.()
// An offset indexes this list, so one listing holds its snapshot across pages. A
// removal between pages would otherwise shift the rest and drop an entry.
const entries =
diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.ts
index 26597848a986..7151052cb419 100644
--- a/frontend/src/scenes/terminal/posthogCommands.ts
+++ b/frontend/src/scenes/terminal/posthogCommands.ts
@@ -302,7 +302,7 @@ export class PosthogCommands {
this.connectedLoaded = true
}
- private parseArguments(tool: Command, argv: string[], cwd: string): Record<string, unknown> {
+ private async parseArguments(tool: Command, argv: string[], cwd: string): Promise<Record<string, unknown>> {
const args: Record<string, unknown> = Object.create(null)
const properties = object(tool.inputSchema.properties)
for (let index = 0; index < argv.length; index++) {
@@ -339,6 +339,7 @@ export class PosthogCommands {
}
}
if (tool.reference && typeof args[tool.reference.parameter] === 'string') {
+ await this.filesystem.loadReference(args[tool.reference.parameter] as string, cwd)
args[tool.reference.parameter] = this.filesystem.resolveReference(
args[tool.reference.parameter] as string,
cwd,
@@ -393,7 +394,7 @@ export class PosthogCommands {
const { invoke: _, ...description } = tool
return description
}
- return tool.invoke(this.parseArguments(tool, rest, cwd))
+ return tool.invoke(await this.parseArguments(tool, rest, cwd))
}
private async find(name: string): Promise<Command> {
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.ts
index 7fd1f47c2aa9..8c18dc094346 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts
@@ -71,6 +71,145 @@ describe('PostHog filesystem projection', () => {
jest.mocked(notebooksRetrieve).mockResolvedValue(notebook)
})
+ it('loads only browsed folders, shares pending requests, and refreshes visited directories', async () => {
+ let entries = [
+ entry('research', 'Research', 'folder'),
+ entry('other', 'Other', 'folder'),
+ entry('nested', 'Research/Nested', 'folder'),
+ entry('note1', 'Research/Notes'),
+ entry('12', 'Other/Dashboard', 'dashboard'),
+ ]
+ jest.mocked(fileSystemList).mockImplementation(async (_, params) => {
+ const { parent, depth, type } = params as { parent?: string; depth?: number; type?: string }
+ const results = entries.filter((item) =>
+ type
+ ? item.type === type
+ : 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)
+ const server = new NinePServer(fs, jest.fn())
+ const request = async (type: number, body: NinePWriter): Promise<NinePReader> => {
+ const bytes = await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))
+ const response = new NinePReader(bytes)
+ response.number(4)
+ expect(response.number(1)).toBe(type + 1)
+ response.number(2)
+ return response
+ }
+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string(''))
+ await request(110, new NinePWriter().number(1, 4).number(2, 4).number(1, 2).string('files'))
+ expect(fileSystemList).not.toHaveBeenCalled()
+ await request(40, new NinePWriter().number(2, 4).number(0, 8).number(4096, 4))
+ expect(fileSystemList).toHaveBeenCalledTimes(1)
+ expect(fileSystemList).toHaveBeenLastCalledWith(
+ '42',
+ { parent: '', depth: 1, limit: 500, offset: 0 },
+ expect.anything()
+ )
+ expect(notebooksList).not.toHaveBeenCalled()
+ const files = fs.root.children!.get('files')!
+ const research = files.children!.get('Research')!
+ expect(research.children!.size).toBe(0)
+ await Promise.all([research.loadChildren!(), research.loadChildren!()])
+ expect(fileSystemList).toHaveBeenCalledTimes(2)
+ expect(fileSystemList).toHaveBeenLastCalledWith(
+ '42',
+ { parent: 'Research', depth: 2, limit: 500, offset: 0 },
+ expect.anything()
+ )
+ expect([...research.children!.keys()]).toEqual(['Nested', 'Notes.md'])
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ const note = research.children!.get('Notes.md')!
+ await request(
+ 110,
+ new NinePWriter().number(2, 4).number(3, 4).number(2, 2).string('Research').string('Notes.md')
+ )
+ expect(fileSystemList).toHaveBeenCalledTimes(2)
+ jest.mocked(fileSystemList).mockResolvedValueOnce({ count: 1, results: [entries[4]] })
+ const cachedPath = jest.spyOn(
+ Object.defineProperty(entries[3], 'path', { configurable: true, get: () => 'Research/Notes' }),
+ 'path',
+ 'get'
+ )
+ await files.children!.get('Other')!.loadChildren!()
+ expect(files.children!.get('Other')!.children!.has('Dashboard.json')).toBe(true)
+ expect(cachedPath).not.toHaveBeenCalled()
+ cachedPath.mockRestore()
+ entries.push(entry('note2', 'Research/New'))
+ await fs.load()
+ expect(fileSystemList).toHaveBeenCalledTimes(6)
+ expect(research.children!.get('Notes.md')).toBe(note)
+ 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(notebooksRetrieve).not.toHaveBeenCalled()
+ entries = entries.map((item) => ({ ...item, path: item.path.replace(/^Research/, 'Published') }))
+ await fs.load()
+ expect(files.children!.has('Research')).toBe(false)
+ expect(files.children!.has('Published')).toBe(true)
+ await fs.loadReference('/posthog/files/Published/Notes.md', '/')
+ expect(fs.resolveReference('/posthog/files/Published/Notes.md', '/')).toBe('note1')
+ const publishedNote = files.children!.get('Published')!.children!.get('Notes.md')!
+ entries = entries.filter((item) => !item.path.startsWith('Published'))
+ await fs.load()
+ expect(files.children!.has('Published')).toBe(false)
+ await expect(publishedNote.open!()).rejects.toMatchObject({ errno: 116 })
+ })
+
+ it.each(['dashboard', 'hog_function/source', 'unknown'])(
+ 'loads API paths for %s and retries failed directory pages without caching partial results',
+ async (type) => {
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ const server = new NinePServer(fs, jest.fn())
+ const request = async (type: number, body: NinePWriter): Promise<NinePReader> => {
+ const bytes = await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))
+ const response = new NinePReader(bytes)
+ response.number(4)
+ expect(response.number(1)).toBe(type + 1)
+ response.number(2)
+ return response
+ }
+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string(''))
+ const name = encodeURIComponent(type)
+ const walked = await request(
+ 110,
+ new NinePWriter().number(1, 4).number(2, 4).number(2, 2).string('api').string(name)
+ )
+ expect(walked.number(2)).toBe(2)
+ const directory = fs.root.children!.get('api')!.children!.get(name)!
+ expect(fileSystemList).not.toHaveBeenCalled()
+ jest.mocked(fileSystemList)
+ .mockResolvedValueOnce({ count: 2, next: '/next', results: [entry('12', 'First', type)] })
+ .mockRejectedValueOnce(new Error('Try again'))
+ await expect(directory.loadChildren!()).rejects.toThrow('Try again')
+ expect(directory.children!.size).toBe(0)
+ jest.mocked(fileSystemList)
+ .mockResolvedValueOnce({ count: 2, next: '/next', results: [entry('12', 'First', type)] })
+ .mockResolvedValueOnce({ count: 2, next: null, results: [entry('13', 'Second', type)] })
+ await fs.loadReference(`/posthog/api/${name}/13.json`, '/')
+ 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 },
+ ])
+ expect(notebooksList).not.toHaveBeenCalled()
+ expect(apiMutator).not.toHaveBeenCalled()
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 0, next: null, results: [] })
+ await fs.load()
+ expect(fs.root.children!.get('api')!.children!.get(name)).toBe(directory)
+ expect(directory.children!.size).toBe(0)
+ const fresh = new PosthogFilesystem('42', new AbortController().signal)
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [entry('13', 'Second', type)] })
+ await fresh.loadReference(`/posthog/api/${name}/13.json`, '/')
+ expect(fresh.resolveReference(`/posthog/api/${name}/13.json`, '/', type)).toBe('13')
+ }
+ )
+
it('projects markdown without changing the stored path and saves with the version it read', async () => {
const session = new AbortController()
const read = new AbortController()
@@ -444,6 +583,27 @@ describe('PostHog filesystem projection', () => {
}
})
+ it('updates permissions in both projections when browsing an overlapping API type', async () => {
+ const object = entry('12', 'Object', 'dashboard')
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [object] })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.root.children!.get('files')!.loadChildren!()
+ const file = fs.root.children!.get('files')!.children!.get('Object.json')!
+ const type = fs.root.children!.get('api')!.children!.get('dashboard')!
+ const apiFile = type.children!.get('12.json')!
+ expect(file.writable).toBe(true)
+ expect(apiFile.writable).toBe(true)
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 1,
+ results: [{ ...object, user_access_level: 'viewer' }],
+ })
+ await type.loadChildren!()
+ expect(file.writable).toBe(false)
+ expect(apiFile.writable).toBe(false)
+ expect(fs.root.children!.get('files')!.children!.get('Object.json')).toBe(file)
+ expect(type.children!.get('12.json')).toBe(apiFile)
+ })
+
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' })
@@ -474,7 +634,8 @@ describe('PostHog filesystem projection', () => {
for (const node of fs.root.children!.get('files')!.children!.values()) {
expect(node.writable).toBe(false)
}
- for (const directory of fs.root.children!.get('api')!.children!.values()) {
+ for (const type of ['unknown', 'dashboard']) {
+ const directory = fs.root.children!.get('api')!.children!.get(type)!
expect([...directory.children!.values()][0].writable).toBe(false)
}
})
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.ts
index 756a819864eb..0df35c3ae54a 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts
@@ -7,8 +7,9 @@ import {
fileSystemRetrieve,
getFileSystemMoveCreateUrl,
} from '~/generated/core/api'
-import type { FileSystemApi } from '~/generated/core/api.schemas'
+import type { FileSystemApi, FileSystemListParams } from '~/generated/core/api.schemas'
import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { fileSystemTypes } from '~/products'
import { actionsPartialUpdate, actionsRetrieve } from 'products/actions/frontend/generated/api'
import { cohortsPartialUpdate, cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
@@ -125,10 +126,12 @@ Files open for writing must be closed before removal. Use ph notebook-create to
Work in /tmp for programs that save by renaming a temporary file,
then use cat /tmp/edited.md > '/posthog/files/path/to/notebook.md'.
-Directories are a snapshot from startup. File contents load from the API on open.
-Listing directories never downloads object contents. Sizes are zero until a file
-is opened, then show its last known size. Startup uses the notebook index to find
-markdown notebooks without fetching their bodies.
+Directories load when you browse them and stay cached until ph refresh.
+The terminal starts without downloading the project tree. Browsing /posthog/files
+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 notebook
+index loads when you first browse notebooks, without fetching their bodies.
Run ph refresh to discover new or renamed objects. Unsupported object types
expose their filesystem record as JSON. Legacy rich-text notebooks stay JSON.
Characters that cannot appear in Unix filenames are percent-encoded. Duplicate
@@ -163,11 +166,39 @@ export class PosthogFilesystem extends TerminalFilesystem {
private readonly files = this.directory('files', this.root)
private readonly api = this.directory('api', this.root)
private readonly references = new Map<string, FileSystemApi>()
+ private readonly mountedFiles = new Map<string, TerminalNode>()
private readonly projectNodes = new Map<
TerminalNode,
{ parts: string[]; entry?: FileSystemApi; extension?: string }
>()
+ 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>
+
+ async loadReference(value: string, cwd: string): Promise<void> {
+ if (!value.includes('/') && !/\.(md|json)$/.test(value)) {
+ return
+ }
+ const parts = (value.startsWith('/') ? value : `${cwd}/${value}`).split('/').filter(Boolean)
+ if (parts.shift() !== 'posthog') {
+ return
+ }
+ let node: TerminalNode | undefined = this.root
+ for (const part of parts) {
+ if (!node) {
+ return
+ }
+ if (part === '..') {
+ node = node.parent ?? node
+ } else if (part !== '.') {
+ await node.loadChildren?.()
+ node = node.children?.get(part) ?? node.lookupChild?.(part)
+ }
+ }
+ }
+
resolveReference(value: string, cwd: string, type?: string): string {
const parts: string[] = []
for (const part of (value.startsWith('/') ? value : `${cwd}/${value}`).split('/')) {
@@ -200,10 +231,17 @@ export class PosthogFilesystem extends TerminalFilesystem {
super()
this.text('README.txt', this.root, TERMINAL_README)
this.registerDirectory(this.files, [])
+ this.mountApiDirectories(new Map())
+ this.api.lookupChild = (name) => {
+ const node = this.directory(name, this.api)
+ node.loadChildren = () => this.ensureDirectory(node)
+ return node
+ }
}
private registerDirectory(node: TerminalNode, parts: string[], entry?: FileSystemApi): void {
this.projectNodes.set(node, { parts, entry })
+ node.loadChildren = () => this.ensureDirectory(node)
node.mkdir = async (name) => {
const directory = this.projectNodes.get(node)
if (!directory) {
@@ -217,6 +255,7 @@ export class PosthogFilesystem extends TerminalFilesystem {
)
const child = this.directory(name, node)
this.registerDirectory(child, parts, entry)
+ this.loadedDirectories.add(child)
return child
}
if (node !== this.files) {
@@ -260,6 +299,9 @@ export class PosthogFilesystem extends TerminalFilesystem {
}
this.references.delete(this.mountedPath(node))
this.projectNodes.delete(node)
+ if (source.entry && source.extension) {
+ this.mountedFiles.delete(this.fileIdentity(source.entry, source.extension))
+ }
node.parent!.children!.delete(node.name)
node.removed = true
const entry = source.entry
@@ -516,51 +558,171 @@ export class PosthogFilesystem extends TerminalFilesystem {
}
}
- async load(): Promise<void> {
+ private mountApiDirectories(directories: Map<string, TerminalNode>): void {
+ const names = new Set([
+ ...Object.keys(fileSystemTypes).map(terminalFilename),
+ 'unknown',
+ ...[...directories.values()].filter((node) => node.parent === this.api).map((node) => node.name),
+ ])
+ for (const name of names) {
+ const node = this.mountDirectory(name, this.api, directories)
+ node.loadChildren = () => this.ensureDirectory(node)
+ }
+ }
+
+ private ensureDirectory(node: TerminalNode): Promise<void> {
+ if (this.loadedDirectories.has(node)) {
+ return Promise.resolve()
+ }
+ const pending = this.pendingDirectories.get(node)
+ if (pending) {
+ return pending
+ }
+ const request = this.directoryQueue.then(() => this.loadDirectory(node))
+ this.pendingDirectories.set(node, request)
+ this.directoryQueue = request.catch(() => {})
+ void request.finally(() => this.pendingDirectories.delete(node)).catch(() => {})
+ 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 directoryParams(
+ node: TerminalNode
+ ): FileSystemListParams & { parent?: string; depth?: number; type?: string } {
+ if (node.removed) {
+ throw new FilesystemError(116)
+ }
+ const directory = this.projectNodes.get(node)
+ const type = node.parent === this.api ? this.storedName(node.name) : undefined
+ if (!directory && !type) {
+ throw new FilesystemError(116)
+ }
+ // The list endpoint supports parent/depth/type filters that its generated schema omits.
+ return directory ? { parent: joinPath(directory.parts), depth: directory.parts.length + 1 } : { type }
+ }
+
+ private async directoryEntries(params: ReturnType<PosthogFilesystem['directoryParams']>): Promise<FileSystemApi[]> {
const entries: FileSystemApi[] = []
let offset = 0
while (true) {
- const page = await fileSystemList(this.projectId, { limit: 500, offset }, { signal: this.signal })
+ const page = await fileSystemList(
+ this.projectId,
+ { ...params, limit: 500, offset },
+ { signal: this.signal }
+ )
entries.push(...page.results)
if (!page.next) {
- break
+ return entries
}
if (!page.results.length || entries.length > 50_000) {
- throw new Error('This project tree is too large for the terminal experiment.')
+ throw new Error('This directory is too large for the terminal. Open a smaller folder instead.')
}
offset += page.results.length
}
- entries.sort((a, b) => a.path.localeCompare(b.path) || a.id.localeCompare(b.id))
- const markdownNotebooks = new Map<string, NotebookMinimalApi>()
- if (entries.some((entry) => entry.type === 'notebook')) {
- let offset = 0
- while (true) {
- const page = await notebooksList(
- this.projectId,
- { contains: 'markdown-notebook', limit: 500, offset },
- { signal: this.signal }
+ }
+
+ private async loadDirectory(node: TerminalNode): Promise<void> {
+ const entries = await this.directoryEntries(this.directoryParams(node))
+ const markdownNotebooks = entries.some((entry) => entry.type === 'notebook')
+ ? await this.loadNotebookIndex()
+ : (this.markdownNotebooks ?? new Map<string, NotebookMinimalApi>())
+ this.mountEntries(entries, markdownNotebooks, true)
+ this.loadedDirectories.add(node)
+ }
+
+ private async refreshDirectories(): Promise<void> {
+ const directories = this.loadedDirectories.size ? [...this.loadedDirectories] : [this.files]
+ const scopes = directories.filter((node) => !node.removed).map((node) => this.directoryParams(node))
+ const parents = new Set(scopes.flatMap((scope) => (scope.parent === undefined ? [] : [scope.parent])))
+ const types = new Set(scopes.flatMap((scope) => (scope.type === undefined ? [] : [scope.type])))
+ const inScope = (entry: FileSystemApi): boolean =>
+ types.has(entry.type ?? 'unknown') || parents.has(joinPath(splitPath(entry.path).slice(0, -1)))
+ const previousEntries = [...this.projectNodes.values()].flatMap(({ entry }) => (entry ? [entry] : []))
+ const refreshed = new Map<string, FileSystemApi>()
+ for (const scope of scopes) {
+ for (const entry of await this.directoryEntries(scope)) {
+ refreshed.set(entry.id, entry)
+ }
+ }
+ const removedFolders = new Set(
+ previousEntries
+ .filter(
+ (entry) => entry.type === 'folder' && inScope(entry) && refreshed.get(entry.id)?.path !== entry.path
)
- for (const notebook of page.results) {
- markdownNotebooks.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.')
+ .map((entry) => entry.path)
+ )
+ const retained = previousEntries.filter((entry) => {
+ if (inScope(entry)) {
+ return false
+ }
+ const parts = splitPath(entry.path)
+ for (let depth = 1; depth < parts.length; depth++) {
+ if (removedFolders.has(joinPath(parts.slice(0, depth)))) {
+ return false
}
- offset += page.results.length
+ }
+ return true
+ })
+ const merged = new Map(retained.map((entry) => [entry.id, entry]))
+ for (const entry of refreshed.values()) {
+ merged.set(entry.id, entry)
+ }
+ this.markdownNotebooks = undefined
+ const entries = [...merged.values()]
+ const markdownNotebooks = entries.some((entry) => entry.type === 'notebook')
+ ? await this.loadNotebookIndex()
+ : new Map<string, NotebookMinimalApi>()
+ this.mountEntries(entries, markdownNotebooks)
+ for (const node of directories) {
+ if (!node.removed) {
+ this.loadedDirectories.add(node)
}
}
- const previousNodes = this.mountedNodes()
+ }
+
+ load(): Promise<void> {
+ const request = this.directoryQueue.then(() => this.refreshDirectories())
+ this.directoryQueue = request.catch(() => {})
+ return request
+ }
+
+ private mountEntries(
+ entries: FileSystemApi[],
+ markdownNotebooks: Map<string, NotebookMinimalApi>,
+ 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(
[...previousNodes].filter((node) => node.children).map((node) => [this.mountedPath(node), node])
)
- const files = new Map(
- [...this.projectNodes]
- .filter(([, metadata]) => metadata.entry && metadata.extension)
- .map(([node, metadata]) => [this.fileIdentity(metadata.entry!, metadata.extension!), node])
- )
+ const files = incremental ? this.mountedFiles : new Map(this.mountedFiles)
const apiFiles = new Map(
[...previousNodes]
.filter((node) => !node.children && node.parent?.parent === this.api)
@@ -569,13 +731,27 @@ export class PosthogFilesystem extends TerminalFilesystem {
for (const node of previousNodes) {
node.children?.clear()
}
- this.references.clear()
- this.projectNodes.clear()
- this.registerDirectory(this.files, [])
+ if (!incremental) {
+ this.references.clear()
+ this.projectNodes.clear()
+ this.mountedFiles.clear()
+ this.registerDirectory(this.files, [])
+ this.mountApiDirectories(directories)
+ } else {
+ for (const entry of entries) {
+ const extension = entry.type === 'notebook' && markdownNotebooks.has(entry.ref ?? '') ? '.md' : '.json'
+ const existing = files.get(this.fileIdentity(entry, extension))
+ if (existing) {
+ existing.parent!.children!.delete(existing.name)
+ this.references.delete(this.mountedPath(existing))
+ }
+ }
+ }
for (const entry of entries.filter((item) => item.type === 'folder' && item.user_access_level !== 'none')) {
const parts = splitPath(entry.path)
this.registerDirectory(this.parent(parts, this.files, directories), parts, entry)
}
+ const mountedApiPaths = new Set<string>()
for (const entry of entries) {
if (entry.type === 'folder' || entry.user_access_level === 'none') {
continue
@@ -605,29 +781,36 @@ export class PosthogFilesystem extends TerminalFilesystem {
writable,
files.get(this.fileIdentity(entry, extension))
)
+ this.mountedFiles.set(this.fileIdentity(entry, extension), file)
file.writeKey = JSON.stringify([entry.type, entry.ref ?? entry.id])
this.projectNodes.set(file, { parts: splitPath(entry.path), entry, extension })
file.rename = (parent, name) => this.move(file, parent, name)
file.remove = () => this.remove(file)
this.references.set(`/posthog/files/${[...parts.map(terminalFilename), name].join('/')}`, entry)
const type = this.mountDirectory(terminalFilename(entry.type ?? 'unknown'), this.api, directories)
+ type.loadChildren = () => this.ensureDirectory(type)
const apiName = `${terminalFilename(entry.ref ?? entry.id)}.json`
- if (!type.children!.has(apiName)) {
+ const apiPath = `${this.mountedPath(type)}/${apiName}`
+ if (!mountedApiPaths.has(apiPath)) {
+ mountedApiPaths.add(apiPath)
const apiFile = this.mountFile(
apiName,
type,
(signal) => this.json(entry, writable, signal),
writable,
- apiFiles.get(`${this.mountedPath(type)}/${apiName}`)
+ apiFiles.get(apiPath) ?? type.children!.get(apiName)
)
apiFile.writeKey = file.writeKey
- this.references.set(`/posthog/api/${type.name}/${apiName}`, entry)
+ this.references.set(apiPath, entry)
}
}
- const currentNodes = this.mountedNodes()
- for (const node of previousNodes) {
- if (!currentNodes.has(node)) {
- node.removed = true
+ if (!incremental) {
+ const currentNodes = this.mountedNodes()
+ for (const node of previousNodes) {
+ if (!currentNodes.has(node)) {
+ node.removed = true
+ this.loadedDirectories.delete(node)
+ }
}
}
}
diff --git a/frontend/src/scenes/terminal/terminalFilesystem.ts b/frontend/src/scenes/terminal/terminalFilesystem.ts
index 15058914df12..53bcfe68adf2 100644
--- a/frontend/src/scenes/terminal/terminalFilesystem.ts
+++ b/frontend/src/scenes/terminal/terminalFilesystem.ts
@@ -8,6 +8,8 @@ export interface TerminalNode {
name: string
parent?: TerminalNode
children?: Map<string, TerminalNode>
+ loadChildren?: () => Promise<void>
+ lookupChild?: (name: string) => TerminalNode
open?: (signal?: AbortSignal) => Promise<TerminalFile>
size: number
writable: boolean
diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.ts
index 9f4dbafa432d..94c79bb8d399 100644
--- a/frontend/src/scenes/terminal/terminalLogic.test.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts
@@ -9,6 +9,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
+import { PosthogFilesystem } from './posthogFilesystem'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
import { TerminalRuntime } from './terminalRuntime'
@@ -51,6 +52,7 @@ describe('terminal lifecycle', () => {
featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: true })
terminalLogic.actions.start()
await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ expect(jest.mocked(PosthogFilesystem).mock.results[0].value.load).not.toHaveBeenCalled()
const runtime = jest.mocked(TerminalRuntime).mock.results[0].value
featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })
expect(runtime.dispose).toHaveBeenCalledTimes(1)
diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.ts
index 2da3b7614e86..af617d1c37b3 100644
--- a/frontend/src/scenes/terminal/terminalLogic.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.ts
@@ -191,7 +191,7 @@ export const terminalLogic = kea<terminalLogicType>([
actions.stop()
}
},
- start: async (_, breakpoint) => {
+ start: async () => {
const projectId = values.currentTeamId
if (!values.terminalEnabled || !projectId || ['loading', 'booting', 'ready'].includes(values.status)) {
return
@@ -226,11 +226,6 @@ export const terminalLogic = kea<terminalLogicType>([
actions.setStatus('loading')
try {
const filesystem = new PosthogFilesystem(String(projectId), controller.signal)
- await filesystem.load()
- breakpoint()
- if (controller.signal.aborted) {
- return
- }
cache.filesystem = filesystem
new PosthogCommands(String(projectId), controller.signal, filesystem)
actions.setStatus('booting')