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.

feat(terminal): open folders from files menus (#106321)

Marius Andra47948ca6daeb
diff --git a/docs/published/handbook/engineering/project-structure.md b/docs/published/handbook/engineering/project-structure.md
index b4767da13770..9e842f19f980 100644
--- a/docs/published/handbook/engineering/project-structure.md
+++ b/docs/published/handbook/engineering/project-structure.md
@@ -53,6 +53,7 @@ The Starred section's menu opens **Configure starred**, a flat app picker that s
Drag starred items in the sidebar to change their order.
The app-level terminal lives in `src/scenes/terminal`.
+While the terminal is open, folder menus in Files offer **Open in terminal** to change its working directory.
SQL insights appear as editable `.sql` files; their full JSON remains editable under `/posthog/api/insight`.
Saving SQL preserves the insight's other query options, and JSON saves send only changed fields through the existing APIs.
`run report.sql` executes a SQL file in the current project and prints a Markdown table; `--json`, `--csv`, and `--tsv` select export formats.
diff --git a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.test.tsx b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.test.tsx
index 2f13c464e887..2e5a3270bc5f 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.test.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.test.tsx
@@ -1,10 +1,12 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { router } from 'kea-router'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from 'lib/ui/ContextMenu/ContextMenu'
import { DropdownMenu, DropdownMenuContent } from 'lib/ui/DropdownMenu/DropdownMenu'
+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { initKeaTests } from '~/test/init'
@@ -13,6 +15,7 @@ import { MenuItems } from './MenuItems'
describe('MenuItems', () => {
let unmountLogic: () => void
+ let unmountTerminalLogic: () => void
beforeEach(() => {
initKeaTests()
@@ -22,14 +25,74 @@ describe('MenuItems', () => {
jest.spyOn(api.fileSystemShortcuts, 'list').mockResolvedValue({ count: 0, results: [] })
jest.spyOn(api.fileSystem, 'create').mockImplementation(async (item) => ({ ...item, id: 'new-folder' }))
unmountLogic = projectTreeDataLogic.mount()
+ unmountTerminalLogic = terminalDockLogic.mount()
})
afterEach(() => {
cleanup()
unmountLogic()
+ unmountTerminalLogic()
jest.restoreAllMocks()
})
+ it.each([
+ ['project://', 'project://Research/Ideas', "Research/Alice's ideas", undefined, "Research/Alice's ideas"],
+ ['shortcuts://', 'shortcuts://Ideas', 'Ideas', 'Research/Ideas', 'Research/Ideas'],
+ ['project://', 'project-folder-empty/', '', undefined, ''],
+ ])('opens the correct terminal folder from %s %s', async (root, id, path, ref, expectedFolder) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: true })
+ terminalDockLogic.actions.setDockOpen(true)
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuContent>
+ <MenuItems
+ type="dropdown"
+ root={root}
+ item={{ id, name: 'Ideas', record: { path, ref, type: 'folder' } }}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ fireEvent.click(await screen.findByText('Open in terminal'))
+ expect(terminalDockLogic.values.requestedFolder).toBe(expectedFolder)
+ expect(terminalDockLogic.values.dockOpen).toBe(true)
+ })
+
+ it.each([
+ { enabled: true, dockOpen: false, route: '/', type: 'folder', root: 'project://', visible: false },
+ { enabled: false, dockOpen: true, route: '/', type: 'folder', root: 'project://', visible: false },
+ { enabled: true, dockOpen: true, route: '/', type: 'notebook', root: 'project://', visible: false },
+ { enabled: true, dockOpen: true, route: '/', type: 'folder', root: 'products://', visible: false },
+ {
+ enabled: true,
+ dockOpen: false,
+ route: '/project/42/terminal',
+ type: 'folder',
+ root: 'project://',
+ visible: true,
+ },
+ ])(
+ 'shows the folder action only for a visible terminal: %j',
+ async ({ enabled, dockOpen, route, type, root, visible }) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: enabled })
+ terminalDockLogic.actions.setDockOpen(dockOpen)
+ router.actions.push(route)
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuContent>
+ <MenuItems
+ type="dropdown"
+ root={root}
+ item={{ id: `${root}Ideas`, name: 'Ideas', record: { path: 'Ideas', type } }}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ await screen.findByRole('menu')
+ expect(screen.queryByText('Open in terminal') !== null).toBe(visible)
+ }
+ )
+
it.each(['context', 'dropdown'] as const)(
'creates folders and resources in the original starred folder through the %s menu',
async (type) => {
diff --git a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
index 48931680ba75..f5f56977bf4d 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { useState } from 'react'
import {
@@ -8,6 +9,7 @@ import {
IconPencil,
IconShortcut,
IconStar,
+ IconTerminal,
IconTrash,
} from '@posthog/icons'
@@ -32,9 +34,11 @@ import {
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from 'lib/ui/DropdownMenu/DropdownMenu'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { pluralize } from 'lib/utils/strings'
import { openDeleteGroupTypeDialog } from 'scenes/settings/environment/GroupAnalyticsConfig'
import { groupAnalyticsConfigLogic } from 'scenes/settings/environment/groupAnalyticsConfigLogic'
+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { FileSystemEntry } from '~/queries/schema/schema-general'
@@ -77,6 +81,9 @@ export function MenuItems({
const { groupTypes } = useValues(groupAnalyticsConfigLogic)
const { deleteGroupType } = useActions(groupAnalyticsConfigLogic)
const { enabledToolPaths: customProductsSelectedPaths } = useValues(customProductsLogic)
+ const { dockOpen, terminalEnabled } = useValues(terminalDockLogic)
+ const { openInTerminal } = useActions(terminalDockLogic)
+ const { location } = useValues(router)
const projectTreeLogicProps = { key: logicKey ?? uniqueKey, root, isActiveInPanel }
const { checkedItems, checkedItemCountNumeric, checkedItemsArray } = useValues(
@@ -160,6 +167,13 @@ export function MenuItems({
const isItemAFolder = item.record?.type === 'folder'
const isStarredFolder = isItemAFolder && item.id.startsWith('shortcuts://') && !!item.record?.ref
const newMenuItem = isStarredFolder ? { ...item, record: { ...item.record, path: item.record?.ref } } : item
+ const terminalFolder = isStarredFolder ? item.record?.ref : item.record?.path
+ const showOpenInTerminal =
+ terminalEnabled &&
+ (dockOpen || removeProjectIdIfPresent(location.pathname) === '/terminal') &&
+ isItemAFolder &&
+ (root === 'project://' || item.record?.protocol === 'project://' || isStarredFolder) &&
+ typeof terminalFolder === 'string'
const itemShortcutPath = joinPath([splitPath(item.record?.path).pop() ?? 'Unnamed'])
const isItemAlreadyInShortcut = !isItemAFolder && shortcutNonFolderPaths.has(itemShortcutPath)
const shortcutId =
@@ -176,6 +190,24 @@ export function MenuItems({
return (
<>
{productMenu}
+ {showOpenInTerminal && (
+ <>
+ <MenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ openInTerminal(terminalFolder)
+ }}
+ data-attr="tree-item-menu-open-in-terminal-button"
+ >
+ <ButtonPrimitive menuItem>
+ <IconTerminal className="size-4 text-tertiary" />
+ <span>Open in terminal</span>
+ </ButtonPrimitive>
+ </MenuItem>
+ <MenuSeparator />
+ </>
+ )}
{showSelectMenuItems ? (
<>
<MenuItem
diff --git a/frontend/src/scenes/terminal/terminalDockLogic.ts b/frontend/src/scenes/terminal/terminalDockLogic.ts
index 370e365e4da3..46d11fcc4f9a 100644
--- a/frontend/src/scenes/terminal/terminalDockLogic.ts
+++ b/frontend/src/scenes/terminal/terminalDockLogic.ts
@@ -50,6 +50,10 @@ export type terminalDockLogicType = MakeLogicType<
terminalDockLogicMeta
>
+function isTerminalPage(): boolean {
+ return removeProjectIdIfPresent(router.values.location.pathname) === '/terminal'
+}
+
export const terminalDockLogic = kea<terminalDockLogicType>([
path(['scenes', 'terminal', 'terminalDockLogic']),
connect({ values: [featureFlagLogic, ['featureFlags']] }),
@@ -72,13 +76,21 @@ export const terminalDockLogic = kea<terminalDockLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
- openInTerminal: ({ folder }) => {
+ openInTerminal: async ({ folder }, breakpoint) => {
if (!values.terminalEnabled) {
return
}
+ // The full-page terminal hides the dock, so opening it there makes it appear on the next page.
+ if (!values.dockOpen && !isTerminalPage()) {
+ actions.setDockOpen(true)
+ }
+ // Opening the dock follows the current page's folder, so the folder request must come after it.
actions.setRequestedFolder(folder)
- actions.setDockOpen(true)
- actions.focusTerminal()
+ // Menus restore focus to their trigger when they close.
+ await breakpoint(100)
+ if (values.terminalEnabled && (values.dockOpen || isTerminalPage())) {
+ actions.focusTerminal()
+ }
},
toggleTerminal: () => {
if (!values.terminalEnabled) {
diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.ts
index 5a75f6081bd8..07545c205dd5 100644
--- a/frontend/src/scenes/terminal/terminalLogic.test.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts
@@ -20,6 +20,7 @@ import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
import { TerminalRuntime } from './terminalRuntime'
+import { TerminalSession } from './TerminalSession'
const mockFolderFor = jest.fn<Promise<string | null>, []>()
@@ -160,9 +161,19 @@ describe('terminal lifecycle', () => {
expect.any(Function),
'/posthog/files/Research'
)
+ const view = jest.mocked(TerminalSession).mock.results[0].value.view
+ view.focus.mockClear()
terminalDockLogic.actions.openInTerminal('Research/Reports')
await waitFor(() => expect(runtime.changeDirectory).toHaveBeenCalledWith('/posthog/files/Research/Reports'))
+ await waitFor(() => expect(view.focus).toHaveBeenCalled())
expect(TerminalRuntime).toHaveBeenCalledTimes(1)
+ terminalDockLogic.actions.setDockOpen(false)
+ router.actions.push(urls.terminal())
+ view.focus.mockClear()
+ terminalDockLogic.actions.openInTerminal('Research/Notes')
+ await waitFor(() => expect(runtime.changeDirectory).toHaveBeenCalledWith('/posthog/files/Research/Notes'))
+ await waitFor(() => expect(view.focus).toHaveBeenCalled())
+ expect(terminalDockLogic.values.dockOpen).toBe(false)
featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })
terminalDockLogic.actions.openInTerminal('Hidden')
expect(terminalDockLogic.values.dockOpen).toBe(false)
diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.ts
index 72ccdc5edc3d..4836b9f3a463 100644
--- a/frontend/src/scenes/terminal/terminalLogic.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.ts
@@ -317,6 +317,11 @@ export const terminalLogic = kea<terminalLogicType>([
actions.followFolder()
}
},
+ setRequestedFolder: ({ folder }) => {
+ if (folder !== null) {
+ actions.followFolder()
+ }
+ },
answerConfirmation: ({ confirmation, approved }) => {
if (values.confirmation === confirmation) {
cache.answerConfirmation?.(approved)