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): require pointer confirmation before deleting data (#105299)

Marius Andra20fe63d66a09
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6cbb72c18c10..fa13066d9cf2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11404,6 +11404,10 @@ snapshots:
hash: v1.k794b7964.0647acd4cc4525c6a5f0f5792805408120e874f6092a92db0ecf559725e47646.ve96neC-YTgo1mBSm1W7F7LOcJAz4-F6qUaAiXrjy2E
scenes-app-terminal--default--light:
hash: v1.k794b7964.09ecf1a6454895b4cc8336ea75615e27733a6f0e83e6a195fac566de956d06ba.l93c7xJK2992oHa4ojwl2B886SAirPasa7wWkpDN7L4
+ scenes-app-terminal--delete-confirmation--dark:
+ hash: v1.k794b7964.13b9d8c6669e2bb84c689af7f37e383cbd0129dbb16c8f81265683d5b470f980.6AYk7xKLc2QtwETUCrUbvudsLrkZqYxhQNzeBKcMrNY
+ scenes-app-terminal--delete-confirmation--light:
+ hash: v1.k794b7964.8344095574712f5fbe0cf38abf68c2f6bc4fc063c54d3b26b064f68f108d0335.SGlchg7RaTSCLC4dG7cdhOP8PdWZE9LY9qiNLZv5Emg
scenes-app-terminal--dock-disabled--dark:
hash: v1.k794b7964.403a28973d9199c1f21d005d8e91c1aeeb8d6266d18ba452b1c9404d89c42f9f.xOYN9HKJQanfqMaWQiKm-X9bfiQQJYv7mOAQK-P79nA
scenes-app-terminal--dock-disabled--light:
diff --git a/frontend/src/scenes/terminal/TerminalConfirmationModal.tsx b/frontend/src/scenes/terminal/TerminalConfirmationModal.tsx
new file mode 100644
index 000000000000..ae7b2547e426
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalConfirmationModal.tsx
@@ -0,0 +1,61 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { terminalLogic } from './terminalLogic'
+
+export function TerminalConfirmationModal(): JSX.Element | null {
+ const { confirmation } = useValues(terminalLogic)
+ const { answerConfirmation } = useActions(terminalLogic)
+ if (!confirmation) {
+ return null
+ }
+ return (
+ <LemonModal
+ width={640}
+ overlayClassName="!items-center !bg-black/70"
+ closable={false}
+ forceAbovePopovers
+ title={confirmation.title}
+ className="ph-no-capture ph-replay-block"
+ data-attr="terminal-confirmation"
+ footer={
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="secondary"
+ data-attr="terminal-confirmation-cancel"
+ onClick={(event) => {
+ if (event.detail === 1) {
+ answerConfirmation(confirmation, false)
+ }
+ }}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ status="danger"
+ data-attr="terminal-confirmation-approve"
+ onClick={(event) => {
+ if (event.detail === 1) {
+ answerConfirmation(confirmation, true)
+ }
+ }}
+ >
+ Yes, continue
+ </LemonButton>
+ </div>
+ }
+ >
+ <p>{confirmation.description}</p>
+ <p>The terminal is waiting. Click a button to continue or cancel. Keyboard shortcuts are disabled.</p>
+ <ul className="space-y-2 pl-4" translate="no">
+ {confirmation.items.map((item, index) => (
+ <li key={index} className="whitespace-pre-wrap break-words font-mono text-sm">
+ {item}
+ </li>
+ ))}
+ </ul>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/terminal/TerminalPanel.tsx b/frontend/src/scenes/terminal/TerminalPanel.tsx
index 6c5bf839a6a8..5c3e5bfe117a 100644
--- a/frontend/src/scenes/terminal/TerminalPanel.tsx
+++ b/frontend/src/scenes/terminal/TerminalPanel.tsx
@@ -7,6 +7,7 @@ import { resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { cn } from 'lib/utils/css-classes'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { TerminalConfirmationModal } from './TerminalConfirmationModal'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
import { TerminalView } from './TerminalView'
@@ -50,42 +51,45 @@ export function TerminalPanel(): JSX.Element | null {
return null
}
return (
- <div
- ref={container}
- data-attr="terminal-dock"
- aria-label="Terminal panel"
- className={cn(
- 'fixed inset-x-0 bottom-0 z-[calc(var(--z-scene-layout-content-panel)+1)] border-t bg-surface-primary shadow-lg pt-1 min-h-40 max-h-[80vh]',
- !visible && 'hidden'
- )}
- style={{ height: desiredSize ?? 320 }}
- >
- <Resizer {...resizeProps} />
- <button
- type="button"
- role="separator"
- aria-label="Resize terminal"
- aria-orientation="horizontal"
- aria-valuenow={desiredSize ?? 320}
- aria-valuemin={160}
- aria-valuemax={Math.floor(window.innerHeight * 0.8)}
- className="absolute top-0 left-1/2 w-12 h-1 rounded bg-border cursor-ns-resize focus-visible:ring"
- onKeyDown={(event) => {
- if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
- event.preventDefault()
- setDesiredSize(
- Math.max(
- 160,
- Math.min(
- window.innerHeight * 0.8,
- (desiredSize ?? 320) + (event.key === 'ArrowUp' ? 40 : -40)
+ <>
+ <TerminalConfirmationModal />
+ <div
+ ref={container}
+ data-attr="terminal-dock"
+ aria-label="Terminal panel"
+ className={cn(
+ 'fixed inset-x-0 bottom-0 z-[calc(var(--z-scene-layout-content-panel)+1)] border-t bg-surface-primary shadow-lg pt-1 min-h-40 max-h-[80vh]',
+ !visible && 'hidden'
+ )}
+ style={{ height: desiredSize ?? 320 }}
+ >
+ <Resizer {...resizeProps} />
+ <button
+ type="button"
+ role="separator"
+ aria-label="Resize terminal"
+ aria-orientation="horizontal"
+ aria-valuenow={desiredSize ?? 320}
+ aria-valuemin={160}
+ aria-valuemax={Math.floor(window.innerHeight * 0.8)}
+ className="absolute top-0 left-1/2 w-12 h-1 rounded bg-border cursor-ns-resize focus-visible:ring"
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
+ event.preventDefault()
+ setDesiredSize(
+ Math.max(
+ 160,
+ Math.min(
+ window.innerHeight * 0.8,
+ (desiredSize ?? 320) + (event.key === 'ArrowUp' ? 40 : -40)
+ )
)
)
- )
- }
- }}
- />
- {visible && <TerminalView onClose={() => setDockOpen(false)} />}
- </div>
+ }
+ }}
+ />
+ {visible && <TerminalView onClose={() => setDockOpen(false)} />}
+ </div>
+ </>
)
}
diff --git a/frontend/src/scenes/terminal/TerminalScene.stories.tsx b/frontend/src/scenes/terminal/TerminalScene.stories.tsx
index ad2c2239f6a4..16f4a68f91a2 100644
--- a/frontend/src/scenes/terminal/TerminalScene.stories.tsx
+++ b/frontend/src/scenes/terminal/TerminalScene.stories.tsx
@@ -11,7 +11,7 @@ import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { GlobalShortcuts } from '~/layout/GlobalShortcuts'
import { useStorybookMocks } from '~/mocks/browser'
-import { expect, spyOn, waitFor } from 'storybook/test'
+import { expect, spyOn, userEvent, waitFor } from 'storybook/test'
import { TerminalDock } from './TerminalDock'
import { terminalDockLogic } from './terminalDockLogic'
@@ -330,3 +330,28 @@ export const Narrow: StoryObj<typeof TerminalScene> = {
),
],
}
+
+export const DeleteConfirmation: StoryObj<typeof TerminalScene> = {
+ play: async () => {
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ void terminalLogic.cache.filesystem
+ .confirmOperation({
+ title: 'Delete PostHog files and folders?',
+ description:
+ 'Remove 4 files and folders from project 1. Removing the last file reference also deletes the PostHog object. This affects everyone in the project.',
+ items: [
+ '/posthog/files/Research/Welcome.md (notebook: demonote)',
+ '/posthog/files/Research/Overview.json (dashboard: 101)',
+ '/posthog/files/Research/Signups.json (insight: demoinsight)',
+ '/posthog/files/Research',
+ ],
+ })
+ .catch(() => {})
+ await waitFor(() => expect(document.querySelector('[data-attr="terminal-confirmation"]')).not.toBeNull())
+ const approve = document.querySelector<HTMLButtonElement>('[data-attr="terminal-confirmation-approve"]')!
+ approve.focus()
+ await userEvent.keyboard('{Enter} {Escape}{Tab}')
+ approve.click()
+ expect(document.querySelector('[data-attr="terminal-confirmation"]')).not.toBeNull()
+ },
+}
diff --git a/frontend/src/scenes/terminal/TerminalScene.tsx b/frontend/src/scenes/terminal/TerminalScene.tsx
index 9e4247279816..afbb32c6f585 100644
--- a/frontend/src/scenes/terminal/TerminalScene.tsx
+++ b/frontend/src/scenes/terminal/TerminalScene.tsx
@@ -9,6 +9,7 @@ import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { TerminalConfirmationModal } from './TerminalConfirmationModal'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
import { TerminalView } from './TerminalView'
@@ -16,12 +17,13 @@ import { TerminalView } from './TerminalView'
export const scene: SceneExport = { component: TerminalScene, logic: terminalLogic }
export function TerminalScene(): JSX.Element {
const { receivedFeatureFlags } = useValues(featureFlagLogic)
- const { terminalEnabled } = useValues(terminalDockLogic)
+ const { terminalEnabled, hasOpened } = useValues(terminalDockLogic)
if (receivedFeatureFlags && !terminalEnabled) {
return <NotFound object="page" />
}
return (
<SceneContent className="h-full min-h-0 flex-1 pb-1">
+ {!hasOpened && <TerminalConfirmationModal />}
<SceneTitleSection name="Terminal" resourceType={{ type: 'terminal', forceIcon: <IconTerminal /> }} />
{terminalEnabled && <TerminalView />}
</SceneContent>
diff --git a/frontend/src/scenes/terminal/ninepServer.ts b/frontend/src/scenes/terminal/ninepServer.ts
index 722038afb87b..0aff36bd622c 100644
--- a/frontend/src/scenes/terminal/ninepServer.ts
+++ b/frontend/src/scenes/terminal/ninepServer.ts
@@ -27,7 +27,9 @@ function qid(writer: NinePWriter, node: TerminalNode): NinePWriter {
export class NinePServer {
private fids = new Map<number, Fid>()
- private writers = new Set<string | number>()
+ private get writers(): Set<string | number> {
+ return this.filesystem.writers
+ }
private requests = new Map<number, AbortController>()
private queue: Promise<void> = Promise.resolve()
private messageSize = 256 * 1024
diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.ts
index 9bbe733c0551..3e030a9facfe 100644
--- a/frontend/src/scenes/terminal/posthogCommands.test.ts
+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts
@@ -1,3 +1,5 @@
+import { waitFor } from '@testing-library/react'
+
import { fileSystemList } from '~/generated/core/api'
import type { FileSystemApi } from '~/generated/core/api.schemas'
@@ -35,6 +37,7 @@ jest.mock('products/product_analytics/frontend/generated/api', () => ({
}))
describe('PostHog terminal commands', () => {
+ const confirm = jest.fn(async () => true)
let commands: PosthogCommands
let filesystem: PosthogFilesystem
const navigate = jest.fn()
@@ -46,8 +49,32 @@ describe('PostHog terminal commands', () => {
hedgehog_config: null,
}
+ it.each([
+ ['notebook-delete', 'shortnote'],
+ ['notebook-update', 'shortnote', '--deleted'],
+ ['example/echo', '--text', 'hello'],
+ ])('blocks %s until the user approves its exact arguments', async (...argv) => {
+ let answer!: (approved: boolean) => void
+ confirm.mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ answer = resolve
+ })
+ )
+ const operation = commands.execute(argv, cwd)
+ const outcome = operation.catch((error: Error) => error)
+ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1))
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ expect(mcpServerInstallationsCallToolCreate).not.toHaveBeenCalled()
+ answer(false)
+ await expect(outcome).resolves.toEqual(expect.objectContaining({ message: 'Canceled. No changes made.' }))
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ expect(mcpServerInstallationsCallToolCreate).not.toHaveBeenCalled()
+ })
+
beforeEach(async () => {
jest.clearAllMocks()
+ confirm.mockResolvedValue(true)
jest.mocked(fileSystemList).mockResolvedValue({
count: 1,
next: null,
@@ -122,7 +149,7 @@ describe('PostHog terminal commands', () => {
structured_content: { echoed: true },
})
const signal = new AbortController().signal
- filesystem = new PosthogFilesystem('42', signal)
+ filesystem = new PosthogFilesystem('42', signal, confirm)
await filesystem.load()
commands = new PosthogCommands('42', signal, filesystem, navigate)
})
diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.ts
index 021120b288fb..f83971ff56d0 100644
--- a/frontend/src/scenes/terminal/posthogCommands.ts
+++ b/frontend/src/scenes/terminal/posthogCommands.ts
@@ -17,6 +17,7 @@ import { insightsList, insightsRetrieve } from 'products/product_analytics/front
import { markdownNode, PosthogFilesystem, terminalFilename } from './posthogFilesystem'
import { TerminalCommands } from './terminalCommands'
+import { parseRemovalArguments, RM_SCRIPT } from './terminalRemove'
interface Command {
name: string
@@ -255,6 +256,7 @@ export class PosthogCommands {
this.register(tool)
}
new TerminalCommands(filesystem, (argv, cwd) => this.execute(argv, cwd))
+ filesystem.text('rm', filesystem.directory('bin', filesystem.root), RM_SCRIPT)
}
private register(tool: Command): void {
@@ -364,6 +366,18 @@ export class PosthogCommands {
async execute(argv: string[], cwd: string): Promise<unknown> {
const [name = 'help', ...rest] = argv
+ if (name === 'terminal-remove') {
+ if (rest.length !== 2 || rest[0] !== '--json') {
+ throw new Error('Use rm to delete PostHog files.')
+ }
+ const request = z
+ .object({ argv: z.array(z.string()).max(1000) })
+ .strict()
+ .parse(JSON.parse(rest[1]))
+ const { paths, recursive, force } = parseRemovalArguments(request.argv)
+ await this.filesystem.removePaths(paths, recursive, force)
+ return null
+ }
if (name === 'open') {
if (rest.length > 1) {
throw new Error('Use open with one file or folder path. Quote paths containing spaces.')
@@ -407,7 +421,17 @@ export class PosthogCommands {
const { invoke: _, ...description } = tool
return description
}
- return tool.invoke(await this.parseArguments(tool, rest, cwd))
+ const args = await this.parseArguments(tool, rest, cwd)
+ if (tool.name.includes('/') || tool.name === 'notebooks-destroy' || args.deleted) {
+ await this.filesystem.confirmOperation({
+ title: tool.name.includes('/') ? 'Run a connected tool?' : 'Delete a PostHog object?',
+ description: tool.name.includes('/')
+ ? `Run ${tool.name} from project ${this.projectId}. Connected tools can change or delete data in external services. Review the tool and its arguments before continuing.`
+ : `Run ${tool.name} in project ${this.projectId}. This deletes the specified notebook for everyone in the project.`,
+ items: [tool.description, JSON.stringify(args, null, 2)],
+ })
+ }
+ return tool.invoke(args)
}
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 835475381943..4885757c6cf6 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts
@@ -1,3 +1,5 @@
+import { waitFor } from '@testing-library/react'
+
import apiMutator from 'lib/api-orval-mutator'
import { fileSystemCreate, fileSystemDestroy, fileSystemList, fileSystemRetrieve } from '~/generated/core/api'
@@ -390,16 +392,34 @@ describe('PostHog filesystem projection', () => {
{ ...entry('alias', 'Copy'), ref: 'note1' },
],
})
- const fs = new PosthogFilesystem('42', new AbortController().signal)
+ const fs = new PosthogFilesystem('42', new AbortController().signal, async () => true)
await fs.load()
const files = fs.root.children!.get('files')!
const folder = files.children!.get('Research')!
const note = folder.children!.get('Notes.md')!
await expect(folder.remove!()).rejects.toMatchObject({ errno: 39 })
expect(fileSystemDestroy).not.toHaveBeenCalled()
- jest.mocked(fileSystemDestroy).mockRejectedValueOnce({ status: 403 })
- await expect(note.remove!()).rejects.toMatchObject({ errno: 13 })
+ jest.mocked(fileSystemDestroy).mockRejectedValueOnce(
+ Object.assign(new Error('You do not have permission to delete this file.'), { status: 403 })
+ )
+ await expect(note.remove!()).rejects.toMatchObject({
+ errno: 13,
+ message:
+ 'Could not delete /posthog/files/Research/Notes.md (HTTP 403):\nYou do not have permission to delete this file.\nRun ph refresh to check the remaining files before trying again.',
+ })
expect(fs.resolveReference('Research/Notes.md', '/posthog/files')).toBe('note1')
+ jest.mocked(fileSystemDestroy).mockRejectedValueOnce({ status: 500 })
+ await expect(note.remove!()).rejects.toMatchObject({
+ errno: 5,
+ message: expect.stringContaining('Could not delete /posthog/files/Research/Notes.md (HTTP 500)'),
+ })
+ expect(folder.children!.get('Notes.md')).toBe(note)
+ jest.mocked(fileSystemDestroy).mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ await expect(note.remove!()).rejects.toMatchObject({
+ errno: 5,
+ message: expect.stringContaining('Could not delete /posthog/files/Research/Notes.md:\nFailed to fetch'),
+ })
+ expect(folder.children!.get('Notes.md')).toBe(note)
jest.mocked(fileSystemDestroy).mockResolvedValue(undefined)
await note.remove!()
expect(fileSystemDestroy).toHaveBeenLastCalledWith('42', 'note1', { recursive: false }, expect.anything())
@@ -417,6 +437,78 @@ describe('PostHog filesystem projection', () => {
expect(notebooksRetrieve).not.toHaveBeenCalled()
})
+ it.each([false, true])(
+ 'confirms a recursive snapshot once before any API deletion (approved=%s)',
+ async (approved) => {
+ const entries = [
+ entry('folder', 'Research', 'folder'),
+ entry('note1', 'Research/Notes'),
+ entry('note2', 'Research/More'),
+ ]
+ jest.mocked(fileSystemList).mockImplementation(async (_, params) => {
+ const { parent, depth } = params as { parent?: string; depth?: number }
+ const results = entries.filter(
+ (item) =>
+ item.path.split('/').length === depth && item.path.split('/').slice(0, -1).join('/') === parent
+ )
+ return { count: results.length, results }
+ })
+ let answer!: (approved: boolean) => void
+ const confirm = jest.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ answer = resolve
+ })
+ )
+ const fs = new PosthogFilesystem('42', new AbortController().signal, confirm)
+ const operation = fs.removePaths(['/posthog/files/Research'], true, true)
+ const outcome = operation.catch((error: Error) => error)
+ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1))
+ expect(confirm.mock.calls[0]).toEqual([
+ expect.objectContaining({
+ items: [
+ '/posthog/files/Research/More.md (notebook: note2)',
+ '/posthog/files/Research/Notes.md (notebook: note1)',
+ '/posthog/files/Research',
+ ],
+ }),
+ ])
+ expect(fileSystemDestroy).not.toHaveBeenCalled()
+ answer(approved)
+ if (approved) {
+ await expect(outcome).resolves.toBeUndefined()
+ expect(jest.mocked(fileSystemDestroy).mock.calls.map((call) => call[1])).toEqual([
+ 'note2',
+ 'note1',
+ 'folder',
+ ])
+ } else {
+ await expect(outcome).resolves.toEqual(
+ expect.objectContaining({ message: 'Canceled. No changes made.' })
+ )
+ expect(fileSystemDestroy).not.toHaveBeenCalled()
+ }
+ expect(confirm).toHaveBeenCalledTimes(1)
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['remove', 'json'] as const)('fails closed without a confirmation handler for %s', async (operation) => {
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const node =
+ operation === 'remove'
+ ? fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!
+ : fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!
+ const pending =
+ operation === 'remove'
+ ? node.remove!()
+ : (await node.open!()).save!(new TextEncoder().encode(JSON.stringify({ deleted: true })))
+ await expect(pending).rejects.toThrow('Canceled. No changes made.')
+ expect(fileSystemDestroy).not.toHaveBeenCalled()
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ })
+
it('rejects moves of implicit folders without creating records or changing their contents', async () => {
const fs = new PosthogFilesystem('42', new AbortController().signal)
await fs.load()
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.ts
index cf52b86b5033..84b57430d27c 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts
@@ -22,6 +22,7 @@ import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/a
import { insightsPartialUpdate, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
import { surveysPartialUpdate, surveysRetrieve } from 'products/surveys/frontend/generated/api'
+import { ConfirmTerminalOperation, TerminalConfirmation } from './terminalConfirmation'
import {
FilesystemError,
MAX_TERMINAL_FILE_BYTES,
@@ -127,6 +128,11 @@ inside /posthog/files. Keep .md or .json extensions when renaming files.
Moves preserve object IDs and folder contents. Existing destinations cannot be
replaced. 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.
+Deletes require a blocking confirmation. Click a button to approve or cancel;
+keyboard input cannot approve a deletion. rm groups all its PostHog targets into
+one confirmation. Other programs confirm each removal. Local Linux files do not
+require confirmation. Delete local and PostHog files in separate commands.
+JSON saves that mark an object deleted and connected tools also ask for confirmation.
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.
Work in /tmp for programs that save by renaming a temporary file,
@@ -275,7 +281,8 @@ export class PosthogFilesystem extends TerminalFilesystem {
constructor(
private projectId: string,
- private signal: AbortSignal
+ private signal: AbortSignal,
+ private confirm: ConfirmTerminalOperation = async () => false
) {
super()
this.text('README.txt', this.root, TERMINAL_README)
@@ -330,7 +337,79 @@ export class PosthogFilesystem extends TerminalFilesystem {
return `/posthog/${parts.join('/')}`
}
- private async remove(node: TerminalNode): Promise<void> {
+ async confirmOperation(confirmation: TerminalConfirmation): Promise<void> {
+ if (this.signal.aborted || !(await this.confirm(confirmation)) || this.signal.aborted) {
+ throw new Error('Canceled. No changes made.')
+ }
+ }
+
+ private removalConfirmation(nodes: TerminalNode[]): TerminalConfirmation {
+ return {
+ title: 'Delete PostHog files and folders?',
+ description: `Remove ${nodes.length === 1 ? '1 file or folder' : `${nodes.length} files and folders`} from project ${this.projectId}. Removing the last file reference also deletes the PostHog object. This affects everyone in the project.`,
+ items: nodes.map((node) => {
+ const entry = this.projectNodes.get(node)?.entry
+ return `${this.mountedPath(node)}${entry && entry.type !== 'folder' ? ` (${entry.type}: ${entry.ref})` : ''}`
+ }),
+ }
+ }
+
+ async removePaths(paths: string[], recursive: boolean, force: boolean): Promise<void> {
+ const nodes = new Set<TerminalNode>()
+ const visit = async (node: TerminalNode): Promise<void> => {
+ if (nodes.has(node)) {
+ return
+ }
+ if (!node.remove || this.writers.has(node.writeKey ?? node.id)) {
+ throw new FilesystemError(
+ node.remove ? 16 : 30,
+ `Could not delete ${this.mountedPath(node)}: ${node.remove ? 'Device or resource busy. Close the file before deleting it.' : 'Read-only file system. Choose a writable path.'}`
+ )
+ }
+ if (node.children) {
+ if (!recursive) {
+ throw new FilesystemError(
+ 21,
+ `Could not delete ${this.mountedPath(node)}: Is a directory. Use rm -r to delete folders.`
+ )
+ }
+ await node.loadChildren?.()
+ for (const child of node.children.values()) {
+ await visit(child)
+ }
+ }
+ nodes.add(node)
+ }
+ for (const path of paths) {
+ if (!path.startsWith('/posthog/files/')) {
+ throw new Error(
+ 'Delete local files and PostHog files in separate commands. Use a path inside /posthog/files.'
+ )
+ }
+ let node: TerminalNode | undefined = this.files
+ for (const part of path.slice('/posthog/files/'.length).split('/')) {
+ if (!part || part === '.' || part === '..') {
+ throw new Error('Use a resolved path inside /posthog/files.')
+ }
+ await node?.loadChildren?.()
+ node = node?.children?.get(part)
+ }
+ if (node) {
+ await visit(node)
+ } else if (!force) {
+ throw new FilesystemError(2, `Could not delete ${path}: No such file or directory. Check the path.`)
+ }
+ }
+ if (!nodes.size) {
+ return
+ }
+ await this.confirmOperation(this.removalConfirmation([...nodes]))
+ for (const node of nodes) {
+ await this.remove(node, true)
+ }
+ }
+
+ private async remove(node: TerminalNode, confirmed = false): Promise<void> {
const source = this.projectNodes.get(node)
if (!source || node.removed) {
throw new FilesystemError(116)
@@ -338,12 +417,24 @@ export class PosthogFilesystem extends TerminalFilesystem {
if (node.children?.size) {
throw new FilesystemError(39)
}
+ if (this.writers.has(node.writeKey ?? node.id)) {
+ throw new FilesystemError(16)
+ }
+ if (!confirmed) {
+ await this.confirmOperation(this.removalConfirmation([node]))
+ }
+ if (this.signal.aborted) {
+ throw new FilesystemError(4)
+ }
if (source.entry) {
try {
await fileSystemDestroy(this.projectId, source.entry.id, { recursive: false }, { signal: this.signal })
} catch (error) {
const status = error && typeof error === 'object' && 'status' in error ? error.status : undefined
- throw new FilesystemError(status === 409 ? 39 : status === 403 ? 13 : status === 404 ? 2 : 5)
+ throw new FilesystemError(
+ status === 409 ? 39 : status === 403 ? 13 : status === 404 ? 2 : 5,
+ `Could not delete ${this.mountedPath(node)}${status ? ` (HTTP ${status})` : ''}:\n${error instanceof Error ? error.message : 'API request failed'}\nRun ph refresh to check the remaining files before trying again.`
+ )
}
}
this.references.delete(this.mountedPath(node))
@@ -543,6 +634,13 @@ export class PosthogFilesystem extends TerminalFilesystem {
if (!Object.keys(payload).length) {
return
}
+ if (payload.deleted) {
+ await this.confirmOperation({
+ title: 'Delete a PostHog object?',
+ description: `Save a deletion to ${entry.type} ${entry.ref} in project ${this.projectId}. This affects everyone in the project.`,
+ items: [JSON.stringify(payload, null, 2)],
+ })
+ }
if (entry.type === 'notebook' && 'content' in payload && !('text_content' in payload)) {
const node = markdownNode(payload.content)
if (!node) {
diff --git a/frontend/src/scenes/terminal/terminalConfirmation.ts b/frontend/src/scenes/terminal/terminalConfirmation.ts
new file mode 100644
index 000000000000..cc7c06be399e
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalConfirmation.ts
@@ -0,0 +1,7 @@
+export interface TerminalConfirmation {
+ title: string
+ description: string
+ items: string[]
+}
+
+export type ConfirmTerminalOperation = (confirmation: TerminalConfirmation) => Promise<boolean>
diff --git a/frontend/src/scenes/terminal/terminalFilesystem.ts b/frontend/src/scenes/terminal/terminalFilesystem.ts
index 53bcfe68adf2..29934f56fccf 100644
--- a/frontend/src/scenes/terminal/terminalFilesystem.ts
+++ b/frontend/src/scenes/terminal/terminalFilesystem.ts
@@ -21,8 +21,11 @@ export interface TerminalNode {
}
export class FilesystemError extends Error {
- constructor(readonly errno: number) {
- super(`Filesystem error ${errno}`)
+ constructor(
+ readonly errno: number,
+ message = `Filesystem error ${errno}`
+ ) {
+ super(message)
}
}
@@ -30,6 +33,7 @@ export const MAX_TERMINAL_FILE_BYTES = 4 * 1024 * 1024
export class TerminalFilesystem {
private nextId = 1
+ readonly writers = new Set<string | number>()
readonly root: TerminalNode = this.directory('')
readonly recovery = this.directory('recovery', this.root)
diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.ts
index 94c79bb8d399..da0e6ff32a40 100644
--- a/frontend/src/scenes/terminal/terminalLogic.test.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts
@@ -10,6 +10,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
import { PosthogFilesystem } from './posthogFilesystem'
+import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
import { TerminalRuntime } from './terminalRuntime'
@@ -21,6 +22,7 @@ jest.mock('./terminalRuntime', () => ({
resize: jest.fn(),
syncClock: jest.fn(),
read: jest.fn(() => ''),
+ write: jest.fn(),
})),
}))
jest.mock('./TerminalSession', () => ({
@@ -96,4 +98,41 @@ describe('terminal lifecycle', () => {
expect(document.activeElement).toBe(opener)
opener.remove()
})
+
+ it.each(['cancel', 'stop', 'project', 'unmount', 'approve'] as const)(
+ 'blocks input until a click and settles pending approval on %s',
+ async (finish) => {
+ terminalLogic.actions.attach(document.createElement('div'))
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ const confirm = jest.mocked(PosthogFilesystem).mock.calls[0][2]!
+ const request: TerminalConfirmation = {
+ title: 'Delete?',
+ description: 'Delete a notebook',
+ items: ['note1'],
+ }
+ const pending = confirm(request)
+ await waitFor(() => expect(terminalLogic.values.confirmation).toBe(request))
+ for (const key of ['Enter', ' ', 'Escape', '`']) {
+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
+ document.dispatchEvent(event)
+ expect(event.defaultPrevented).toBe(true)
+ }
+ window.posthogTerminal!.write('rm -rf Research\n')
+ expect(jest.mocked(TerminalRuntime).mock.results[0].value.write).not.toHaveBeenCalled()
+ expect(terminalLogic.values.confirmation).toBe(request)
+ if (finish === 'stop') {
+ terminalLogic.actions.stop()
+ } else if (finish === 'project') {
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 })
+ } else if (finish === 'unmount') {
+ terminalLogic.unmount()
+ } else {
+ terminalLogic.actions.answerConfirmation(request, finish === 'approve')
+ }
+ await expect(pending).resolves.toBe(finish === 'approve')
+ const event = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })
+ document.dispatchEvent(event)
+ expect(event.defaultPrevented).toBe(false)
+ }
+ )
})
diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.ts
index 7d57b4ce0f79..96e56d2cd452 100644
--- a/frontend/src/scenes/terminal/terminalLogic.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.ts
@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { NinePServer } from './ninepServer'
import { PosthogCommands } from './posthogCommands'
import { PosthogFilesystem } from './posthogFilesystem'
+import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
import { TerminalRuntime } from './terminalRuntime'
import { TerminalSession } from './TerminalSession'
@@ -30,6 +31,7 @@ export interface terminalLogicValues {
currentTeamId: number | null // teamLogic
terminalEnabled: boolean // terminalDockLogic
clipboardError: string | null
+ confirmation: TerminalConfirmation | null
error: string | null
hasSelection: boolean
hasStarted: boolean
@@ -44,6 +46,13 @@ export interface terminalLogicActions {
focusTerminal: () => {
value: true
} // terminalDockLogic
+ answerConfirmation: (
+ confirmation: TerminalConfirmation,
+ approved: boolean
+ ) => {
+ approved: boolean
+ confirmation: TerminalConfirmation
+ }
attach: (container: HTMLElement) => {
container: HTMLElement
}
@@ -65,6 +74,9 @@ export interface terminalLogicActions {
setClipboardError: (error: string | null) => {
error: string | null
}
+ setConfirmation: (confirmation: TerminalConfirmation | null) => {
+ confirmation: TerminalConfirmation | null
+ }
setError: (error: string | null) => {
error: string | null
}
@@ -97,6 +109,8 @@ export const terminalLogic = kea<terminalLogicType>([
actions: [terminalDockLogic, ['focusTerminal']],
}),
actions({
+ setConfirmation: (confirmation: TerminalConfirmation | null) => ({ confirmation }),
+ answerConfirmation: (confirmation: TerminalConfirmation, approved: boolean) => ({ confirmation, approved }),
start: true,
attach: (container: HTMLElement) => ({ container }),
detach: (container: HTMLElement) => ({ container }),
@@ -113,6 +127,10 @@ export const terminalLogic = kea<terminalLogicType>([
setSaveError: (error: string | null) => ({ error }),
}),
reducers({
+ confirmation: [
+ null as TerminalConfirmation | null,
+ { setConfirmation: (_, { confirmation }) => confirmation, stop: () => null },
+ ],
hasStarted: [false, { start: () => true }],
runRequested: [false, { start: () => true, stop: () => false }],
hasSelection: [false, { setHasSelection: (_, { selected }) => selected }],
@@ -127,10 +145,15 @@ export const terminalLogic = kea<terminalLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
+ answerConfirmation: ({ confirmation, approved }) => {
+ if (values.confirmation === confirmation) {
+ cache.answerConfirmation?.(approved)
+ }
+ },
attach: ({ container }) => {
if (!cache.session) {
cache.session = new TerminalSession(
- (data) => cache.runtime?.write(data),
+ (data) => !values.confirmation && cache.runtime?.write(data),
(columns, rows) => cache.runtime?.resize(columns, rows),
actions.setHasSelection,
actions.paste
@@ -150,21 +173,27 @@ export const terminalLogic = kea<terminalLogicType>([
}
},
detach: ({ container }) => cache.session?.detach(container),
- focus: () => cache.session?.view.focus(),
+ focus: () => !values.confirmation && cache.session?.view.focus(),
focusTerminal: () => actions.focus(),
insertCommand: ({ command }) => {
+ if (values.confirmation) {
+ return
+ }
cache.session?.view.paste(command)
actions.focus()
},
copy: () => void copyToClipboard(cache.session?.view.getSelection() ?? '', 'terminal selection'),
paste: async () => {
- if (values.pasting) {
+ if (values.pasting || values.confirmation) {
return
}
actions.setPasting(true)
actions.setClipboardError(null)
try {
const text = await navigator.clipboard.readText()
+ if (values.confirmation) {
+ return
+ }
cache.session?.view.paste(text)
actions.focus()
} catch {
@@ -210,6 +239,7 @@ export const terminalLogic = kea<terminalLogicType>([
disposables.add(
() => () => {
controller.abort()
+ disposables.dispose('confirmation')
disposables.dispose('clock-sync')
runtime.dispose()
if (cache.runtime === runtime) {
@@ -223,10 +253,50 @@ export const terminalLogic = kea<terminalLogicType>([
'terminal',
{ pauseOnPageHidden: false }
)
- const agent: TerminalAgent = { write: (data) => runtime.write(data), read: () => runtime.read() }
+ const agent: TerminalAgent = {
+ write: (data) => !values.confirmation && runtime.write(data),
+ read: () => runtime.read(),
+ }
actions.setStatus('loading')
try {
- const filesystem = new PosthogFilesystem(String(projectId), controller.signal)
+ let confirmationQueue = Promise.resolve(false)
+ const filesystem = new PosthogFilesystem(String(projectId), controller.signal, (confirmation) => {
+ const pending = confirmationQueue.then(() => {
+ if (controller.signal.aborted) {
+ return false
+ }
+ return new Promise<boolean>((resolve) => {
+ disposables.add(
+ () => {
+ const blockKeyboard = (event: KeyboardEvent): void => {
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ }
+ for (const type of ['keydown', 'keypress', 'keyup'] as const) {
+ window.addEventListener(type, blockKeyboard, true)
+ }
+ cache.answerConfirmation = (approved: boolean): void => {
+ resolve(approved)
+ disposables.dispose('confirmation')
+ }
+ actions.setConfirmation(confirmation)
+ return () => {
+ resolve(false)
+ cache.answerConfirmation = null
+ actions.setConfirmation(null)
+ for (const type of ['keydown', 'keypress', 'keyup'] as const) {
+ window.removeEventListener(type, blockKeyboard, true)
+ }
+ }
+ },
+ 'confirmation',
+ { pauseOnPageHidden: false }
+ )
+ })
+ })
+ confirmationQueue = pending
+ return pending
+ })
cache.filesystem = filesystem
new PosthogCommands(String(projectId), controller.signal, filesystem, (url) => router.actions.push(url))
actions.setStatus('booting')
diff --git a/frontend/src/scenes/terminal/terminalRemove.test.ts b/frontend/src/scenes/terminal/terminalRemove.test.ts
new file mode 100644
index 000000000000..f9cdb12bc7c3
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalRemove.test.ts
@@ -0,0 +1,73 @@
+import { spawnSync } from 'child_process'
+import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+import { RM_SCRIPT } from './terminalRemove'
+
+describe('terminal rm wrapper', () => {
+ let directory: string
+ let trace: string
+
+ beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'terminal-rm-'))
+ trace = join(directory, 'dispatch')
+ writeFileSync(trace, '')
+ for (const command of ['busybox', 'ph']) {
+ writeFileSync(join(directory, command), '#!/bin/sh\nprintf "%s\\n" "$0" "$@" >> "$TERMINAL_RM_TRACE"\n', {
+ mode: 0o700,
+ })
+ }
+ symlinkSync('/', join(directory, 'root-link'))
+ })
+
+ afterEach(() => {
+ rmSync(directory, { recursive: true, force: true })
+ })
+
+ const run = (argv: string[], cwd = '/'): ReturnType<typeof spawnSync> =>
+ spawnSync('/bin/sh', ['-c', RM_SCRIPT, 'rm', ...argv], {
+ cwd,
+ env: { ...process.env, PATH: `${directory}:${process.env.PATH}`, TERMINAL_RM_TRACE: trace },
+ encoding: 'utf8',
+ })
+
+ it.each(['/', '//', '/./', '/..', '.', '..'])('refuses root target %s before dispatching any removal', (target) => {
+ const result = run(['-rf', '--', join(directory, 'local-file'), target])
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Refusing to remove the filesystem root')
+ expect(readFileSync(trace, 'utf8')).toBe('')
+ })
+
+ it.each(['/posthog', '//posthog', 'posthog', '/posthog/'])(
+ 'refuses the mount target %s instead of dispatching to BusyBox',
+ (target) => {
+ const result = run(['-rf', target])
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Refusing to remove the PostHog mount')
+ expect(readFileSync(trace, 'utf8')).toBe('')
+ }
+ )
+
+ it('resolves a symlinked parent before checking the root', () => {
+ const result = run(['-rf', `${directory}/root-link/.`])
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Refusing to remove the filesystem root')
+ expect(readFileSync(trace, 'utf8')).toBe('')
+ })
+
+ it('does not fall back to BusyBox when an earlier target cannot be resolved', () => {
+ const result = run(['-rf', join(directory, 'missing', 'parent', 'file'), '/'])
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Could not resolve')
+ expect(readFileSync(trace, 'utf8')).toBe('')
+ })
+
+ it('still dispatches local removals with their original arguments', () => {
+ const argv = ['-rf', '--', 'local-file']
+ const result = run(argv, directory)
+ expect(result.status).toBe(0)
+ expect(result.stderr).toBe('')
+ expect(readFileSync(trace, 'utf8').trim().split('\n')).toEqual([join(directory, 'busybox'), 'rm', ...argv])
+ })
+})
diff --git a/frontend/src/scenes/terminal/terminalRemove.ts b/frontend/src/scenes/terminal/terminalRemove.ts
new file mode 100644
index 000000000000..933baaa3bbdf
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalRemove.ts
@@ -0,0 +1,89 @@
+export const RM_SCRIPT = String.raw`#!/bin/sh
+set -eu
+resolve_target() {
+ parent=$(readlink -f -- "$(dirname -- "$1")") || return 1
+ if [ "$parent" = / ]; then parent=''; fi
+ name=$(basename -- "$1")
+ case "$name" in
+ /|.|..) readlink -f -- "$1" ;;
+ *) printf '%s/%s' "$parent" "$name" ;;
+ esac
+}
+mounted=false
+options=true
+for argument in "$@"; do
+ if [ "$options" = true ]; then
+ case "$argument" in
+ --) options=false; continue ;;
+ -?*) continue ;;
+ esac
+ fi
+ target=$(resolve_target "$argument") || {
+ printf 'Could not resolve %s. Check the path before deleting it.\n' "$argument" >&2
+ exit 1
+ }
+ case "$target" in
+ /)
+ printf 'Refusing to remove the filesystem root. Choose a specific file or folder.\n' >&2
+ exit 1
+ ;;
+ /posthog)
+ printf 'Refusing to remove the PostHog mount. Choose a file or folder inside /posthog/files.\n' >&2
+ exit 1
+ ;;
+ /posthog/*) mounted=true ;;
+ esac
+done
+if [ "$mounted" = false ]; then
+ exec busybox rm "$@"
+fi
+arguments=$(
+ options=true
+ for argument in "$@"; do
+ option=false
+ if [ "$options" = true ]; then
+ case "$argument" in
+ --) options=false; option=true ;;
+ -?*) option=true ;;
+ esac
+ fi
+ if [ "$option" = false ]; then
+ argument=$(resolve_target "$argument") || exit 1
+ fi
+ printf '%s' "$argument" | base64 | tr -d '\n'
+ printf '\n'
+ done | jq -Rsc '{argv: (split("\n")[:-1] | map(@base64d))}'
+)
+exec ph terminal-remove --json "$arguments" > /dev/null
+`
+
+export function parseRemovalArguments(argv: string[]): { paths: string[]; recursive: boolean; force: boolean } {
+ const paths: string[] = []
+ let recursive = false
+ let force = false
+ let options = true
+ for (const argument of argv) {
+ if (options && argument === '--') {
+ options = false
+ } else if (options && argument.startsWith('-') && argument !== '-') {
+ if (argument === '--recursive') {
+ recursive = true
+ } else if (argument === '--force') {
+ force = true
+ } else if (/^-[rRf]+$/.test(argument)) {
+ recursive ||= /[rR]/.test(argument)
+ force ||= argument.includes('f')
+ } else {
+ throw new Error(
+ 'For PostHog files, rm supports -r, -R, -f, --recursive, --force, and --. Confirmation is always required.'
+ )
+ }
+ } else {
+ paths.push(argument)
+ }
+ }
+ if (!paths.length && !force) {
+ throw new Error('Specify a file or folder to delete.')
+ }
+ return { paths, recursive, force }
+}
diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.ts
index 018d42cd6934..c9745b93c748 100644
--- a/frontend/src/scenes/terminal/terminalRuntime.ts
+++ b/frontend/src/scenes/terminal/terminalRuntime.ts
@@ -158,6 +158,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',
+ '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',
...Object.values(packageManifest.packages).flatMap((pkg) =>
Object.keys(pkg.commands).map(