:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(terminal): create blank markdown files (#106472)
Marius Andra85267bfb5851
diff --git a/frontend/src/scenes/terminal/ninepServer.ts b/frontend/src/scenes/terminal/ninepServer.tsindex 0aff36bd622c..066a79af2675 100644--- a/frontend/src/scenes/terminal/ninepServer.ts+++ b/frontend/src/scenes/terminal/ninepServer.ts@@ -313,6 +313,23 @@ export class NinePServer {}return qid(result, await parent.mkdir(name))}+ case 14: {+ const id = reader.number(4)+ const parent = this.fid(id).node+ const name = reader.string()+ const flags = reader.number(4)+ reader.number(4)+ reader.number(4)+ await parent.loadChildren?.()+ this.validateDestination(parent, name)+ if (!parent.create) {+ throw new FilesystemError(30)+ }+ const fid = { node: await parent.create(name, signal) }+ await this.open(fid, flags, signal)+ this.fids.set(id, fid)+ return qid(result, fid.node).number(this.messageSize - 24, 4)+ }case 76: {const parent = this.fid(reader.number(4)).nodeconst name = reader.string()diff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.tsindex 889c3c05428e..eda9443f51cf 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts@@ -5,7 +5,12 @@ import apiMutator from 'lib/api-orval-mutator'import { fileSystemCreate, fileSystemDestroy, fileSystemList, fileSystemRetrieve } from '~/generated/core/api'import type { FileSystemApi } from '~/generated/core/api.schemas'-import { notebooksList, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'+import {+ notebooksCreate,+ notebooksList,+ notebooksPartialUpdate,+ notebooksRetrieve,+} from 'products/notebooks/frontend/generated/api'import type { NotebookApi } from 'products/notebooks/frontend/generated/api.schemas'import { insightsList } from 'products/product_analytics/frontend/generated/api'@@ -25,6 +30,7 @@ jest.mock('lib/api-orval-mutator', () => {return { __esModule: true, default: mutator, apiMutator: mutator }})jest.mock('products/notebooks/frontend/generated/api', () => ({+ notebooksCreate: jest.fn(),notebooksRetrieve: jest.fn(),notebooksList: jest.fn(),notebooksPartialUpdate: jest.fn(),@@ -69,6 +75,260 @@ describe('PostHog filesystem projection', () => {jest.mocked(notebooksRetrieve).mockResolvedValue(notebook)})+ it.each([+ { folder: '', name: 'Blank.md', flags: 1, text: '' },+ { folder: 'Research', name: 'Notes.md', flags: 577, text: '' },+ { folder: 'Research', name: 'Notes%2Fdraft.md', flags: 577, text: '# New notes\n' },+ { folder: 'Research', name: 'Draft.md', flags: 577, text: '# New notes\n', concurrent: true },+ ])('creates and reopens $folder/$name with content "$text"', async ({ folder, name, flags, text, concurrent }) => {+ const title = decodeURIComponent(name)+ const createdEntry = entry('created', folder ? `${folder}/${title.replaceAll('/', '\\/')}` : title)+ let current = {+ ...notebook,+ short_id: 'created',+ content: {+ type: 'doc',+ content: [{ type: 'ph-markdown-notebook', attrs: { nodeId: 'markdown-notebook-v2', markdown: '' } }],+ },+ }+ jest.mocked(fileSystemList).mockResolvedValue({ count: 0, results: [] })+ jest.mocked(notebooksCreate).mockImplementation(async () => {+ const entries = concurrent ? [entry('another', createdEntry.path), createdEntry] : [createdEntry]+ jest.mocked(fileSystemList).mockResolvedValue({ count: entries.length, results: entries })+ return current+ })+ jest.mocked(notebooksRetrieve).mockImplementation(async (_, id) => (id === 'another' ? notebook : current))+ jest.mocked(notebooksPartialUpdate).mockImplementation(async (_, __, body) => {+ current = { ...current, content: body!.content as typeof current.content, version: current.version! + 1 }+ return current+ })+ const confirm = jest.fn().mockResolvedValue(true)+ const signal = new AbortController().signal+ const fs = new PosthogFilesystem('42', signal, confirm, true)+ await fs.load()+ const files = fs.root.children!.get('files')!+ if (folder) {+ jest.mocked(fileSystemCreate).mockResolvedValue(entry('folder', folder, 'folder'))+ await files.mkdir!(folder)+ confirm.mockClear()+ }+ const server = new NinePServer(fs, jest.fn())+ const request = async (type: number, body: NinePWriter): Promise<NinePReader> => {+ const response = new NinePReader(+ await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))+ )+ 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('').number(0, 4))+ const walk = new NinePWriter()+ .number(1, 4)+ .number(2, 4)+ .number(folder ? 2 : 1, 2)+ .string('files')+ if (folder) {+ walk.string(folder)+ }+ await request(110, walk)+ await request(14, new NinePWriter().number(2, 4).string(name).number(flags, 4).number(0o644, 4).number(0, 4))+ expect(notebooksCreate).toHaveBeenCalledWith(+ '42',+ expect.objectContaining({ title, _create_in_folder: folder, text_content: '', content: current.content }),+ { signal }+ )+ expect(confirm).toHaveBeenCalledTimes(1)+ if (text) {+ const data = new TextEncoder().encode(text)+ await request(118, new NinePWriter().number(2, 4).number(0, 8).number(data.length, 4).data(data))+ await request(50, new NinePWriter().number(2, 4).number(0, 4))+ }+ await request(120, new NinePWriter().number(2, 4))+ expect(notebooksCreate).toHaveBeenCalledTimes(1)+ expect(notebooksPartialUpdate).toHaveBeenCalledTimes(text ? 1 : 0)+ expect(fs.writers.size).toBe(0)+ await fs.load()+ const parent = folder ? files.children!.get(folder)! : files+ const createdName = concurrent ? `${name}~created.md` : name+ const file = await parent.children!.get(createdName)!.open!()+ expect(decoder.decode(file.bytes)).toBe(text)+ expect(fs.resolveReference(createdName, fs.folderPath(folder), 'notebook')).toBe('created')+ expect(await fs.navigationUrl(createdName, fs.folderPath(folder))).toBe('/notebooks/created')+ if (concurrent) {+ expect(fs.resolveReference(name, fs.folderPath(folder), 'notebook')).toBe('another')+ await file.save!(new TextEncoder().encode('Edit after refresh'))+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(+ '42',+ 'created',+ expect.objectContaining({ text_content: 'Edit after refresh' }),+ expect.anything()+ )+ const other = await parent.children!.get(name)!.open!()+ expect(decoder.decode(other.bytes)).toBe('# Hello 🦔')+ }+ })++ it.each([+ { name: 'Draft.md', allowed: false, fails: false, errno: 5 },+ { name: 'Draft.md', allowed: true, fails: true, errno: 5 },+ { name: 'Notes.md', allowed: true, fails: false, errno: 17 },+ { name: 'Draft.sql', allowed: true, fails: false, errno: 95 },+ { name: 'Draft.md~', allowed: true, fails: false, errno: 95 },+ ])('rejects creation of $name with allowed=$allowed and fails=$fails', async ({ name, allowed, fails, errno }) => {+ const confirm = jest.fn().mockResolvedValue(allowed)+ jest.mocked(notebooksCreate).mockRejectedValue(new Error('Permission denied'))+ const fs = new PosthogFilesystem('42', new AbortController().signal, confirm, true)+ await fs.load()+ const folder = fs.root.children!.get('files')!.children!.get('Research')!+ const before = [...folder.children!.entries()]+ const server = new NinePServer(fs, jest.fn())+ const request = async (type: number, body: NinePWriter): Promise<{ type: number; body: NinePReader }> => {+ const response = new NinePReader(+ await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))+ )+ response.number(4)+ const responseType = response.number(1)+ response.number(2)+ return { type: responseType, body: response }+ }+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string('').number(0, 4))+ await request(110, new NinePWriter().number(1, 4).number(2, 4).number(2, 2).string('files').string('Research'))+ const response = await request(+ 14,+ new NinePWriter().number(2, 4).string(name).number(1, 4).number(0o644, 4).number(0, 4)+ )+ expect(response.type).toBe(7)+ expect(response.body.number(4)).toBe(errno)+ expect(notebooksCreate).toHaveBeenCalledTimes(fails ? 1 : 0)+ expect([...folder.children!.entries()]).toEqual(before)+ expect(fs.writers.size).toBe(0)+ })++ it.each(['lookup error', 'missing entry', 'open error'])(+ 'recovers a created notebook after %s without duplicating it',+ async (failure) => {+ jest.mocked(notebooksCreate).mockImplementation(async () => {+ jest.mocked(fileSystemList).mockResolvedValue({+ count: 2,+ next: null,+ results: [entry('note1', 'Research/Notes'), entry('created', 'Research/Draft.md')],+ })+ if (failure === 'lookup error') {+ jest.mocked(fileSystemList).mockRejectedValueOnce(new Error('Network error'))+ } else if (failure === 'missing entry') {+ jest.mocked(fileSystemList).mockResolvedValueOnce({ count: 0, results: [] })+ } else {+ jest.mocked(notebooksRetrieve).mockRejectedValueOnce(new Error('Network error'))+ }+ return { ...notebook, short_id: 'created' }+ })+ const fs = new PosthogFilesystem(+ '42',+ new AbortController().signal,+ jest.fn().mockResolvedValue(true),+ true+ )+ await fs.load()+ const server = new NinePServer(fs, jest.fn())+ const request = async (type: number, body: NinePWriter): Promise<{ type: number; body: NinePReader }> => {+ const response = new NinePReader(+ await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))+ )+ response.number(4)+ const responseType = response.number(1)+ response.number(2)+ return { type: responseType, body: response }+ }+ const create = async (fid: number): Promise<number> => {+ await request(+ 110,+ new NinePWriter().number(1, 4).number(fid, 4).number(2, 2).string('files').string('Research')+ )+ const response = await request(+ 14,+ new NinePWriter().number(fid, 4).string('Draft.md').number(1, 4).number(0o644, 4).number(0, 4)+ )+ return response.type === 7 ? response.body.number(4) : 0+ }+ await request(+ 104,+ new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string('').number(0, 4)+ )++ expect(await create(2)).toBe(5)+ expect(await create(3)).toBe(17)+ expect(notebooksCreate).toHaveBeenCalledTimes(1)+ expect(fs.root.children!.get('files')!.children!.get('Research')!.children!.has('Draft.md')).toBe(true)+ expect(+ (await request(110, new NinePWriter().number(3, 4).number(4, 4).number(1, 2).string('Draft.md'))).type+ ).toBe(111)+ expect((await request(12, new NinePWriter().number(4, 4).number(0, 4))).type).toBe(13)+ const content = await request(116, new NinePWriter().number(4, 4).number(0, 8).number(1024, 4))+ expect(content.type).toBe(117)+ expect(decoder.decode(content.body.data(content.body.number(4)))).toBe('# Hello 🦔')+ expect((await request(120, new NinePWriter().number(4, 4))).type).toBe(121)+ expect(fs.writers.size).toBe(0)+ }+ )++ it.each(['confirmation', 'post'])('handles a guest flush during %s without an untracked create', async (phase) => {+ let approve!: (approved: boolean) => void+ const confirm = jest.fn(+ () =>+ new Promise<boolean>((resolve) => {+ approve = resolve+ })+ )+ let completePost!: () => void+ jest.mocked(notebooksCreate).mockImplementation(async () => {+ if (phase === 'post') {+ await new Promise<void>((resolve) => {+ completePost = resolve+ })+ }+ jest.mocked(fileSystemList).mockResolvedValue({+ count: 1,+ results: [entry('created', 'Research/Draft.md')],+ })+ return { ...notebook, short_id: 'created' }+ })+ const fs = new PosthogFilesystem('42', new AbortController().signal, confirm, true)+ await fs.load()+ const server = new NinePServer(fs, jest.fn())+ const request = async (type: number, body: NinePWriter): Promise<number> => {+ const response = new NinePReader(+ await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))+ )+ response.number(4)+ return response.number(1)+ }+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string('').number(0, 4))+ await request(110, new NinePWriter().number(1, 4).number(2, 4).number(2, 2).string('files').string('Research'))+ const reply = jest.fn()+ server.handle(+ new NinePWriter().number(2, 4).string('Draft.md').number(1, 4).number(0o644, 4).number(0, 4).frame(14, 77),+ reply+ )+ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1))+ if (phase === 'post') {+ approve(true)+ await waitFor(() => expect(notebooksCreate).toHaveBeenCalledTimes(1))+ }+ expect(await request(108, new NinePWriter().number(77, 2))).toBe(109)+ if (phase === 'confirmation') {+ approve(true)+ } else {+ completePost()+ }+ expect(await request(50, new NinePWriter().number(2, 4).number(0, 4))).toBe(51)+ expect(reply).not.toHaveBeenCalled()+ expect(notebooksCreate).toHaveBeenCalledTimes(phase === 'post' ? 1 : 0)+ const folder = fs.root.children!.get('files')!.children!.get('Research')!+ expect(folder.children!.has('Draft.md')).toBe(phase === 'post')+ expect(fs.writers.size).toBe(0)+ })+it('edits SQL while preserving insight options and exposes editable JSON metadata', async () => {const signal = new AbortController().signaljest.mocked(fileSystemList).mockResolvedValue({diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex e7fdca48fa1b..655cf7ded54c 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -19,7 +19,7 @@ import { cohortsPartialUpdate, cohortsRetrieve } from 'products/cohorts/frontendimport { dashboardsPartialUpdate, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'import { experimentsPartialUpdate, experimentsRetrieve } from 'products/experiments/frontend/generated/api'import { featureFlagsPartialUpdate, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'-import { notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'+import { notebooksCreate, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'import { insightsPartialUpdate, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'import { surveysPartialUpdate, surveysRetrieve } from 'products/surveys/frontend/generated/api'@@ -146,7 +146,11 @@ to approve or cancel; keyboard input cannot approve changes. rm groups its PostHone confirmation. Other programs confirm each removal. Local Linux files do notrequire confirmation. Delete local and PostHog files in separate commands.Removing the last file reference deletes the PostHog object, using your permissions.-Files open for writing must be closed before removal. Use ph notebook-create to create notebooks.+Files open for writing must be closed before removal. Use touch Notes.md or save a+new .md file in an editor to create a blank markdown notebook in the current folder.+Other new file types and editor backup files are not supported under /posthog/files.+Notebook names are not unique across clients. If another client creates the same+name, run ph refresh to see both notebooks with distinct filenames.Work in /tmp for programs that save by renaming a temporary file,then use cat /tmp/edited.md > '/posthog/files/path/to/notebook.md'.@@ -355,6 +359,7 @@ export class PosthogFilesystem extends TerminalFilesystem {private registerDirectory(node: TerminalNode, parts: string[], entry?: FileSystemApi): void {this.projectNodes.set(node, { parts, entry })node.loadChildren = () => this.ensureDirectory(node)+ node.create = (name, signal) => this.createNotebook(node, name, signal)node.mkdir = async (name) => {const directory = this.projectNodes.get(node)if (!directory) {@@ -382,6 +387,67 @@ export class PosthogFilesystem extends TerminalFilesystem {}}+ private async createNotebook(parent: TerminalNode, name: string, signal?: AbortSignal): Promise<TerminalNode> {+ if (signal?.aborted) {+ throw new FilesystemError(4)+ }+ const directory = this.projectNodes.get(parent)+ if (!directory || parent.removed) {+ throw new FilesystemError(116)+ }+ if (!name.endsWith('.md')) {+ throw new FilesystemError(95)+ }+ const title = this.storedName(name)+ if (terminalFilename(title) !== name) {+ throw new FilesystemError(22)+ }+ await this.confirmWrite({+ title: 'Create a PostHog notebook?',+ description: `Create a blank markdown notebook in project ${this.projectId}. This affects everyone in the project.`,+ items: [joinPath([...directory.parts, title])],+ })+ if (signal?.aborted) {+ throw new FilesystemError(4)+ }+ // Finish reconciling approved writes even if the guest cancels after the POST starts.+ const notebook = await notebooksCreate(+ this.projectId,+ {+ title,+ _create_in_folder: joinPath(directory.parts),+ content: {+ type: 'doc',+ content: [+ {+ type: 'ph-markdown-notebook',+ attrs: { nodeId: 'markdown-notebook-v2', markdown: '' },+ },+ ],+ },+ text_content: '',+ },+ { signal: this.signal }+ )+ const params = { type: 'notebook', ref: notebook.short_id, include_content_type: true }+ try {+ const page = await fileSystemList(this.projectId, params, { signal: this.signal })+ const entry = page.results.find((entry) => entry.type === 'notebook' && entry.ref === notebook.short_id)+ if (!entry) {+ throw new Error(+ 'The notebook was created but could not be loaded. Run ph refresh to reload the folder.'+ )+ }+ this.mountEntries([entry], true)+ return this.mountedFiles.get(this.fileIdentity(entry, '.md'))!+ } catch (error) {+ // The notebook exists but is not mounted. Reload the folder on the next lookup so that+ // a retry finds the notebook instead of creating a duplicate.+ this.loadedDirectories.delete(parent)+ throw error+ }+ }+private storedName(name: string): string {try {const decoded = decodeURIComponent(name)diff --git a/frontend/src/scenes/terminal/terminalFilesystem.ts b/frontend/src/scenes/terminal/terminalFilesystem.tsindex 29934f56fccf..b0463ee912f2 100644--- a/frontend/src/scenes/terminal/terminalFilesystem.ts+++ b/frontend/src/scenes/terminal/terminalFilesystem.ts@@ -15,6 +15,7 @@ export interface TerminalNode {writable: booleanwriteKey?: stringmkdir?: (name: string) => Promise<TerminalNode>+ create?: (name: string, signal?: AbortSignal) => Promise<TerminalNode>rename?: (parent: TerminalNode, name: string) => Promise<void>remove?: () => Promise<void>removed?: boolean