:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(live-debugger): remove the live debugger product (#109614)
Paul D'Ambra019dfc51092f
diff --git a/frontend/package.json b/frontend/package.jsonindex 3a7f896c250f..163959da5ef1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -118,7 +118,6 @@"@posthog/products-groups": "workspace:*","@posthog/products-growth": "workspace:*","@posthog/products-legal-documents": "workspace:*",- "@posthog/products-live-debugger": "workspace:*","@posthog/products-logs": "workspace:*","@posthog/products-managed-migrations": "workspace:*","@posthog/products-marketing-analytics": "workspace:*",diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsxindex 8a6cdfee9141..151047a36e60 100644--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx@@ -18,7 +18,6 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS,FEATURE_FLAGS.DATA_WAREHOUSE_SCENE,- FEATURE_FLAGS.LIVE_DEBUGGER,FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,FEATURE_FLAGS.PRODUCT_TOURS,],diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex f2f5984a42c1..0ac49de16ec7 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -9,7 +9,6 @@ import {IconBook,IconBrackets,IconBrowser,- IconBug,IconCheckbox,IconCircleDashed,IconClock,@@ -251,10 +250,6 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Filicon: <IconNotebook />,iconColor: ['var(--color-product-notebooks-light)', 'var(--color-product-notebooks-dark)'],},- live_debugger: {- icon: <IconBug />,- iconColor: ['var(--color-product-live-debugger-light)', 'var(--color-product-live-debugger-dark)'],- },action: {icon: <IconPlay />,},diff --git a/frontend/src/layout/panel-layout/sidebarProductMeta.ts b/frontend/src/layout/panel-layout/sidebarProductMeta.tsindex 2bf06f8af745..a3ced4a9bbc6 100644--- a/frontend/src/layout/panel-layout/sidebarProductMeta.ts+++ b/frontend/src/layout/panel-layout/sidebarProductMeta.ts@@ -72,7 +72,6 @@ export const SIDEBAR_PRODUCTS_WITHOUT_DOCS = new Set<string>(['Business knowledge','Engineering analytics','Identity matching',- 'Live Debugger','Product tours','Pulse','Visual review',@@ -111,7 +110,6 @@ const examples: Record<string, string> = {Evaluations: 'Check whether AI responses meet your quality criteria.','Identity matching': 'Review how identities connect across your data.',Inbox: 'Review a report about friction discovered in user sessions.',- 'Live Debugger': 'Inspect the state of running code when a breakpoint fires.',Logs: 'Search application logs around the time an error occurred.','MCP analytics': 'See which tools AI users call and what they are trying to achieve.','MCP servers': 'Find a server that gives your agent the tools it needs.',diff --git a/frontend/src/lib/components/ReleaseStageTag/releaseStage.test.ts b/frontend/src/lib/components/ReleaseStageTag/releaseStage.test.tsindex 445c00a2761c..833c918ca3c5 100644--- a/frontend/src/lib/components/ReleaseStageTag/releaseStage.test.ts+++ b/frontend/src/lib/components/ReleaseStageTag/releaseStage.test.ts@@ -20,7 +20,6 @@ describe('releaseStage', () => {['Inbox', 'Self-driving inbox', 'beta'],['CustomerAnalytics', 'Customer analytics', 'beta'],['CustomerAnalyticsAccount', 'Acme Inc', null],- ['LiveDebugger', 'Live debugger', 'internal'],['Dashboard', 'Dashboard', null],['AIObservability', 'AI observability', null],['AIObservabilityTags', 'Taggers', 'alpha'],diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5391d5e0a079..b7569a732688 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -371,7 +371,6 @@ export const FEATURE_FLAGS = {INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,testJS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-librariesLEGACY_OAUTH_RECONNECT_WARNING: 'legacy-oauth-reconnect-warning', // owner: @jabahamondes #team-web-analytics — kill-switch for the retiring-OAuth-app reconnect banner- LIVE_DEBUGGER: 'live-debugger', // owner: @marcecollLIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analyticsLIVESTREAM_HOGQL: 'livestream-hogql', // owner: @benjackwhite #team-replay, swaps livestream service calls for HogQL queriesLLM_ANALYTICS_CATEGORICAL_EVALS: 'llm-analytics-categorical-evaluations', // owner: #team-ai-observabilitydiff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 52ae3ee61aeb..7fd22b05a13f 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -126,7 +126,6 @@ export const productScenes: Record<string, () => Promise<any>> = {AIEnrichment: () => import('../../products/growth/frontend/aiEnrichment/AIEnrichmentScene'),LegalDocuments: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentsScene'),LegalDocumentNew: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentNewScene'),- LiveDebugger: () => import('../../products/live_debugger/frontend/LiveDebugger'),Logs: () => import('../../products/logs/frontend/LogsScene'),LogsAlertDetail: () => import('../../products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene'),LogsAlertNotificationDetail: () =>diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 30393b066e90..f981766cf230 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -169,13 +169,6 @@"intents": ["marketing_analytics"]},{ "path": "Inbox", "category": "Tools", "iconType": null, "type": null, "intents": [] },- {- "path": "Live Debugger",- "category": "Unreleased",- "iconType": "live_debugger",- "type": "live_debugger",- "intents": ["live_debugger"]- },{ "path": "Logs", "category": "Monitoring", "iconType": null, "type": null, "intents": ["logs"] },{"path": "Marketing analytics",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex a84154bf60b8..153afb0e9c04 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -210,7 +210,6 @@ export const productRoutes: Record<string, [string, string]> = {'/ai-enrichment/:label': ['AIEnrichment', 'aiEnrichment'],'/legal': ['LegalDocuments', 'legalDocuments'],'/legal/new/:type': ['LegalDocumentNew', 'legalDocumentNew'],- '/live-debugger': ['LiveDebugger', 'liveDebugger'],'/logs': ['Logs', 'logs'],'/logs/alerts/:id': ['LogsAlertDetail', 'logsAlertDetail'],'/logs/alerts/:id/notifications/:hogFunctionId': ['LogsAlertNotificationDetail', 'logsAlertNotificationDetail'],@@ -893,11 +892,6 @@ export const productConfiguration: Record<string, any> = {description: 'Generate a Business Associate Agreement or Data Processing Agreement for your organization.',},LegalDocumentNew: { name: 'New legal document', organizationBased: true, activityScope: 'LegalDocument' },- LiveDebugger: {- name: 'Live debugger',- projectBased: true,- description: 'Set breakpoints in your running code and inspect the state captured when they hit.',- },Logs: {projectBased: true,name: 'Logs',@@ -1553,7 +1547,6 @@ export const productUrls = {aiEnrichment: (label?: string): string => `/ai-enrichment${label ? `/${encodeURIComponent(label)}` : ''}`,legalDocuments: (): string => '/legal',legalDocumentNew: (type: 'BAA' | 'DPA'): string => `/legal/new/${type.toLowerCase()}`,- liveDebugger: (): string => '/live-debugger',logs: (): string => '/logs',logsAlertDetail: (id: string, tab?: string): string =>tab ? `/logs/alerts/${id}?tab=${tab}` : `/logs/alerts/${id}`,@@ -1857,14 +1850,6 @@ export const fileSystemTypes = {iconColor: ['var(--color-product-product-analytics-light)'],filterKey: 'insight',},- live_debugger: {- name: 'Live Debugger',- iconType: 'live_debugger',- href: () => urls.liveDebugger(),- iconColor: ['var(--color-product-live-debugger-light)'],- filterKey: 'live_debugger',- flag: FEATURE_FLAGS.LIVE_DEBUGGER,- },notebook: {name: 'Notebook',iconType: 'notebook',@@ -2112,7 +2097,6 @@ export type ProductTreePath =| 'Heatmaps'| 'Identity matching'| 'Inbox'- | 'Live Debugger'| 'LLM analytics'| 'Logs'| 'Marketing analytics'@@ -2557,20 +2541,6 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityCluster',],},- {- path: 'Live Debugger',- displayLabel: 'Live debugger',- intents: [ProductKey.LIVE_DEBUGGER],- sceneKey: 'LiveDebugger',- category: ProductItemCategory.UNRELEASED,- type: 'live_debugger',- href: urls.liveDebugger(),- flag: FEATURE_FLAGS.LIVE_DEBUGGER,- iconType: 'live_debugger',- tags: ['alpha'],- iconColor: ['var(--color-product-live-debugger-light)', 'var(--color-product-live-debugger-dark)'],- sceneKeys: ['LiveDebugger'],- },{path: 'Logs',intents: [ProductKey.LOGS],diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex ad1ee5d27f2f..b99ae1e2143d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -27099,7 +27099,6 @@"data_pipeline_metadata","data_warehouse","task",- "live_debugger","logs","tracing","metrics",@@ -40565,7 +40564,6 @@"history","ingestion_warnings","integrations",- "live_debugger","llm_clusters","llm_datasets","llm_evaluations",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ff222b5f8fdd..8eb31f33b1ba 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5434,7 +5434,6 @@ export type FileSystemIconType =| 'data_pipeline_metadata'| 'data_warehouse'| 'task'- | 'live_debugger'| 'logs'| 'tracing'| 'metrics'@@ -9067,7 +9066,6 @@ export enum ProductKey {HISTORY = 'history',INGESTION_WARNINGS = 'ingestion_warnings',INTEGRATIONS = 'integrations',- LIVE_DEBUGGER = 'live_debugger',LLM_CLUSTERS = 'llm_clusters',LLM_DATASETS = 'llm_datasets',LLM_EVALUATIONS = 'llm_evaluations',diff --git a/frontend/src/scenes/library/libraryUtils.ts b/frontend/src/scenes/library/libraryUtils.tsindex 498bbfe5726b..cfd8df825a73 100644--- a/frontend/src/scenes/library/libraryUtils.ts+++ b/frontend/src/scenes/library/libraryUtils.ts@@ -4,7 +4,7 @@ import { fileSystemTypes, getTreeItemsMetadata, getTreeItemsProducts } from '~/pimport { FileSystemEntry } from '~/queries/schema/schema-general'// These file system types are working pages rather than saved objects, so they belong to Tools.-export const TOOL_FILE_SYSTEM_TYPES = new Set(['endpoints', 'live_debugger', 'task'])+export const TOOL_FILE_SYSTEM_TYPES = new Set(['endpoints', 'task'])// These file system types are views people open and read, so they belong to Views, next to canvases.export const VIEW_FILE_SYSTEM_TYPES = new Set(['dashboard', 'notebook'])diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 36996d9df244..f27ee9d3f164 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -107,7 +107,6 @@ export enum Scene {Views = 'Views',ViewsNew = 'ViewsNew',Tools = 'Tools',- LiveDebugger = 'LiveDebugger',Activity = 'Activity',LiveEvents = 'LiveEvents',Login = 'Login',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex a9767d48c5b8..c4c2c5e32723 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -259,7 +259,6 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {description: 'Real-time events from your app or website.',iconType: 'live',},- [Scene.LiveDebugger]: { projectBased: true, name: 'Live debugger' },[Scene.Login2FA]: { onlyUnauthenticated: true, name: 'Login 2FA', layout: 'plain' },[Scene.Login]: { onlyUnauthenticated: true, layout: 'plain' },[Scene.Max]: { projectBased: true, name: 'Max', layout: 'app-raw-no-header', hideProjectNotice: true },@@ -689,7 +688,6 @@ export const redirects: Record<'/instance/query_performance': urls.experimentsStaffTools(),'/me/settings': urls.settings('user'),'/new': urls.newTab(),- '/live-debugger': urls.liveDebugger(),// Only billing, confirm-creation and create-project have an `/organization*` scene. Every other// path here is guessed or bookmarked, matched no route, and rendered the 404 screen.'/organization': urls.settings('organization'),@@ -924,7 +922,6 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.settings(':section' as any)]: [Scene.Settings, 'settings'],[urls.moveToPostHogCloud()]: [Scene.MoveToPostHogCloud, 'moveToPostHogCloud'],[urls.advancedActivityLogs()]: [Scene.AdvancedActivityLogs, 'advancedActivityLogs'],- [urls.liveDebugger()]: [Scene.LiveDebugger, 'liveDebugger'],[urls.sessionAttributionExplorer()]: [Scene.SessionAttributionExplorer, 'sessionAttributionExplorer'],[urls.coupons(':campaign')]: [Scene.Coupons, 'coupons'],[urls.health()]: [Scene.Health, 'health'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 2fad8f08746c..2bf8c42047d9 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -206,7 +206,6 @@ export const urls = {credentialReview: (): string => '/account/credential-review',cliAuthorize: (): string => '/cli/authorize',cliLive: (): string => '/cli/live',- liveDebugger: (): string => '/live-debugger',passwordReset: (): string => '/reset',passwordResetComplete: (userUuid: string, token: string): string => `/reset/${userUuid}/${token}`,// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point herediff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scssindex 88a33aae76b9..ff81c38a0baa 100644--- a/frontend/src/styles/base.scss+++ b/frontend/src/styles/base.scss@@ -328,7 +328,6 @@--color-product-logs-dark: rgb(240 92 161);--color-product-marketing-analytics-light: rgb(214 37 123);--color-product-marketing-analytics-dark: rgb(240 92 161);- --color-product-live-debugger-light: rgb(76 14 200);--color-product-feature-flags-light: rgb(48 171 198);--color-product-experiments-light: rgb(182 42 217);--color-product-error-tracking-light: rgb(211 148 24);@@ -441,7 +440,6 @@--color-product-identity-matching-dark: rgb(45 212 191);--color-product-managed-viewsets-light: rgb(202 138 4);--color-product-managed-viewsets-dark: rgb(250 204 21);- --color-product-live-debugger-dark: rgb(139 92 246);// Generic brand color assignments// Change these to change the brand colorsdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1727f57fcaa8..d0790248d75a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -755,9 +755,6 @@ importers:'@posthog/products-legal-documents':specifier: workspace:*version: link:../products/legal_documents- '@posthog/products-live-debugger':- specifier: workspace:*- version: link:../products/live_debugger'@posthog/products-logs':specifier: workspace:*version: link:../products/logs@@ -3821,42 +3818,7 @@ importers:products/links: {}- products/live_debugger:- dependencies:- '@posthog/icons':- specifier: 'catalog:'- '@posthog/lemon-ui':- specifier: '*'- version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])- '@types/react':- specifier: 18.3.27- version: 18.3.27- '@types/react-dom':- specifier: 18.3.7- version: 18.3.7(@types/[email protected])- clsx:- specifier: '*'- version: 1.2.1- fuse.js:- specifier: 'catalog:'- version: 7.3.0- kea:- specifier: 'catalog:'- version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])- kea-loaders:- specifier: 'catalog:'- version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))- react:- specifier: 18.3.1- version: 18.3.1- react-dom:- specifier: 18.3.1- version: 18.3.1([email protected])- devDependencies:- kea-test-utils:- specifier: 'catalog:'- version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ products/live_debugger: {}products/llm_analytics: {}diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex d886579a94ec..6d3feb499bc5 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -398,9 +398,7 @@ class CSPMiddleware:# SQL editor all render blob URLs, so they lose their images without it.f"img-src 'self' data: blob: https: {resource_url} https://posthog.com https://www.gravatar.com https://res.cloudinary.com https://platform.slack-edge.com https://raw.githubusercontent.com",frame_ancestors,- # The live debugger's repo browser reads PostHog/posthog from the GitHub API. The path keeps- # the rest of the API, and every other repository, out of reach of injected script.- f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://api.github.com/repos/PostHog/posthog/ https://raw.githubusercontent.com/PostHog/terminal-assets/ {object_storage_source}",+ f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://raw.githubusercontent.com/PostHog/terminal-assets/ {object_storage_source}",# https: lets heatmaps frame a customer's site. 'self' is for the replay player# frame, whose document is same-origin: an http origin does not match https:."frame-src 'self' https:",diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 6373522c8f06..72bce62cf180 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -436,7 +436,6 @@ def _is_request_for_team_secret_token_secured_endpoint(request: Request) -> bool"featureflag-local-evaluation","project_feature_flags-remote-config","project_feature_flags-local-evaluation",- "project_live_debugger_breakpoints-active-breakpoints",})diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 563337e395f9..b7c3a7914b3e 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1393,7 +1393,6 @@ class FileSystemIconType(StrEnum):DATA_PIPELINE_METADATA = "data_pipeline_metadata"DATA_WAREHOUSE = "data_warehouse"TASK = "task"- LIVE_DEBUGGER = "live_debugger"LOGS = "logs"TRACING = "tracing"METRICS = "metrics"@@ -2459,7 +2458,6 @@ class ProductKey(StrEnum):HISTORY = "history"INGESTION_WARNINGS = "ingestion_warnings"INTEGRATIONS = "integrations"- LIVE_DEBUGGER = "live_debugger"LLM_CLUSTERS = "llm_clusters"LLM_DATASETS = "llm_datasets"LLM_EVALUATIONS = "llm_evaluations"diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 280c5d8433be..7a7601e9b9be 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -82,7 +82,7 @@ APIScopeObject = Literal["internal_run","legal_document","link", # Endpoints are gone; kept advertised until desktop OAuth clients stop requesting it.- "live_debugger",+ "live_debugger", # Endpoints are gone; kept advertised until desktop OAuth clients stop requesting it."llm_analytics","ai_observability_clusters","llm_gateway",diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 0a49f301202e..9807709dc9a4 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -136,7 +136,6 @@1 products/growth/backend/temporal/signup_enrichment/workflow.py1 products/growth/dags/product_push_campaigns.py1 products/growth/dags/team_production_event_activation.py-1 products/live_debugger/backend/models.py1 products/logs/backend/anomaly_scan.py1 products/managed_warehouse/backend/cp_teams.py1 products/marketing_analytics/backend/demo/warehouse.pydiff --git a/products/live_debugger/README.md b/products/live_debugger/README.mddeleted file mode 100644index ed492ee8f28b..000000000000--- a/products/live_debugger/README.md+++ /dev/null@@ -1,62 +0,0 @@-# Live Debugger--Live Debugger provides runtime inspection capabilities for PostHog users by enabling breakpoints in production code. When a breakpoint is hit, the system captures local variables, stack traces, and execution context without interrupting the running application.--## Related Projects--- [https://github.com/PostHog/hogtrace](hogtrace), a DTrace-inspired language for defining- instrumentation scripts. It includes a Rust-based VM that can evaluate expressions within- the context of the client application safely.-- [https://github.com/PostHog/libdebugger](libdebugger), a library for runtime instrumentation- of Python code.--## Flow--```text- PostHog UI User Application- ───────────── ────────────────- │ │- │ (1) Create breakpoint │- ▼ │- ┌─────────┐ │- │ Postgres│ │- └─────────┘ │- │ │- │ (2) Fetch active breakpoints │- │ (Project API key) │- └─────────────────────────────────────────────────►│- │- │ (3) Breakpoint hit- │ Capture state- │- │ (4) Send event- ┌───────────┐ │ $data_breakpoint_hit- │ ClickHouse│ ◄─────────────────────────────────────────┘- └───────────┘- │- │ (5) Query hits (HogQL)- ▼- PostHog UI-```--## Architecture--The system consists of three components working together. The backend stores breakpoint definitions in PostgreSQL, associating each breakpoint with a team, repository, file, and line number. When instrumented code executes, it sends breakpoint hit events to PostHog that are stored in ClickHouse for efficient querying. The frontend provides a GitHub repository browser where users can navigate source files, set breakpoints, and inspect captured runtime state.--Applications poll the external API using a Project API key to fetch active breakpoints for their repository. When code execution reaches a breakpoint line, the instrumentation layer captures the current state and sends it as a PostHog event. The system supports conditional breakpoints through optional Python expressions that determine whether to capture state at a given location.--## API Endpoints--The product exposes two primary endpoints. The `/api/environments/:team_id/live_debugger_breakpoints/` endpoint handles breakpoint management operations through standard CRUD methods. The `/api/environments/:team_id/live_debugger_breakpoints/active/` endpoint allows external applications to fetch enabled breakpoints using Project API key authentication, returning breakpoint configurations that applications use to instrument their code at runtime.--The `/api/environments/:team_id/live_debugger_breakpoints/breakpoint_hits/` endpoint queries ClickHouse for captured runtime state, retrieving events from the last hour with support for filtering by specific breakpoint and pagination. Each hit contains the captured variables, stack trace, timestamp, and execution context.--## Data Model--Breakpoints are identified by the combination of team, repository, filename, and line number. Each breakpoint can be enabled or disabled and may include a condition expression. Breakpoint hits are stored as PostHog events with the event name `$data_breakpoint_hit` containing properties for the breakpoint ID, file path, line number, function name, local variables, and stack trace.--The system enforces team isolation at both the database and API levels. Breakpoint queries automatically filter by team ID, and attempts to access breakpoints from other teams return 404 responses to prevent information disclosure.--## Security Considerations--The external API uses Project API key authentication to allow runtime applications to fetch breakpoints without requiring user credentials. This enables server-side applications, background workers, and other headless processes to participate in debugging sessions. The API validates that breakpoint IDs belong to the requesting team before returning hit data, preventing cross-team data access through breakpoint ID enumeration.diff --git a/products/live_debugger/backend/api.py b/products/live_debugger/backend/api.pydeleted file mode 100644index d52f4247759b..000000000000--- a/products/live_debugger/backend/api.py+++ /dev/null@@ -1,316 +0,0 @@-from django.db.models import QuerySet--from django_filters.rest_framework import DjangoFilterBackend, FilterSet-from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema-from rest_framework import serializers, viewsets-from rest_framework.request import Request-from rest_framework.response import Response--from posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.utils import action-from posthog.auth import SessionAuthentication, TeamSecretTokenAuthentication-from posthog.permissions import TeamSecretTokenPermission--from products.live_debugger.backend.models import LiveDebuggerBreakpoint---class LiveDebuggerBreakpointSerializer(serializers.ModelSerializer):- class Meta:- model = LiveDebuggerBreakpoint- fields = [- "id",- "repository",- "filename",- "line_number",- "enabled",- "condition",- "created_at",- "updated_at",- ]- read_only_fields = ["id", "created_at", "updated_at"]-- def create(self, validated_data: dict) -> LiveDebuggerBreakpoint:- validated_data["team"] = self.context["team"]- return super().create(validated_data)---class BreakpointHitsRequestSerializer(serializers.Serializer):- breakpoint_ids = serializers.ListField(- child=serializers.UUIDField(),- required=False,- help_text="Filter hits for specific breakpoints (use multiple breakpoint_ids params, e.g., ?breakpoint_ids=uuid1&breakpoint_ids=uuid2)",- )- limit = serializers.IntegerField(- required=False,- default=100,- min_value=1,- max_value=1000,- help_text="Number of hits to return (max 1000)",- )- offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Pagination offset")---class ActiveBreakpointsRequestSerializer(serializers.Serializer):- repository = serializers.CharField(- required=False, help_text="Filter breakpoints for specific repository (e.g., 'PostHog/posthog')"- )- filename = serializers.CharField(required=False, help_text="Filter breakpoints for specific file")- enabled = serializers.BooleanField(required=False, default=True, help_text="Only return enabled breakpoints")---class BreakpointHitSerializer(serializers.Serializer):- """Schema for a single breakpoint hit event"""-- id = serializers.UUIDField(help_text="Unique identifier for the hit event")- lineNumber = serializers.IntegerField(help_text="Line number where the breakpoint was hit")- functionName = serializers.CharField(help_text="Name of the function where breakpoint was hit")- timestamp = serializers.DateTimeField(help_text="When the breakpoint was hit")- variables = serializers.DictField(help_text="Local variables at the time of the hit")- stackTrace = serializers.ListField(help_text="Stack trace at the time of the hit")- breakpoint_id = serializers.UUIDField(help_text="ID of the breakpoint that was hit")- filename = serializers.CharField(help_text="Filename where the breakpoint was hit")---class BreakpointHitsResponseSerializer(serializers.Serializer):- """Response schema for breakpoint hits endpoint"""-- results = serializers.ListField(child=BreakpointHitSerializer(), help_text="List of breakpoint hit events")- count = serializers.IntegerField(help_text="Number of results returned")- has_more = serializers.BooleanField(help_text="Whether there are more results available")---class ActiveBreakpointSerializer(serializers.Serializer):- """Schema for a single active breakpoint"""-- id = serializers.UUIDField(help_text="Unique identifier for the breakpoint")- repository = serializers.CharField(- required=False, allow_null=True, help_text="Repository identifier (e.g., 'PostHog/posthog')"- )- filename = serializers.CharField(help_text="File path where the breakpoint is set")- line_number = serializers.IntegerField(help_text="Line number of the breakpoint")- enabled = serializers.BooleanField(help_text="Whether the breakpoint is enabled")- condition = serializers.CharField(- required=False, allow_null=True, help_text="Optional condition for the breakpoint"- )---class ActiveBreakpointsResponseSerializer(serializers.Serializer):- """Response schema for active breakpoints endpoint"""-- breakpoints = serializers.ListField(child=ActiveBreakpointSerializer(), help_text="List of active breakpoints")---class LiveDebuggerBreakpointFilterSet(FilterSet):- class Meta:- model = LiveDebuggerBreakpoint- fields = ["repository", "filename"]---class LiveDebuggerBreakpointViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):- """- Create, Read, Update and Delete breakpoints for live debugging.- """-- scope_object = "live_debugger"- scope_object_read_actions = ["list", "retrieve", "active_breakpoints", "breakpoint_hits"]- scope_object_write_actions = ["create", "update", "partial_update", "destroy"]- queryset = LiveDebuggerBreakpoint.objects.all()- serializer_class = LiveDebuggerBreakpointSerializer- basename = "live_debugger_breakpoints"- filter_backends = [DjangoFilterBackend]- filterset_class = LiveDebuggerBreakpointFilterSet-- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:- return queryset.order_by("-created_at")-- def get_serializer_context(self) -> dict:- context = super().get_serializer_context()- context["team"] = self.team- return context-- @extend_schema(- summary="Get breakpoint hits",- description=(- "Retrieve breakpoint hit events from ClickHouse with optional filtering and pagination. "- "Returns hit events containing stack traces, local variables, and execution context from your application's runtime. "- "\n\nSecurity: Breakpoint IDs are filtered to only include those belonging to the current team."- ),- parameters=[- OpenApiParameter(- "breakpoint_ids",- OpenApiTypes.STR,- description="Filter hits for specific breakpoints (repeat parameter for multiple IDs, e.g., ?breakpoint_ids=uuid1&breakpoint_ids=uuid2)",- required=False,- ),- OpenApiParameter(- "limit",- OpenApiTypes.INT,- description="Number of hits to return (default: 100, max: 1000)",- required=False,- ),- OpenApiParameter(- "offset",- OpenApiTypes.INT,- description="Pagination offset for retrieving additional results (default: 0)",- required=False,- ),- ],- responses={- 200: OpenApiResponse(- response=BreakpointHitsResponseSerializer,- description="List of breakpoint hits with pagination info",- ),- 400: OpenApiResponse(description="Invalid query parameters (invalid UUID, limit out of range, etc.)"),- },- )- @action(methods=["GET"], detail=False)- def breakpoint_hits(self, request: Request, *args, **kwargs) -> Response:- """- Get breakpoint hit events from ClickHouse.-- Query parameters:- - breakpoint_ids (optional): Filter hits for specific breakpoints (repeat parameter for multiple, e.g., ?breakpoint_ids=uuid1&breakpoint_ids=uuid2)- - limit (default: 100): Number of hits to return- - offset (default: 0): Pagination offset- """- param_serializer = BreakpointHitsRequestSerializer(data=request.query_params)- param_serializer.is_valid(raise_exception=True)- params = param_serializer.validated_data-- breakpoint_ids = params.get("breakpoint_ids")- limit = params["limit"]- offset = params["offset"]-- # Filter to only breakpoints that exist and belong to this team- if breakpoint_ids:- breakpoint_ids = list(- LiveDebuggerBreakpoint.objects.filter(id__in=breakpoint_ids, team=self.team).values_list(- "id", flat=True- )- )-- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(- team=self.team, breakpoint_ids=breakpoint_ids, limit=limit, offset=offset- )-- return Response(- {- "results": [hit.to_json() for hit in hits],- "count": len(hits),- "has_more": len(hits) == limit,- }- )-- @extend_schema(- summary="Get active breakpoints (External API)",- description=(- "External API endpoint for client applications to fetch active breakpoints using Project API key. "- "This endpoint allows external client applications (like Python scripts, Node.js apps, etc.) "- "to fetch the list of active breakpoints so they can instrument their code accordingly. "- "\n\nAuthentication: Requires a Project API Key in the Authorization header: "- "`Authorization: Bearer phs_<your-project-api-key>`. "- "You can find your Project API Key in PostHog at: Settings → Project → Project API Key"- ),- parameters=[- OpenApiParameter(- "repository",- OpenApiTypes.STR,- description="Filter breakpoints for a specific repository (e.g., 'PostHog/posthog')",- required=False,- ),- OpenApiParameter(- "filename",- OpenApiTypes.STR,- description="Filter breakpoints for a specific file",- required=False,- ),- OpenApiParameter(- "enabled",- OpenApiTypes.BOOL,- description="Only return enabled breakpoints",- required=False,- ),- ],- responses={- 200: OpenApiResponse(- response=ActiveBreakpointsResponseSerializer,- description="List of breakpoints for client consumption",- ),- 400: OpenApiResponse(description="Invalid query parameters"),- 401: OpenApiResponse(description="Invalid or missing Project API key"),- },- )- @action(- methods=["GET"],- detail=False,- authentication_classes=[- TeamSecretTokenAuthentication,- SessionAuthentication,- ],- required_scopes=["live_debugger:read"],- permission_classes=[TeamSecretTokenPermission],- url_path="active",- )- def active_breakpoints(self, request: Request, *args, **kwargs) -> Response:- """- External API endpoint for client applications to fetch active breakpoints using Project API key.-- This endpoint allows external client applications (like Python scripts, Node.js apps, etc.)- to fetch the list of active breakpoints so they can instrument their code accordingly.-- Authentication: Requires a Project API Key in the Authorization header:- Authorization: Bearer phs_<your-project-api-key>-- You can find your Project API Key in PostHog at: Settings → Project → Project API Key-- Query parameters:- - repository (optional): Filter breakpoints for specific repository (e.g., 'PostHog/posthog')- - filename (optional): Filter breakpoints for specific file- - enabled (default: true): Only return enabled breakpoints-- Response format:- {- "results": [- {- "id": "uuid",- "repository": "PostHog/posthog",- "filename": "capture_event.py",- "line_number": 123,- "enabled": true,- "condition": "user_id == '12345'" // optional- }- ],- "count": 1,- "has_more": false- }- """- param_serializer = ActiveBreakpointsRequestSerializer(data=request.query_params)- param_serializer.is_valid(raise_exception=True)- params = param_serializer.validated_data-- enabled_filter = params["enabled"]- repository = params.get("repository")- filename = params.get("filename")-- queryset = self.get_queryset()-- if enabled_filter:- queryset = queryset.filter(enabled=True)-- if repository:- queryset = queryset.filter(repository=repository)-- if filename:- queryset = queryset.filter(filename=filename)-- breakpoints = queryset.values("id", "repository", "filename", "line_number", "enabled", "condition")- breakpoints_list = list(breakpoints)-- return Response(- {- "results": breakpoints_list,- "count": len(breakpoints_list),- "has_more": False,- }- )diff --git a/products/live_debugger/backend/clickhouse/__init__.py b/products/live_debugger/backend/clickhouse/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/live_debugger/backend/models.py b/products/live_debugger/backend/models.pyindex fe580908f988..63adeb1b7a12 100644--- a/products/live_debugger/backend/models.py+++ b/products/live_debugger/backend/models.py@@ -1,49 +1,12 @@-import logging-from dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Optional-from django.db import modelsfrom posthog.models.utils import UUIDModel-if TYPE_CHECKING:- from posthog.models import Team--logger = logging.getLogger(__name__)---@dataclass-class BreakpointHit:- """- Represents a single breakpoint hit event.- """-- id: str- timestamp: str- breakpoint_id: str- line_number: Optional[int]- filename: str- function_name: str- locals: dict[str, Any]- stack_trace: list[dict[str, Any]]-- def to_json(self) -> dict[str, Any]:- """- Convert the breakpoint hit to JSON format with camelCase keys for the API.- """- return {- "id": self.id,- "lineNumber": self.line_number,- "functionName": self.function_name,- "timestamp": self.timestamp,- "variables": self.locals,- "stackTrace": self.stack_trace,- "breakpoint_id": self.breakpoint_id,- "filename": self.filename,- }-class LiveDebuggerBreakpoint(UUIDModel):+ """The live debugger product is retired. The model stays so that Django keeps cascading team+ deletes into its table. A later migration removes the model and drops the table."""+team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")repository = models.TextField(null=True, blank=True) # Format: "owner/repo" (e.g., "PostHog/posthog")filename = models.TextField()@@ -65,100 +28,3 @@ class LiveDebuggerBreakpoint(UUIDModel):indexes = [models.Index(fields=["team_id", "repository"], name="live_debug_team_repo_idx"),]-- def __str__(self) -> str:- repo_str = f"{self.repository}/" if self.repository else ""- return f"Breakpoint at {repo_str}{self.filename}:{self.line_number} for team {self.team.pk}"-- @classmethod- def get_breakpoint_hits(- cls,- team: "Team",- breakpoint_ids: Optional[list] = None,- limit: int = 100,- offset: int = 0,- ) -> list[BreakpointHit]:- """- Query ClickHouse for breakpoint hit events using HogQL.-- Returns a list of BreakpointHit dataclass instances.- """- from posthog.hogql import ast- from posthog.hogql.parser import parse_select- from posthog.hogql.query import execute_hogql_query-- # Build WHERE conditions (team_id filter is automatically added by execute_hogql_query)- where_conditions = [- "event = {event_name}",- "timestamp >= now() - INTERVAL 1 HOUR",- ]-- placeholders: dict[str, ast.Expr] = {- "event_name": ast.Constant(value="$data_breakpoint_hit"),- "limit": ast.Constant(value=limit),- "offset": ast.Constant(value=offset),- }-- if breakpoint_ids:- # Convert UUIDs to strings for the IN clause- breakpoint_id_strings = [str(bp_id) for bp_id in breakpoint_ids]- where_conditions.append("JSONExtractString(properties, '$breakpoint_id') IN {breakpoint_ids}")- placeholders["breakpoint_ids"] = ast.Constant(value=breakpoint_id_strings)-- where_clause = " AND ".join(where_conditions)-- query = parse_select(- f"""- SELECT- uuid,- timestamp,- properties.$breakpoint_id as breakpoint_id,- properties.$line_number as line_number,- properties.$file_path as filename,- arrayElement(JSONExtractArrayRaw(properties, '$stack_trace'), 1) as stack_first,- properties.$locals_variables as locals,- properties.$stack_trace as stack_trace,- properties- FROM events- WHERE {where_clause}- ORDER BY timestamp DESC- LIMIT {{limit}} OFFSET {{offset}}- """,- placeholders=placeholders,- )-- logger.info(f"Executing breakpoint hits query for team_id={team.pk}, limit={limit}, offset={offset}")- response = execute_hogql_query(query, team=team)- results = response.results or []- logger.info(f"Query returned {len(results)} results")-- # Process results to return structured data- processed_results = []- import json-- for row in results:- try:- # Extract function name from first stack trace element- stack_first = json.loads(row[5]) if row[5] else {}- function_name = stack_first.get("function", "") if isinstance(stack_first, dict) else ""-- locals_data = json.loads(row[6]) if row[6] else {}- stack_trace_data = json.loads(row[7]) if row[7] else []-- processed_results.append(- BreakpointHit(- id=str(row[0]),- timestamp=row[1].isoformat(),- breakpoint_id=row[2],- line_number=int(row[3]) if row[3] else None,- filename=row[4],- function_name=function_name,- locals=locals_data,- stack_trace=stack_trace_data,- )- )- except (json.JSONDecodeError, TypeError, ValueError):- # Skip malformed entries- continue-- return processed_resultsdiff --git a/products/live_debugger/backend/routes.py b/products/live_debugger/backend/routes.pydeleted file mode 100644index c4024be13847..000000000000--- a/products/live_debugger/backend/routes.py+++ /dev/null@@ -1,12 +0,0 @@-from posthog.api.routing import RouterRegistry--from products.live_debugger.backend.api import LiveDebuggerBreakpointViewSet---def register_routes(routers: RouterRegistry) -> None:- routers.projects.register(- r"live_debugger_breakpoints",- LiveDebuggerBreakpointViewSet,- "project_live_debugger_breakpoints",- ["project_id"],- )diff --git a/products/live_debugger/backend/test_api.py b/products/live_debugger/backend/test_api.pydeleted file mode 100644index 26dc798ec07a..000000000000--- a/products/live_debugger/backend/test_api.py+++ /dev/null@@ -1,948 +0,0 @@-from posthog.test.base import APIBaseTest--from rest_framework import status--from products.live_debugger.backend.models import LiveDebuggerBreakpoint---class TestLiveDebuggerBreakpointAPI(APIBaseTest):- def test_create_breakpoint(self):- data = {- "repository": "PostHog/posthog",- "filename": "capture_event.py",- "line_number": 123,- "enabled": True,- "condition": "user_id == '12345'",- }- response = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data,- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertEqual(response.json()["repository"], data["repository"])- self.assertEqual(response.json()["filename"], data["filename"])- self.assertEqual(response.json()["line_number"], data["line_number"])- self.assertEqual(response.json()["enabled"], data["enabled"])- self.assertEqual(response.json()["condition"], data["condition"])-- def test_create_breakpoint_without_condition(self):- data = {- "repository": "PostHog/posthog",- "filename": "capture_event.py",- "line_number": 456,- "enabled": True,- }- response = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data,- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertEqual(response.json()["repository"], data["repository"])- self.assertEqual(response.json()["filename"], data["filename"])- self.assertIsNone(response.json()["condition"])-- def test_create_breakpoint_duplicate_same_repo_fails(self):- """Test that creating duplicate breakpoint in same repo fails due to unique constraint"""- from django.db import transaction-- data = {- "repository": "PostHog/posthog",- "filename": "test.py",- "line_number": 100,- "enabled": True,- }- response1 = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data,- )- self.assertEqual(response1.status_code, status.HTTP_201_CREATED)-- with transaction.atomic():- response2 = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data,- )- self.assertNotEqual(response2.status_code, status.HTTP_201_CREATED)-- self.assertEqual(- LiveDebuggerBreakpoint.objects.filter(- team=self.team,- repository=data["repository"],- filename=data["filename"],- line_number=data["line_number"], # type: ignore- ).count(),- 1,- )-- def test_create_breakpoint_same_file_different_repo_succeeds(self):- """Test that same filename/line can exist in different repositories"""- data1 = {- "repository": "PostHog/posthog",- "filename": "test.py",- "line_number": 100,- "enabled": True,- }- data2 = {- "repository": "PostHog/frontend",- "filename": "test.py",- "line_number": 100,- "enabled": True,- }-- response1 = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data1,- )- self.assertEqual(response1.status_code, status.HTTP_201_CREATED)-- response2 = self.client.post(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/",- data=data2,- )- self.assertEqual(response2.status_code, status.HTTP_201_CREATED)-- breakpoints = LiveDebuggerBreakpoint.objects.filter(team=self.team)- self.assertEqual(breakpoints.count(), 2)-- def test_list_breakpoints(self):- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file2.py",- line_number=200,- enabled=False,- )-- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.json()["results"]), 2)-- def test_list_breakpoints_filter_by_repository(self):- """Test filtering breakpoints by repository"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/frontend",- filename="file2.py",- line_number=200,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file3.py",- line_number=300,- enabled=True,- )-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/?repository=PostHog/posthog"- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 2)- self.assertTrue(all(bp["repository"] == "PostHog/posthog" for bp in results))-- def test_list_breakpoints_filter_by_filename(self):- """Test filtering breakpoints by filename"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/frontend",- filename="file1.py",- line_number=200,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file2.py",- line_number=300,- enabled=True,- )-- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/?filename=file1.py")- self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 2)- self.assertTrue(all(bp["filename"] == "file1.py" for bp in results))-- def test_list_breakpoints_filter_by_repository_and_filename(self):- """Test filtering breakpoints by both repository and filename"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/frontend",- filename="file1.py",- line_number=200,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file2.py",- line_number=300,- enabled=True,- )-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/?repository=PostHog/posthog&filename=file1.py"- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 1)- self.assertEqual(results[0]["repository"], "PostHog/posthog")- self.assertEqual(results[0]["filename"], "file1.py")- self.assertEqual(results[0]["line_number"], 100)-- def test_retrieve_breakpoint(self):- breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=50,- enabled=True,- condition="x > 10",- )-- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/{breakpoint.id}/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["filename"], breakpoint.filename)- self.assertEqual(response.json()["line_number"], breakpoint.line_number)- self.assertEqual(response.json()["condition"], breakpoint.condition)-- def test_update_breakpoint(self):- breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=50,- enabled=True,- )-- update_data = {- "enabled": False,- "condition": "y < 5",- }- response = self.client.patch(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/{breakpoint.id}/",- data=update_data,- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["enabled"], False)- self.assertEqual(response.json()["condition"], "y < 5")-- breakpoint.refresh_from_db()- self.assertEqual(breakpoint.enabled, False)- self.assertEqual(breakpoint.condition, "y < 5")-- def test_delete_breakpoint(self):- breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=50,- enabled=True,- )-- response = self.client.delete(f"/api/projects/{self.team.id}/live_debugger_breakpoints/{breakpoint.id}/")- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)-- self.assertFalse(LiveDebuggerBreakpoint.objects.filter(id=breakpoint.id).exists())-- def test_active_breakpoints_endpoint(self):- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="enabled.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="disabled.py",- line_number=200,- enabled=False,- )-- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- data = response.json()- self.assertEqual(data["count"], 1)- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]- self.assertEqual(len(breakpoints), 1)- self.assertEqual(breakpoints[0]["filename"], "enabled.py")- self.assertEqual(breakpoints[0]["line_number"], 100)-- def test_active_breakpoints_filter_by_filename(self):- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file2.py",- line_number=200,- enabled=True,- )-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/",- {"filename": "file1.py"},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- data = response.json()- self.assertEqual(data["count"], 1)- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]- self.assertEqual(len(breakpoints), 1)- self.assertEqual(breakpoints[0]["filename"], "file1.py")-- def test_active_breakpoints_filter_by_repository(self):- """Test filtering active breakpoints by repository"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="file1.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/frontend",- filename="file2.py",- line_number=200,- enabled=True,- )-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/",- {"repository": "PostHog/posthog"},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- data = response.json()- self.assertEqual(data["count"], 1)- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]- self.assertEqual(len(breakpoints), 1)- self.assertEqual(breakpoints[0]["repository"], "PostHog/posthog")- self.assertEqual(breakpoints[0]["filename"], "file1.py")-- def test_active_breakpoints_include_disabled(self):- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="enabled.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="disabled.py",- line_number=200,- enabled=False,- )-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/",- {"enabled": "false"},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Should return both enabled and disabled- data = response.json()- self.assertEqual(data["count"], 2)- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]- self.assertEqual(len(breakpoints), 2)-- def test_cannot_access_other_team_breakpoints(self):- # Create a breakpoint for a different team- other_team = self.organization.teams.create(name="Other Team")- other_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="secret.py",- line_number=999,- enabled=True,- )-- # Try to access it- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/{other_breakpoint.id}/")- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)-- def test_list_only_shows_own_team_breakpoints(self):- # Create breakpoints for current team- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="my_file.py",- line_number=100,- enabled=True,- )-- # Create breakpoint for different team- other_team = self.organization.teams.create(name="Other Team")- LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="their_file.py",- line_number=200,- enabled=True,- )-- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Should only see own team's breakpoint- self.assertEqual(len(response.json()["results"]), 1)- self.assertEqual(response.json()["results"][0]["filename"], "my_file.py")-- def test_breakpoint_hits_with_defaults(self):- """Test breakpoint_hits endpoint with no parameters (should use defaults)"""- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertIn("results", response.json())- self.assertIn("count", response.json())- self.assertIn("has_more", response.json())-- def test_breakpoint_hits_with_valid_parameters(self):- """Test breakpoint_hits endpoint with valid limit and offset"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": 50, "offset": 10},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- def test_breakpoint_hits_with_breakpoint_id_filter(self):- """Test breakpoint_hits endpoint with valid breakpoint_ids"""- breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=50,- enabled=True,- )- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids={str(breakpoint.id)}",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- def test_breakpoint_hits_with_multiple_breakpoint_ids(self):- """Test breakpoint_hits endpoint with multiple breakpoint_ids"""- breakpoint1 = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=50,- enabled=True,- )- breakpoint2 = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="test.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="other.py",- line_number=200,- enabled=True,- )-- # Request hits for first two breakpoints only using repeated query params- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids={str(breakpoint1.id)}&breakpoint_ids={str(breakpoint2.id)}",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- def test_breakpoint_hits_invalid_breakpoint_id(self):- """Test breakpoint_hits with non-UUID in breakpoint_ids"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids=not-a-uuid",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- # ListField validation returns breakpoint_ids__0 for the first item- self.assertIn("breakpoint_ids", response.json()["attr"])-- def test_breakpoint_hits_limit_too_high(self):- """Test breakpoint_hits with limit > 1000"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": 1001},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "limit")-- def test_breakpoint_hits_limit_too_low(self):- """Test breakpoint_hits with limit < 1"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": 0},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "limit")-- def test_breakpoint_hits_negative_limit(self):- """Test breakpoint_hits with negative limit"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": -5},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "limit")-- def test_breakpoint_hits_negative_offset(self):- """Test breakpoint_hits with negative offset"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"offset": -1},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "offset")-- def test_breakpoint_hits_invalid_limit_type(self):- """Test breakpoint_hits with non-integer limit"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": "not-a-number"},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "limit")-- def test_breakpoint_hits_invalid_offset_type(self):- """Test breakpoint_hits with non-integer offset"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"offset": "not-a-number"},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["attr"], "offset")-- def test_breakpoint_hits_limit_at_max_boundary(self):- """Test breakpoint_hits with limit exactly at max (1000)"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": 1000},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- def test_breakpoint_hits_limit_at_min_boundary(self):- """Test breakpoint_hits with limit exactly at min (1)"""- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/",- {"limit": 1},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- def test_active_breakpoints_enabled_boolean_true(self):- """Test active_breakpoints with boolean enabled=true"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="enabled.py",- line_number=100,- enabled=True,- )- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/",- {"enabled": True},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- data = response.json()- self.assertEqual(data["count"], 1)- self.assertEqual(data["has_more"], False)- self.assertEqual(len(data["results"]), 1)-- def test_active_breakpoints_enabled_boolean_false(self):- """Test active_breakpoints with boolean enabled=false"""- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="enabled.py",- line_number=100,- enabled=True,- )- LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="disabled.py",- line_number=200,- enabled=False,- )- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/",- {"enabled": False},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- # When enabled=false, should return all breakpoints- data = response.json()- self.assertEqual(data["count"], 2)- self.assertEqual(data["has_more"], False)- self.assertEqual(len(data["results"]), 2)-- # ============================================================================- # CRITICAL SECURITY TESTS - Data Isolation & Cross-Team Access Prevention- # ============================================================================-- def test_breakpoint_hits_with_other_team_breakpoint_id_returns_404(self):- """SECURITY: Requesting hits with another team's breakpoint_id returns 404 (not empty results)"""- # Create a breakpoint for another team in the same organization- other_team = self.organization.teams.create(name="Other Team")- other_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="confidential.py",- line_number=123,- enabled=True,- )-- # Try to request hits for the other team's breakpoint from our team's context- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids={str(other_breakpoint.id)}",- )-- # Should return 200 with empty results (filtered out)- # The breakpoint ID is silently filtered to only include team's breakpoints- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 0)-- def test_breakpoint_hits_with_nonexistent_breakpoint_id_returns_404(self):- """SECURITY: Requesting hits with non-existent breakpoint_id returns empty results"""- import uuid-- fake_uuid = str(uuid.uuid4())-- response = self.client.get(- f"/api/projects/{self.team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids={fake_uuid}",- )-- # Should return 200 with empty results (filtered out)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 0)-- def test_active_breakpoints_only_shows_own_team(self):- """SECURITY: active_breakpoints endpoint only shows own team's breakpoints"""- # Create breakpoints for our team- our_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- repository="PostHog/posthog",- filename="our_file.py",- line_number=100,- enabled=True,- )-- # Create breakpoints for another team in same organization- other_team = self.organization.teams.create(name="Other Team")- other_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="their_secret_file.py",- line_number=200,- enabled=True,- )-- # Request active breakpoints from our team's context- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- data = response.json()- self.assertEqual(data["count"], 1)- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]-- # Should only see our team's breakpoint- self.assertEqual(len(breakpoints), 1)- self.assertEqual(breakpoints[0]["filename"], "our_file.py")- self.assertEqual(breakpoints[0]["id"], str(our_breakpoint.id))-- # Verify other team's breakpoint is NOT in response- other_breakpoint_ids = [str(bp["id"]) for bp in breakpoints]- self.assertNotIn(str(other_breakpoint.id), other_breakpoint_ids)-- def test_active_breakpoints_cross_org_isolation(self):- """SECURITY: Complete isolation between different organizations"""- # Create a completely different organization- from posthog.models import Organization-- other_org = Organization.objects.create(name="Other Organization")- other_team = other_org.teams.create(name="Other Org Team")-- # Create breakpoint in the other organization- other_org_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="other_org_secret.py",- line_number=999,- enabled=True,- )-- # Request from our team's context- response = self.client.get(f"/api/projects/{self.team.id}/live_debugger_breakpoints/active/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- data = response.json()- self.assertEqual(data["has_more"], False)- breakpoints = data["results"]-- # Should see NO breakpoints from other organization- other_org_breakpoint_ids = [str(bp["id"]) for bp in breakpoints]- self.assertNotIn(str(other_org_breakpoint.id), other_org_breakpoint_ids)-- def test_cannot_access_different_org_via_url_path(self):- """SECURITY: Cannot access a different organization's data by changing URL path"""- # Create a different organization- from posthog.models import Organization-- other_org = Organization.objects.create(name="Other Organization")- other_team = other_org.teams.create(name="Other Org Team")- LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="sensitive.py",- line_number=500,- enabled=True,- )-- # Try to access via their team's URL path (different org)- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/breakpoint_hits/")-- # Should be denied - cannot access different organization- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- def test_cannot_list_different_org_breakpoints_via_url_path(self):- """SECURITY: Cannot list a different organization's breakpoints by changing URL path"""- # Create a different organization- from posthog.models import Organization-- other_org = Organization.objects.create(name="Other Organization")- other_team = other_org.teams.create(name="Other Org Team")- LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="confidential.py",- line_number=999,- enabled=True,- )-- # Try to access other org's breakpoints list via their URL- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/")-- # Should be denied - cannot access different organization- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- def test_cannot_access_different_org_active_breakpoints_via_url_path(self):- """SECURITY: Cannot access a different organization's active breakpoints by changing URL path"""- # Create a different organization- from posthog.models import Organization-- other_org = Organization.objects.create(name="Other Organization")- other_team = other_org.teams.create(name="Other Org Team")- LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="private.py",- line_number=100,- enabled=True,- )-- # Try to access via their URL path (different org)- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/active/")-- # Should be denied - cannot access different organization- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- def test_can_access_another_team_in_same_org_by_default(self):- """By default (no advanced permissions), org members can access all teams in their org"""- # Create another team in the SAME organization- other_team = self.organization.teams.create(name="Other Team in Same Org")- other_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="shared_file.py",- line_number=100,- enabled=True,- )-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.json()["results"]), 1)- self.assertEqual(response.json()["results"][0]["filename"], "shared_file.py")-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/{other_breakpoint.id}/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["filename"], "shared_file.py")-- def test_cannot_access_private_team_without_explicit_access(self):- """With advanced permissions, users cannot access private teams without explicit access"""- from posthog.constants import AvailableFeature- from posthog.models import OrganizationMembership-- from products.access_control.backend.models.access_control import AccessControl-- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}- ]- self.organization.save()-- other_team = self.organization.teams.create(name="Private Team")- AccessControl.objects.create(- team=other_team,- resource="project",- resource_id=str(other_team.id),- organization_member=None,- role=None,- access_level="none",- )-- private_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="private_file.py",- line_number=200,- enabled=True,- )-- self.organization_membership.level = OrganizationMembership.Level.MEMBER- self.organization_membership.save()-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/")- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/{private_breakpoint.id}/")- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- response = self.client.get(- f"/api/projects/{other_team.id}/live_debugger_breakpoints/breakpoint_hits/?breakpoint_ids={str(private_breakpoint.id)}",- )- self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND])-- def test_can_access_private_team_with_explicit_access(self):- """With advanced permissions, users can access private teams when granted explicit access"""- from posthog.constants import AvailableFeature- from posthog.models import OrganizationMembership-- from products.access_control.backend.models.access_control import AccessControl-- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}- ]- self.organization.save()-- other_team = self.organization.teams.create(name="Private Team with Access")- AccessControl.objects.create(- team=other_team,- resource="project",- resource_id=str(other_team.id),- organization_member=None,- role=None,- access_level="none",- )-- AccessControl.objects.create(- team=other_team,- resource="project",- resource_id=str(other_team.id),- organization_member=self.organization_membership,- role=None,- access_level="member",- )-- private_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="accessible_private_file.py",- line_number=300,- enabled=True,- )-- self.organization_membership.level = OrganizationMembership.Level.MEMBER- self.organization_membership.save()-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.json()["results"]), 1)-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/{private_breakpoint.id}/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["filename"], "accessible_private_file.py")-- def test_org_admin_can_access_private_team(self):- """Org admins can access private teams even without explicit access"""- from posthog.constants import AvailableFeature- from posthog.models import OrganizationMembership-- from products.access_control.backend.models.access_control import AccessControl-- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}- ]- self.organization.save()-- other_team = self.organization.teams.create(name="Private Team for Admin")- AccessControl.objects.create(- team=other_team,- resource="project",- resource_id=str(other_team.id),- organization_member=None,- role=None,- access_level="none",- )-- admin_accessible_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- repository="PostHog/posthog",- filename="admin_accessible_file.py",- line_number=400,- enabled=True,- )-- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- response = self.client.get(f"/api/projects/{other_team.id}/live_debugger_breakpoints/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.json()["results"]), 1)-- response = self.client.get(- f"/api/projects/{other_team.id}/live_debugger_breakpoints/{admin_accessible_breakpoint.id}/"- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["filename"], "admin_accessible_file.py")diff --git a/products/live_debugger/backend/test_models.py b/products/live_debugger/backend/test_models.pydeleted file mode 100644index 8372447ae5be..000000000000--- a/products/live_debugger/backend/test_models.py+++ /dev/null@@ -1,394 +0,0 @@-import uuid-from datetime import datetime, timedelta--import time_machine-from posthog.test.base import BaseTest, ClickhouseTestMixin--from posthog.models.event.util import bulk_create_events--from products.live_debugger.backend.models import LiveDebuggerBreakpoint---class TestLiveDebuggerBreakpointModel(ClickhouseTestMixin, BaseTest):- def setUp(self):- super().setUp()- # Clean ClickHouse events table before each test- from posthog.clickhouse.client import sync_execute-- sync_execute("TRUNCATE TABLE IF EXISTS sharded_events")-- self.breakpoint = LiveDebuggerBreakpoint.objects.create(- team=self.team,- filename="test.py",- line_number=42,- enabled=True,- )-- def test_get_breakpoint_hits_returns_hits_for_team(self):- """Test that get_breakpoint_hits returns breakpoint hits for the specified team"""- breakpoint_id = str(self.breakpoint.id)-- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user123",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": breakpoint_id,- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "test_function", "line": 42, "file": "test.py"}],- "$locals_variables": {"x": 10, "y": 20},- },- }- ]- )-- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- assert len(hits) == 1- assert hits[0].id is not None # UUID should be set- assert hits[0].breakpoint_id == breakpoint_id- assert hits[0].line_number == 42- assert hits[0].filename == "test.py"- assert hits[0].function_name == "test_function"- assert hits[0].locals == {"x": 10, "y": 20}- assert len(hits[0].stack_trace) == 1-- def test_get_breakpoint_hits_team_isolation(self):- """Test that get_breakpoint_hits only returns hits for the specified team"""- other_team = self.organization.teams.create(name="Other Team")- other_breakpoint = LiveDebuggerBreakpoint.objects.create(- team=other_team,- filename="other.py",- line_number=100,- enabled=True,- )-- # Create event for our team- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "my_func"}],- "$locals_variables": {},- },- }- ]- )-- # Create event for other team- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": other_team.pk,- "distinct_id": "user2",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(other_breakpoint.id),- "$line_number": 100,- "$file_path": "other.py",- "$stack_trace": [{"function": "other_func"}],- "$locals_variables": {},- },- }- ]- )-- # Query for our team- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- # Should only return our team's hits- assert len(hits) == 1- assert hits[0].filename == "test.py"- assert hits[0].function_name == "my_func"-- # Query for other team- other_hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=other_team)-- # Should only return other team's hits- assert len(other_hits) == 1- assert other_hits[0].filename == "other.py"- assert other_hits[0].function_name == "other_func"-- def test_get_breakpoint_hits_filter_by_breakpoint_id(self):- """Test that get_breakpoint_hits filters by breakpoint_ids when provided"""- breakpoint2 = LiveDebuggerBreakpoint.objects.create(- team=self.team,- filename="other.py",- line_number=100,- enabled=True,- )-- # Create events for two different breakpoints- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "func1"}],- "$locals_variables": {},- },- },- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(breakpoint2.id),- "$line_number": 100,- "$file_path": "other.py",- "$stack_trace": [{"function": "func2"}],- "$locals_variables": {},- },- },- ]- )-- # Query without filter - should return both- all_hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)- assert len(all_hits) == 2-- # Query with filter for first breakpoint (using list)- filtered_hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team, breakpoint_ids=[self.breakpoint.id])- assert len(filtered_hits) == 1- assert filtered_hits[0].filename == "test.py"- assert filtered_hits[0].function_name == "func1"-- # Query with filter for second breakpoint (using list)- filtered_hits2 = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team, breakpoint_ids=[breakpoint2.id])- assert len(filtered_hits2) == 1- assert filtered_hits2[0].filename == "other.py"- assert filtered_hits2[0].function_name == "func2"-- def test_get_breakpoint_hits_time_filter(self):- """Test that get_breakpoint_hits only returns hits from the last hour"""- # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- now = datetime.now()-- # Create event from 30 minutes ago (should be included)- with time_machine.travel(now - timedelta(minutes=30), tick=False):- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "recent_func"}],- "$locals_variables": {},- },- }- ]- )-- # Create event from 2 hours ago (should be excluded)- with time_machine.travel(now - timedelta(hours=2), tick=False):- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "old_func"}],- "$locals_variables": {},- },- }- ]- )-- # Query should only return the recent event- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- assert len(hits) == 1- assert hits[0].function_name == "recent_func"-- def test_get_breakpoint_hits_pagination(self):- """Test that get_breakpoint_hits respects limit and offset parameters"""- # Create 5 events- events = []- for i in range(5):- events.append(- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42 + i,- "$file_path": "test.py",- "$stack_trace": [{"function": f"func{i}"}],- "$locals_variables": {"index": i},- },- }- )- bulk_create_events(events)-- # Test limit- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team, limit=2)- assert len(hits) == 2-- # Test offset- hits_page2 = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team, limit=2, offset=2)- assert len(hits_page2) == 2-- # Verify different results- hit_functions = {hit.function_name for hit in hits}- hit_functions_page2 = {hit.function_name for hit in hits_page2}- assert hit_functions != hit_functions_page2-- def test_get_breakpoint_hits_empty_results(self):- """Test that get_breakpoint_hits returns empty list when no hits exist"""- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)- assert hits == []-- def test_get_breakpoint_hits_handles_malformed_json(self):- """Test that get_breakpoint_hits skips events with malformed JSON data"""- # Create event with valid JSON- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "good_func"}],- "$locals_variables": {"x": 1},- },- }- ]- )-- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- # Should return the valid event- assert len(hits) == 1- assert hits[0].function_name == "good_func"-- def test_get_breakpoint_hits_only_includes_breakpoint_hit_events(self):- """Test that get_breakpoint_hits only returns $data_breakpoint_hit events"""- # Create a regular event (not a breakpoint hit)- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$pageview",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {},- }- ]- )-- # Create a breakpoint hit event- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": datetime.now(), # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "test_func"}],- "$locals_variables": {},- },- }- ]- )-- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- # Should only return the breakpoint hit event- assert len(hits) == 1- assert hits[0].function_name == "test_func"-- def test_get_breakpoint_hits_orders_by_timestamp_desc(self):- """Test that get_breakpoint_hits returns hits ordered by timestamp descending"""- # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())- now = datetime.now()-- # Create events at different times- bulk_create_events(- [- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": now - timedelta(minutes=30),- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "old_func"}],- "$locals_variables": {},- },- },- {- "uuid": str(uuid.uuid4()),- "event": "$data_breakpoint_hit",- "team_id": self.team.pk,- "distinct_id": "user1",- "timestamp": now - timedelta(minutes=10),- "properties": {- "$breakpoint_id": str(self.breakpoint.id),- "$line_number": 42,- "$file_path": "test.py",- "$stack_trace": [{"function": "recent_func"}],- "$locals_variables": {},- },- },- ]- )-- hits = LiveDebuggerBreakpoint.get_breakpoint_hits(team=self.team)-- # Should return most recent first- assert len(hits) == 2- assert hits[0].function_name == "recent_func"- assert hits[1].function_name == "old_func"diff --git a/products/live_debugger/frontend/CodeLine.tsx b/products/live_debugger/frontend/CodeLine.tsxdeleted file mode 100644index 71ea3825e6fc..000000000000--- a/products/live_debugger/frontend/CodeLine.tsx+++ /dev/null@@ -1,61 +0,0 @@-import clsx from 'clsx'--import { highlightPythonSyntax } from './codeUtils'--export function CodeLine({- line,- lineNumber,- hasBreakpoint,- hasInstances,- hitCount,- hasNewHits,- onClick,- onHitCountClick,-}: {- line: string- lineNumber: number- hasBreakpoint: boolean- hasInstances: boolean- hitCount: number- hasNewHits: boolean- onClick: () => void- onHitCountClick: () => void-}): JSX.Element {- return (- <div- className={clsx(- 'flex items-center group hover:bg-bg-3000 transition-colors',- hasNewHits && 'bg-yellow-100 dark:bg-yellow-900/20'- )}- >- <div className="flex items-center justify-center w-10 px-1 cursor-pointer select-none" onClick={onClick}>- <div className="relative flex items-center justify-center">- {hasBreakpoint ? (- hasInstances ? (- <div className="w-3 h-3 bg-warning rounded-full animate-pulse border-2 border-danger" />- ) : (- <div className="w-3 h-3 bg-danger rounded-full" />- )- ) : hasInstances ? (- <div className="w-3 h-3 bg-warning rounded-full animate-pulse" />- ) : (- <div className="w-3 h-3 border border-muted rounded-full opacity-0 group-hover:opacity-100 transition-opacity" />- )}- </div>- </div>- <div className="w-10 text-right pr-2 text-muted text-xs select-none">{lineNumber}</div>- {hitCount > 0 && (- <div- className="w-6 h-4 text-xs bg-orange-500 text-white rounded-full flex items-center justify-center cursor-pointer mr-2 hover:bg-orange-600 transition-colors"- onClick={onHitCountClick}- title={`${hitCount} breakpoint hit${hitCount > 1 ? 's' : ''}`}- >- {hitCount}- </div>- )}- <pre className="flex-1 m-0 text-xs overflow-hidden whitespace-pre">- <code className="block" dangerouslySetInnerHTML={{ __html: highlightPythonSyntax(line || ' ') }} />- </pre>- </div>- )-}diff --git a/products/live_debugger/frontend/LiveDebugger.tsx b/products/live_debugger/frontend/LiveDebugger.tsxdeleted file mode 100644index 072cad4a9e39..000000000000--- a/products/live_debugger/frontend/LiveDebugger.tsx+++ /dev/null@@ -1,132 +0,0 @@-import clsx from 'clsx'-import { useActions, useValues } from 'kea'--import { NotFound } from 'lib/components/NotFound'-import { dayjs } from 'lib/dayjs'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { SceneExport } from 'scenes/sceneTypes'--import { SceneContent } from '~/layout/scenes/components/SceneContent'-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { ProductKey } from '~/queries/schema/schema-general'--import { StateInspector } from 'products/live_debugger/frontend/StateInspector'--import { BreakpointInstance, liveDebuggerLogic } from './liveDebuggerLogic'-import { RepositoryBrowser } from './repo_browser/RepositoryBrowser'--export const scene: SceneExport = {- component: LiveDebugger,- logic: liveDebuggerLogic,- productKey: ProductKey.LIVE_DEBUGGER,-}--function BreakpointInstanceCard({- instance,- isSelected,- isNew,- onClick,-}: {- instance: BreakpointInstance- isSelected: boolean- isNew: boolean- onClick: () => void-}): JSX.Element {- return (- <div- className={clsx(- 'p-2 border rounded cursor-pointer transition-colors text-xs',- isSelected ? 'border-primary bg-primary-highlight' : 'border-border hover:bg-bg-light',- isNew && 'animate-pulse bg-warning-highlight border-warning'- )}- onClick={onClick}- >- <div className="text-muted text-xs mb-0.5">{dayjs(instance.timestamp).fromNow()}</div>- <div- className="font-mono font-semibold text-xs truncate"- title={`${instance.functionName || 'captureEvent'}:${instance.lineNumber}`}- >- {instance.functionName || 'captureEvent'}:{instance.lineNumber}- </div>- </div>- )-}--export function LiveDebugger(): JSX.Element {- const isEnabled = useFeatureFlag('LIVE_DEBUGGER')-- const { selectedInstance, newInstanceIds, selectedLineForHits, hitsForSelectedLine } = useValues(liveDebuggerLogic)- const { selectInstance, showHitsForLine } = useActions(liveDebuggerLogic)-- if (!isEnabled) {- return <NotFound object="Live debugger" caption="This feature is not enabled for your project." />- }-- return (- <>- <SceneTitleSection- name="Live Debugger"- description="Set breakpoints in your code to capture and inspect runtime values"- resourceType={{- type: 'live_debugger',- }}- />-- <SceneContent>- <div className="flex gap-3 h-[calc(100vh-200px)]">- <RepositoryBrowser />-- {/* Middle - Breakpoint instances for selected line */}- <div className="w-64 border rounded bg-bg-light overflow-hidden flex flex-col">- <div className="px-2 py-1.5 border-b bg-bg-3000 flex items-center justify-between">- <span className="font-semibold text-xs">- {selectedLineForHits ? `Line ${selectedLineForHits}` : 'Hits'}- </span>- {selectedLineForHits && (- <button- onClick={() => showHitsForLine(null)}- className="text-xs text-muted hover:text-default"- >- Clear- </button>- )}- </div>-- <div className="flex-1 overflow-auto">- {selectedLineForHits ? (- hitsForSelectedLine.length > 0 ? (- <div className="p-1.5 space-y-1.5">- {hitsForSelectedLine.map((instance) => (- <BreakpointInstanceCard- key={instance.id}- instance={instance}- isSelected={selectedInstance?.id === instance.id}- isNew={newInstanceIds.has(instance.id)}- onClick={() => selectInstance(instance.id)}- />- ))}- </div>- ) : (- <div className="flex-1 flex items-center justify-center text-muted p-2 text-center">- <p className="text-xs">No hits</p>- </div>- )- ) : (- <div className="flex-1 flex items-center justify-center text-muted p-2 text-center">- <div className="text-xs">- <p>Click hit count badges</p>- <p className="mt-1">to view hits</p>- </div>- </div>- )}- </div>- </div>-- {selectedInstance && (- <StateInspector selectedInstance={selectedInstance} selectInstance={selectInstance} />- )}- </div>- </SceneContent>- </>- )-}diff --git a/products/live_debugger/frontend/StateInspector.tsx b/products/live_debugger/frontend/StateInspector.tsxdeleted file mode 100644index 6baa2c09355e..000000000000--- a/products/live_debugger/frontend/StateInspector.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconX } from '@posthog/icons'--import { JSONViewer } from 'lib/components/JSONViewer'--import { LemonButton } from '../../../frontend/src/lib/lemon-ui/LemonButton'-import { liveDebuggerLogic } from './liveDebuggerLogic'-import { parseJsonPickleVariable } from './serde'--function VariableDisplay({ variables }: { variables: Record<string, any> }): JSX.Element {- return (- <div className="border rounded divide-y">- {Object.entries(variables).map(([key, value]) => {- const parsed = parseJsonPickleVariable(value)- return (- <div key={key} className="p-2">- <div className="flex items-center gap-2 mb-1">- <div className="text-muted text-xs font-semibold">{key}</div>- {parsed.typeName && (- <div className="text-xs text-muted-alt bg-bg-3000 px-1.5 py-0.5 rounded font-mono">- {parsed.typeName}- </div>- )}- </div>- <div className="text-xs font-mono break-words">- {parsed.type === 'complex' ? (- <JSONViewer src={parsed.value} collapsed={1} />- ) : (- <span>{String(parsed.value)}</span>- )}- </div>- </div>- )- })}- </div>- )-}--export function StateInspector({- selectedInstance,- selectInstance,-}: {- selectedInstance: any- selectInstance: (arg: any) => void-}): JSX.Element {- const { breakpoints, breakpointInstances, currentRepository } = useValues(liveDebuggerLogic)-- const { toggleBreakpointForFile } = useActions(liveDebuggerLogic)-- return (- <div className="flex-[2] border rounded bg-bg-light overflow-hidden flex flex-col">- <div className="flex items-center justify-between p-2 border-b bg-bg-3000">- <span className="font-semibold">Debug Details</span>- <button onClick={() => selectInstance(null)} className="text-muted hover:text-default">- <IconX />- </button>- </div>-- <div className="flex-1 p-3 overflow-auto space-y-4">- <div>- <h4 className="font-semibold text-sm mb-2">Variables at Line {selectedInstance.lineNumber}</h4>- <VariableDisplay variables={selectedInstance.variables} />- </div>-- {selectedInstance.stackTrace && (- <div>- <h4 className="font-semibold text-sm mb-2">Stack Trace</h4>- <div className="text-xs font-mono bg-bg-3000 p-2 rounded max-h-96 overflow-auto space-y-1">- {selectedInstance.stackTrace.map((frame: any, i: number) => {- const functionName = frame[1]- const fileName = frame[0]- const lineNumber = frame[2] as number-- // Match filenames more flexibly (handle full paths vs relative paths)- const fileNameMatch = (bpFilename: string, stackFilename: string): boolean => {- if (bpFilename === stackFilename) {- return true- }- // Check if one ends with the other (handles full path vs relative)- return bpFilename.endsWith(stackFilename) || stackFilename.endsWith(bpFilename)- }-- const hasBreakpoint =- Array.isArray(breakpoints) &&- breakpoints.some(- (bp) => fileNameMatch(bp.filename, fileName) && bp.line_number === lineNumber- )- const hitCount = Array.isArray(breakpointInstances)- ? breakpointInstances.filter(- (inst) =>- fileNameMatch(inst.filename, fileName) && inst.lineNumber === lineNumber- ).length- : 0-- return (- <div- key={i}- className="px-2 py-1 border border-border rounded hover:bg-bg-light flex items-center justify-between gap-2"- >- <div className="flex-1 min-w-0">- <div className="flex items-baseline gap-1.5">- <span className="text-muted font-normal">#{i}</span>- <span className="font-semibold truncate">{functionName}</span>- {hitCount > 0 && (- <span className="text-xs bg-orange-500 text-white px-1 rounded">- {hitCount}- </span>- )}- </div>- <div className="text-muted text-xs truncate">- {fileName}- {lineNumber ? `:${lineNumber}` : ''}- </div>- </div>- {lineNumber && (- <LemonButton- size="xsmall"- type={hasBreakpoint ? 'primary' : 'secondary'}- onClick={() => {- if (typeof lineNumber === 'number') {- toggleBreakpointForFile(fileName, lineNumber, currentRepository)- }- }}- >- BP- </LemonButton>- )}- </div>- )- })}- </div>- </div>- )}- </div>- </div>- )-}diff --git a/products/live_debugger/frontend/codeUtils.ts b/products/live_debugger/frontend/codeUtils.tsdeleted file mode 100644index 232a6e97042a..000000000000--- a/products/live_debugger/frontend/codeUtils.ts+++ /dev/null@@ -1,62 +0,0 @@-/// Very very scrappy function to do some syntax highlighting-export function highlightPythonSyntax(line: string): string {- let highlighted = line.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')-- if (line.trim().startsWith('#')) {- return `<span class="text-green-600">${highlighted}</span>`- }-- // Split by comments to avoid highlighting inside them- const commentIndex = line.indexOf('#')- let beforeComment = highlighted- let comment = ''-- if (commentIndex !== -1) {- beforeComment = highlighted.substring(0, commentIndex)- comment = `<span class="text-green-600">${highlighted.substring(commentIndex)}</span>`- }-- // Apply highlighting only to the non-comment part- let processed = beforeComment-- // Strings (avoid conflicts by being more specific)- processed = processed.replace(- /(^|[^a-zA-Z0-9_])(["'])((?:\\.|(?!\2)[^\\])*?)\2/g,- '$1<span class="text-orange-400">$2$3$2</span>'- )-- // Decorators- processed = processed.replace(- /(@[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,- '<span class="text-yellow-400">$1</span>'- )-- // Function definitions (def keyword + function name)- processed = processed.replace(- /\b(def)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g,- '<span class="text-blue-400">$1</span> <span class="text-yellow-300">$2</span>'- )-- // Class definitions (class keyword + class name)- processed = processed.replace(- /\b(class)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g,- '<span class="text-blue-400">$1</span> <span class="text-green-300">$2</span>'- )-- // Keywords (but not inside existing spans)- processed = processed.replace(- /\b(if|else|elif|for|while|import|from|return|try|except|finally|with|as|pass|break|continue|and|or|not|in|is|lambda|global|nonlocal|yield|async|await)\b(?![^<]*>)/g,- '<span class="text-blue-400">$1</span>'- )-- // Built-in functions- processed = processed.replace(- /\b(print|len|range|str|int|float|list|dict|set|tuple|bool|type|isinstance|hasattr|getattr|setattr|open|file|input|raw_input)\b(?![^<]*>)/g,- '<span class="text-cyan-400">$1</span>'- )-- // Numbers- processed = processed.replace(/\b(\d+\.?\d*)\b(?![^<]*>)/g, '<span class="text-green-400">$1</span>')-- return processed + comment-}diff --git a/products/live_debugger/frontend/generated/api.schemas.ts b/products/live_debugger/frontend/generated/api.schemas.tsdeleted file mode 100644index 540a08f48967..000000000000--- a/products/live_debugger/frontend/generated/api.schemas.ts+++ /dev/null@@ -1,165 +0,0 @@-/**- * Auto-generated from the Django backend OpenAPI schema.- * To modify these types, update the Django serializers or views, then run:- * hogli build:openapi- * Questions or issues? #team-devex on Slack- *- * PostHog API - generated- * OpenAPI spec version: 1.0.0- */-export interface LiveDebuggerBreakpointApi {- readonly id: string- /** @nullable */- repository?: string | null- filename: string- /**- * @minimum 0- * @maximum 2147483647- */- line_number: number- enabled?: boolean- /** @nullable */- condition?: string | null- readonly created_at: string- readonly updated_at: string-}--export interface PaginatedLiveDebuggerBreakpointListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: LiveDebuggerBreakpointApi[]-}--export interface PatchedLiveDebuggerBreakpointApi {- readonly id?: string- /** @nullable */- repository?: string | null- filename?: string- /**- * @minimum 0- * @maximum 2147483647- */- line_number?: number- enabled?: boolean- /** @nullable */- condition?: string | null- readonly created_at?: string- readonly updated_at?: string-}--/**- * Schema for a single active breakpoint- */-export interface ActiveBreakpointApi {- /** Unique identifier for the breakpoint */- id: string- /**- * Repository identifier (e.g., 'PostHog/posthog')- * @nullable- */- repository?: string | null- /** File path where the breakpoint is set */- filename: string- /** Line number of the breakpoint */- line_number: number- /** Whether the breakpoint is enabled */- enabled: boolean- /**- * Optional condition for the breakpoint- * @nullable- */- condition?: string | null-}--/**- * Response schema for active breakpoints endpoint- */-export interface ActiveBreakpointsResponseApi {- /** List of active breakpoints */- breakpoints: ActiveBreakpointApi[]-}--/**- * Local variables at the time of the hit- */-export type BreakpointHitApiVariables = { [key: string]: unknown }--/**- * Schema for a single breakpoint hit event- */-export interface BreakpointHitApi {- /** Unique identifier for the hit event */- id: string- /** Line number where the breakpoint was hit */- lineNumber: number- /** Name of the function where breakpoint was hit */- functionName: string- /** When the breakpoint was hit */- timestamp: string- /** Local variables at the time of the hit */- variables: BreakpointHitApiVariables- /** Stack trace at the time of the hit */- stackTrace: unknown[]- /** ID of the breakpoint that was hit */- breakpoint_id: string- /** Filename where the breakpoint was hit */- filename: string-}--/**- * Response schema for breakpoint hits endpoint- */-export interface BreakpointHitsResponseApi {- /** List of breakpoint hit events */- results: BreakpointHitApi[]- /** Number of results returned */- count: number- /** Whether there are more results available */- has_more: boolean-}--export type LiveDebuggerBreakpointsListParams = {- filename?: string- /**- * Number of results to return per page.- */- limit?: number- /**- * The initial index from which to return the results.- */- offset?: number- repository?: string-}--export type LiveDebuggerBreakpointsActiveRetrieveParams = {- /**- * Only return enabled breakpoints- */- enabled?: boolean- /**- * Filter breakpoints for a specific file- */- filename?: string- /**- * Filter breakpoints for a specific repository (e.g., 'PostHog/posthog')- */- repository?: string-}--export type LiveDebuggerBreakpointsBreakpointHitsRetrieveParams = {- /**- * Filter hits for specific breakpoints (repeat parameter for multiple IDs, e.g., ?breakpoint_ids=uuid1&breakpoint_ids=uuid2)- */- breakpoint_ids?: string- /**- * Number of hits to return (default: 100, max: 1000)- */- limit?: number- /**- * Pagination offset for retrieving additional results (default: 0)- */- offset?: number-}diff --git a/products/live_debugger/frontend/generated/api.ts b/products/live_debugger/frontend/generated/api.tsdeleted file mode 100644index 9c5ea1c60e98..000000000000--- a/products/live_debugger/frontend/generated/api.ts+++ /dev/null@@ -1,240 +0,0 @@-import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'-/**- * Auto-generated from the Django backend OpenAPI schema.- * To modify these types, update the Django serializers or views, then run:- * hogli build:openapi- * Questions or issues? #team-devex on Slack- *- * PostHog API - generated- * OpenAPI spec version: 1.0.0- */-import type {- ActiveBreakpointsResponseApi,- BreakpointHitsResponseApi,- LiveDebuggerBreakpointApi,- LiveDebuggerBreakpointsActiveRetrieveParams,- LiveDebuggerBreakpointsBreakpointHitsRetrieveParams,- LiveDebuggerBreakpointsListParams,- PaginatedLiveDebuggerBreakpointListApi,- PatchedLiveDebuggerBreakpointApi,-} from './api.schemas'--// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497-type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B--type WritableKeys<T> = {- [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>-}[keyof T]--type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never-type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never--type Writable<T> = Pick<T, WritableKeys<T>>-type NonReadonly<T> = [T] extends [UnionToIntersection<T>]- ? {- [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]- }- : DistributeReadOnlyOverUnions<T>--export const getLiveDebuggerBreakpointsListUrl = (projectId: string, params?: LiveDebuggerBreakpointsListParams) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/live_debugger_breakpoints/?${stringifiedParams}`- : `/api/projects/${projectId}/live_debugger_breakpoints/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsList = async (- projectId: string,- params?: LiveDebuggerBreakpointsListParams,- options?: RequestInit-): Promise<PaginatedLiveDebuggerBreakpointListApi> => {- return apiMutator<PaginatedLiveDebuggerBreakpointListApi>(getLiveDebuggerBreakpointsListUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getLiveDebuggerBreakpointsCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/live_debugger_breakpoints/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsCreate = async (- projectId: string,- liveDebuggerBreakpointApi: NonReadonly<LiveDebuggerBreakpointApi>,- options?: RequestInit-): Promise<LiveDebuggerBreakpointApi> => {- return apiMutator<LiveDebuggerBreakpointApi>(getLiveDebuggerBreakpointsCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(liveDebuggerBreakpointApi),- })-}--export const getLiveDebuggerBreakpointsRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/live_debugger_breakpoints/${id}/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsRetrieve = async (- projectId: string,- id: string,- options?: RequestInit-): Promise<LiveDebuggerBreakpointApi> => {- return apiMutator<LiveDebuggerBreakpointApi>(getLiveDebuggerBreakpointsRetrieveUrl(projectId, id), {- ...options,- method: 'GET',- })-}--export const getLiveDebuggerBreakpointsUpdateUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/live_debugger_breakpoints/${id}/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsUpdate = async (- projectId: string,- id: string,- liveDebuggerBreakpointApi: NonReadonly<LiveDebuggerBreakpointApi>,- options?: RequestInit-): Promise<LiveDebuggerBreakpointApi> => {- return apiMutator<LiveDebuggerBreakpointApi>(getLiveDebuggerBreakpointsUpdateUrl(projectId, id), {- ...options,- method: 'PUT',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(liveDebuggerBreakpointApi),- })-}--export const getLiveDebuggerBreakpointsPartialUpdateUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/live_debugger_breakpoints/${id}/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsPartialUpdate = async (- projectId: string,- id: string,- patchedLiveDebuggerBreakpointApi?: NonReadonly<PatchedLiveDebuggerBreakpointApi>,- options?: RequestInit-): Promise<LiveDebuggerBreakpointApi> => {- return apiMutator<LiveDebuggerBreakpointApi>(getLiveDebuggerBreakpointsPartialUpdateUrl(projectId, id), {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedLiveDebuggerBreakpointApi),- })-}--export const getLiveDebuggerBreakpointsDestroyUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/live_debugger_breakpoints/${id}/`-}--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsDestroy = async (- projectId: string,- id: string,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getLiveDebuggerBreakpointsDestroyUrl(projectId, id), {- ...options,- method: 'DELETE',- })-}--export const getLiveDebuggerBreakpointsActiveRetrieveUrl = (- projectId: string,- params?: LiveDebuggerBreakpointsActiveRetrieveParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/live_debugger_breakpoints/active/?${stringifiedParams}`- : `/api/projects/${projectId}/live_debugger_breakpoints/active/`-}--/**- * External API endpoint for client applications to fetch active breakpoints using Project API key. This endpoint allows external client applications (like Python scripts, Node.js apps, etc.) to fetch the list of active breakpoints so they can instrument their code accordingly.- *- * Authentication: Requires a Project API Key in the Authorization header: `Authorization: Bearer phs_<your-project-api-key>`. You can find your Project API Key in PostHog at: Settings → Project → Project API Key- * @summary Get active breakpoints (External API)- */-export const liveDebuggerBreakpointsActiveRetrieve = async (- projectId: string,- params?: LiveDebuggerBreakpointsActiveRetrieveParams,- options?: RequestInit-): Promise<ActiveBreakpointsResponseApi> => {- return apiMutator<ActiveBreakpointsResponseApi>(getLiveDebuggerBreakpointsActiveRetrieveUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getLiveDebuggerBreakpointsBreakpointHitsRetrieveUrl = (- projectId: string,- params?: LiveDebuggerBreakpointsBreakpointHitsRetrieveParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/live_debugger_breakpoints/breakpoint_hits/?${stringifiedParams}`- : `/api/projects/${projectId}/live_debugger_breakpoints/breakpoint_hits/`-}--/**- * Retrieve breakpoint hit events from ClickHouse with optional filtering and pagination. Returns hit events containing stack traces, local variables, and execution context from your application's runtime.- *- * Security: Breakpoint IDs are filtered to only include those belonging to the current team.- * @summary Get breakpoint hits- */-export const liveDebuggerBreakpointsBreakpointHitsRetrieve = async (- projectId: string,- params?: LiveDebuggerBreakpointsBreakpointHitsRetrieveParams,- options?: RequestInit-): Promise<BreakpointHitsResponseApi> => {- return apiMutator<BreakpointHitsResponseApi>(- getLiveDebuggerBreakpointsBreakpointHitsRetrieveUrl(projectId, params),- {- ...options,- method: 'GET',- }- )-}diff --git a/products/live_debugger/frontend/generated/api.zod.ts b/products/live_debugger/frontend/generated/api.zod.tsdeleted file mode 100644index a6ed6dd94108..000000000000--- a/products/live_debugger/frontend/generated/api.zod.ts+++ /dev/null@@ -1,62 +0,0 @@-/**- * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.- * To modify these schemas, update the Django serializers or views, then run:- * hogli build:openapi- * Questions or issues? #team-devex on Slack- *- * PostHog API - generated- * OpenAPI spec version: 1.0.0- */-import * as zod from 'zod'--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsCreateBodyLineNumberMin = 0-export const liveDebuggerBreakpointsCreateBodyLineNumberMax = 2147483647--export const LiveDebuggerBreakpointsCreateBody = /* @__PURE__ */ zod.object({- repository: zod.string().nullish(),- filename: zod.string(),- line_number: zod- .number()- .min(liveDebuggerBreakpointsCreateBodyLineNumberMin)- .max(liveDebuggerBreakpointsCreateBodyLineNumberMax),- enabled: zod.boolean().optional(),- condition: zod.string().nullish(),-})--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsUpdateBodyLineNumberMin = 0-export const liveDebuggerBreakpointsUpdateBodyLineNumberMax = 2147483647--export const LiveDebuggerBreakpointsUpdateBody = /* @__PURE__ */ zod.object({- repository: zod.string().nullish(),- filename: zod.string(),- line_number: zod- .number()- .min(liveDebuggerBreakpointsUpdateBodyLineNumberMin)- .max(liveDebuggerBreakpointsUpdateBodyLineNumberMax),- enabled: zod.boolean().optional(),- condition: zod.string().nullish(),-})--/**- * Create, Read, Update and Delete breakpoints for live debugging.- */-export const liveDebuggerBreakpointsPartialUpdateBodyLineNumberMin = 0-export const liveDebuggerBreakpointsPartialUpdateBodyLineNumberMax = 2147483647--export const LiveDebuggerBreakpointsPartialUpdateBody = /* @__PURE__ */ zod.object({- repository: zod.string().nullish(),- filename: zod.string().optional(),- line_number: zod- .number()- .min(liveDebuggerBreakpointsPartialUpdateBodyLineNumberMin)- .max(liveDebuggerBreakpointsPartialUpdateBodyLineNumberMax)- .optional(),- enabled: zod.boolean().optional(),- condition: zod.string().nullish(),-})diff --git a/products/live_debugger/frontend/liveDebuggerLogic.test.ts b/products/live_debugger/frontend/liveDebuggerLogic.test.tsdeleted file mode 100644index bee35e611c48..000000000000--- a/products/live_debugger/frontend/liveDebuggerLogic.test.ts+++ /dev/null@@ -1,867 +0,0 @@-import { MOCK_TEAM_ID } from 'lib/api.mock'--import { expectLogic } from 'kea-test-utils'--import api from 'lib/api'--import { initKeaTests } from '~/test/init'--import type { Breakpoint, BreakpointInstance } from './liveDebuggerLogic'-import { liveDebuggerLogic } from './liveDebuggerLogic'--jest.mock('lib/api')--describe('liveDebuggerLogic', () => {- let logic: ReturnType<typeof liveDebuggerLogic.build>-- // Mock data- const mockBreakpoints: Breakpoint[] = [- {- id: 'bp-1',- repository: 'PostHog/posthog',- filename: 'capture_event.py',- line_number: 100,- enabled: true,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- {- id: 'bp-2',- repository: 'PostHog/posthog',- filename: 'capture_event.py',- line_number: 200,- enabled: true,- condition: 'user_id == "test"',- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- {- id: 'bp-3',- repository: 'PostHog/frontend',- filename: 'capture_event.py',- line_number: 100,- enabled: true,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- ]-- const mockInstances: BreakpointInstance[] = [- {- id: 'inst-1',- lineNumber: 100,- filename: 'capture_event.py',- timestamp: '2024-01-01T10:00:00Z',- variables: { user_id: 'user-123', event: 'pageview' },- breakpoint_id: 'bp-1',- },- {- id: 'inst-2',- lineNumber: 200,- filename: 'capture_event.py',- timestamp: '2024-01-01T10:01:00Z',- variables: { user_id: 'user-456', event: 'click' },- breakpoint_id: 'bp-2',- },- ]-- beforeEach(() => {- jest.useFakeTimers()- // lib/api is automocked, so api.get resolves undefined unless a test overrides it —- // give loaders a benign default so mount-time loads don't crash- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- initKeaTests()- })-- afterEach(() => {- logic?.unmount()- jest.clearAllTimers()- jest.useRealTimers()- jest.clearAllMocks()- })-- describe('initialization', () => {- it('mounts successfully with default values', async () => {- logic = liveDebuggerLogic()- logic.mount()-- // Wait for initial load actions (they won't fetch data without a selected file)- await expectLogic(logic).toDispatchActions(['startPollingBreakpoints'])-- expect(logic.values).toMatchObject({- currentRepository: 'PostHog/posthog',- selectedFilePath: '',- selectedInstanceId: null,- selectedLineForHits: null,- breakpoints: [],- breakpointInstances: [],- })- })-- it('starts polling on mount and loads data when file is selected', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['startPollingBreakpoints'])-- // Select a file to trigger data loading- logic.actions.setSelectedFilePath('test.py')-- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess', 'loadBreakpointInstancesSuccess'])-- expect(api.get).toHaveBeenCalledWith(- `api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/?repository=PostHog%2Fposthog&filename=test.py`- )- })-- it('stops polling on unmount', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- const clearIntervalSpy = jest.spyOn(global, 'clearInterval')-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- await expectLogic(logic, () => {- logic.actions.stopPollingBreakpoints()- }).toDispatchActions(['stopPollingBreakpoints'])-- expect(clearIntervalSpy).toHaveBeenCalled()- })- })-- describe('loaders', () => {- it('loads breakpoints from API when repository and file are set', async () => {- // Mock both breakpoints and instances loading- const mockGet = jest.spyOn(api, 'get')- mockGet.mockImplementation((url: string) => {- if (url.includes('breakpoint_hits')) {- // Return empty hits- return Promise.resolve({ results: [], count: 0, has_more: false })- }- // Return breakpoints- return Promise.resolve({ results: mockBreakpoints, count: mockBreakpoints.length, has_more: false })- })-- logic = liveDebuggerLogic()- logic.mount()-- // Wait for mount to complete (first loadBreakpoints that returns [])- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- // Now set file path - the listener will automatically call loadBreakpoints- await expectLogic(logic, () => {- logic.actions.setSelectedFilePath('capture_event.py')- })- .toDispatchActions(['setSelectedFilePath', 'loadBreakpoints', 'loadBreakpointsSuccess'])- .toMatchValues({- breakpoints: mockBreakpoints,- breakpointsLoading: false,- })- })-- it('loads breakpoint instances from API with filtered breakpoint IDs', async () => {- // Mock for loading breakpoints (returns breakpoints with IDs)- const mockGet = jest.spyOn(api, 'get')- mockGet.mockImplementation((url: string) => {- if (url.includes('live_debugger_breakpoints/breakpoint_hits')) {- return Promise.resolve({ results: mockInstances, count: mockInstances.length, has_more: false })- }- return Promise.resolve({ results: mockBreakpoints, count: mockBreakpoints.length, has_more: false })- })-- logic = liveDebuggerLogic()- logic.mount()-- logic.actions.setSelectedFilePath('capture_event.py')-- // Wait for both breakpoints and instances to load- await expectLogic(logic)- .toDispatchActions(['loadBreakpointsSuccess', 'loadBreakpointInstancesSuccess'])- .toMatchValues({- breakpointInstances: mockInstances,- breakpointInstancesLoading: false,- })-- // Should be called with breakpoint IDs from loaded breakpoints- expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('breakpoint_hits/?breakpoint_ids='))- })-- it('handles missing results field in API response', async () => {- jest.spyOn(api, 'get').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- logic.actions.setSelectedFilePath('test.py')-- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess']).toMatchValues({- breakpoints: [],- })- })- })-- describe('toggle breakpoint', () => {- it('creates a new breakpoint when it does not exist', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- jest.spyOn(api, 'create').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('test.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- await expectLogic(logic, () => {- logic.actions.toggleBreakpoint('test.py', 50, 'PostHog/posthog')- }).toDispatchActions(['toggleBreakpoint', 'loadBreakpoints', 'loadBreakpointInstances'])-- expect(api.create).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/`, {- repository: 'PostHog/posthog',- filename: 'test.py',- line_number: 50,- enabled: true,- })- })-- it('deletes an existing breakpoint when it exists', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints,- count: mockBreakpoints.length,- has_more: false,- })- jest.spyOn(api, 'delete').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('capture_event.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- await expectLogic(logic, () => {- logic.actions.toggleBreakpoint('capture_event.py', 100, 'PostHog/posthog')- }).toDispatchActions(['toggleBreakpoint'])-- expect(api.delete).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/bp-1/`)- })-- it('only deletes breakpoint with matching repository', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints,- count: mockBreakpoints.length,- has_more: false,- })- jest.spyOn(api, 'create').mockResolvedValue({})- jest.spyOn(api, 'delete').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('capture_event.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- // Same file/line but different repository - should create, not delete- await expectLogic(logic, () => {- logic.actions.toggleBreakpoint('capture_event.py', 100, 'PostHog/backend')- }).toDispatchActions(['toggleBreakpoint'])-- expect(api.delete).not.toHaveBeenCalled()- expect(api.create).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/`, {- repository: 'PostHog/backend',- filename: 'capture_event.py',- line_number: 100,- enabled: true,- })- })-- it('toggleBreakpointForFile works the same as toggleBreakpoint', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- jest.spyOn(api, 'create').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('test.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- await expectLogic(logic, () => {- logic.actions.toggleBreakpointForFile('test.py', 50, 'PostHog/posthog')- }).toDispatchActions(['toggleBreakpointForFile', 'loadBreakpoints', 'loadBreakpointInstances'])-- expect(api.create).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/`, {- repository: 'PostHog/posthog',- filename: 'test.py',- line_number: 50,- enabled: true,- })- })- })-- describe('clear all breakpoints', () => {- it('deletes all breakpoints via Promise.all', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints,- count: mockBreakpoints.length,- has_more: false,- })- jest.spyOn(api, 'delete').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('capture_event.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- await expectLogic(logic, () => {- logic.actions.clearAllBreakpoints()- }).toDispatchActions(['clearAllBreakpoints', 'loadBreakpoints', 'loadBreakpointInstances'])-- expect(api.delete).toHaveBeenCalledTimes(3)- expect(api.delete).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/bp-1/`)- expect(api.delete).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/bp-2/`)- expect(api.delete).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/bp-3/`)- })-- it('handles empty breakpoints array gracefully', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- jest.spyOn(api, 'delete').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints (empty result)- logic.actions.setSelectedFilePath('test.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- await expectLogic(logic, () => {- logic.actions.clearAllBreakpoints()- }).toDispatchActions(['clearAllBreakpoints'])-- expect(api.delete).not.toHaveBeenCalled()- })- })-- describe('polling', () => {- it('startPollingBreakpoints loads data immediately and sets up interval', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- const setIntervalSpy = jest.spyOn(global, 'setInterval')-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions([- 'startPollingBreakpoints',- 'loadBreakpoints',- 'loadBreakpointInstances',- ])-- expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 15000)- })-- it('polling interval loads data every 15 seconds', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- // Initial load- expect(api.get).toHaveBeenCalledTimes(2)-- // Advance 15 seconds- jest.advanceTimersByTime(15000)- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- // Should have called 2 more times (breakpoints + instances)- expect(api.get).toHaveBeenCalledTimes(4)-- // Advance another 15 seconds- jest.advanceTimersByTime(15000)- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- expect(api.get).toHaveBeenCalledTimes(6)- })-- it('stopPollingBreakpoints clears the interval', async () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- const clearIntervalSpy = jest.spyOn(global, 'clearInterval')-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpoints'])-- logic.actions.stopPollingBreakpoints()-- expect(clearIntervalSpy).toHaveBeenCalled()- })- })-- describe('instance tracking', () => {- it('markInstanceAsOld adds instance ID to seenInstanceIds', () => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })-- logic = liveDebuggerLogic()- logic.mount()-- logic.actions.markInstanceAsOld('inst-1')-- expect(logic.values.seenInstanceIds.has('inst-1')).toBe(true)- })-- it('loadBreakpointInstancesSuccess auto-marks new instances as old after 2s', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockInstances,- count: mockInstances.length,- has_more: false,- })-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpointInstancesSuccess'])-- // Initially not marked as old- expect(logic.values.seenInstanceIds.has('inst-1')).toBe(false)- expect(logic.values.seenInstanceIds.has('inst-2')).toBe(false)-- // Advance 2 seconds- jest.advanceTimersByTime(2000)-- // Now should be marked as old- expect(logic.values.seenInstanceIds.has('inst-1')).toBe(true)- expect(logic.values.seenInstanceIds.has('inst-2')).toBe(true)- })-- it('updates previousInstanceIds on load', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockInstances,- count: mockInstances.length,- has_more: false,- })-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpointInstancesSuccess'])-- expect(logic.values.previousInstanceIds.has('inst-1')).toBe(true)- expect(logic.values.previousInstanceIds.has('inst-2')).toBe(true)- })-- it('only auto-marks new instances not already in seenInstanceIds', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockInstances,- count: mockInstances.length,- has_more: false,- })-- logic = liveDebuggerLogic()- logic.mount()-- // Mark inst-1 as already seen- logic.actions.markInstanceAsOld('inst-1')-- await expectLogic(logic).toDispatchActions(['loadBreakpointInstancesSuccess'])-- // Advance 2 seconds- jest.advanceTimersByTime(2000)-- // inst-1 was already seen, inst-2 is new- expect(logic.values.seenInstanceIds.has('inst-1')).toBe(true)- expect(logic.values.seenInstanceIds.has('inst-2')).toBe(true)- })- })-- describe('reducers', () => {- beforeEach(() => {- jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0, has_more: false })- logic = liveDebuggerLogic()- logic.mount()- })-- it('setCurrentRepository updates repository state', () => {- logic.actions.setCurrentRepository('PostHog/frontend')-- expect(logic.values.currentRepository).toBe('PostHog/frontend')- })-- it('setSelectedFilePath updates file selection', () => {- logic.actions.setSelectedFilePath('capture_event.py')-- expect(logic.values.selectedFilePath).toBe('capture_event.py')- })-- it('selectInstance updates selected instance ID', () => {- logic.actions.selectInstance('inst-1')-- expect(logic.values.selectedInstanceId).toBe('inst-1')-- logic.actions.selectInstance(null)-- expect(logic.values.selectedInstanceId).toBe(null)- })-- it('showHitsForLine updates selected line', () => {- logic.actions.showHitsForLine(100)-- expect(logic.values.selectedLineForHits).toBe(100)-- logic.actions.showHitsForLine(null)-- expect(logic.values.selectedLineForHits).toBe(null)- })- })-- describe('selectors', () => {- beforeEach(async () => {- jest.spyOn(api, 'get').mockImplementation((url) => {- if (url.includes('breakpoint_hits')) {- return Promise.resolve({- results: mockInstances,- count: mockInstances.length,- has_more: false,- })- }- return Promise.resolve({ results: mockBreakpoints, count: mockBreakpoints.length, has_more: false })- })-- logic = liveDebuggerLogic()- logic.mount()-- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess', 'loadBreakpointInstancesSuccess'])- })-- describe('selectedInstance', () => {- it('returns instance matching selectedInstanceId', () => {- logic.actions.selectInstance('inst-1')-- expect(logic.values.selectedInstance).toEqual(mockInstances[0])- })-- it('returns null when no instance is selected', () => {- expect(logic.values.selectedInstance).toBe(null)- })-- it('returns null when selectedInstanceId does not exist', () => {- logic.actions.selectInstance('non-existent')-- expect(logic.values.selectedInstance).toBe(null)- })- })-- describe('breakpointLines', () => {- it('returns sorted line numbers for selected file', async () => {- // Mock API to return only breakpoints for the current repo when file is selected- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints.filter(- (bp) => bp.repository === 'PostHog/posthog' && bp.filename === 'capture_event.py'- ),- count: 2,- has_more: false,- })-- logic = liveDebuggerLogic()- logic.mount()-- logic.actions.setSelectedFilePath('capture_event.py')-- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- expect(logic.values.breakpointLines).toEqual([100, 200])- })-- it('returns empty array when no file is selected', async () => {- logic = liveDebuggerLogic()- logic.mount()-- // Without a selected file, no breakpoints are loaded- expect(logic.values.breakpointLines).toEqual([])- })- })-- describe('breakpointsByLine', () => {- it('returns breakpoints indexed by line number for selected file', async () => {- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints.filter(- (bp) => bp.repository === 'PostHog/posthog' && bp.filename === 'capture_event.py'- ),- count: 2,- has_more: false,- })-- logic = liveDebuggerLogic()- logic.mount()-- logic.actions.setSelectedFilePath('capture_event.py')-- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- const byLine = logic.values.breakpointsByLine-- expect(byLine[100]).toBeTruthy()- expect(byLine[200]).toBeTruthy()- expect(byLine[100].id).toBe('bp-1')- expect(byLine[200].id).toBe('bp-2')- })-- it('returns empty object when no file is selected', async () => {- logic = liveDebuggerLogic()- logic.mount()-- // Without a selected file, no breakpoints are loaded- expect(logic.values.breakpointsByLine).toEqual({})- })- })-- describe('instancesByLine', () => {- it('groups instances by line number for selected file', () => {- logic.actions.setSelectedFilePath('capture_event.py')-- const byLine = logic.values.instancesByLine-- expect(byLine[100]).toHaveLength(1)- expect(byLine[200]).toHaveLength(1)- expect(byLine[100][0].id).toBe('inst-1')- expect(byLine[200][0].id).toBe('inst-2')- })-- it('returns all instances grouped by line when no file is selected', () => {- const byLine = logic.values.instancesByLine-- expect(byLine[100]).toHaveLength(1)- expect(byLine[200]).toHaveLength(1)- })- })-- describe('newInstanceIds', () => {- it('returns instance IDs not in seenInstanceIds', () => {- const newIds = logic.values.newInstanceIds-- expect(newIds.has('inst-1')).toBe(true)- expect(newIds.has('inst-2')).toBe(true)- })-- it('excludes instance IDs already in seenInstanceIds', () => {- logic.actions.markInstanceAsOld('inst-1')-- const newIds = logic.values.newInstanceIds-- expect(newIds.has('inst-1')).toBe(false)- expect(newIds.has('inst-2')).toBe(true)- })- })-- describe('hitCountsByLine', () => {- it('counts hits per line for selected file', () => {- logic.actions.setSelectedFilePath('capture_event.py')-- const counts = logic.values.hitCountsByLine-- expect(counts[100]).toBe(1)- expect(counts[200]).toBe(1)- })-- it('counts all hits when no file is selected', () => {- const counts = logic.values.hitCountsByLine-- expect(counts[100]).toBe(1)- expect(counts[200]).toBe(1)- })- })-- describe('newHitsByLine', () => {- it('returns line numbers with new unseen hits', () => {- const newHits = logic.values.newHitsByLine-- expect(newHits.has(100)).toBe(true)- expect(newHits.has(200)).toBe(true)- })-- it('excludes lines with only seen hits', () => {- logic.actions.markInstanceAsOld('inst-1')- logic.actions.markInstanceAsOld('inst-2')-- const newHits = logic.values.newHitsByLine-- expect(newHits.size).toBe(0)- })-- it('filters by selected file', () => {- logic.actions.setSelectedFilePath('other_file.py')-- const newHits = logic.values.newHitsByLine-- expect(newHits.size).toBe(0)- })- })-- describe('hitsForSelectedLine', () => {- it('returns instances for selected line', () => {- logic.actions.showHitsForLine(100)-- const hits = logic.values.hitsForSelectedLine-- expect(hits).toHaveLength(1)- expect(hits[0].id).toBe('inst-1')- })-- it('returns empty array when no line is selected', () => {- expect(logic.values.hitsForSelectedLine).toEqual([])- })-- it('returns empty array when selected line has no hits', () => {- logic.actions.showHitsForLine(999)-- expect(logic.values.hitsForSelectedLine).toEqual([])- })- })- })-- describe('multi-repository edge cases', () => {- it('distinguishes breakpoints by repository when toggling', async () => {- // Mock breakpoints for PostHog/posthog repo only- jest.spyOn(api, 'get').mockResolvedValue({- results: mockBreakpoints.filter((bp) => bp.repository === 'PostHog/posthog'),- count: 2,- has_more: false,- })- jest.spyOn(api, 'delete').mockResolvedValue({})-- logic = liveDebuggerLogic()- logic.mount()-- // Set file to load breakpoints- logic.actions.setSelectedFilePath('capture_event.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- // Delete PostHog/posthog breakpoint- await expectLogic(logic, () => {- logic.actions.toggleBreakpoint('capture_event.py', 100, 'PostHog/posthog')- }).toDispatchActions(['toggleBreakpoint'])-- expect(api.delete).toHaveBeenCalledWith(`api/projects/${MOCK_TEAM_ID}/live_debugger_breakpoints/bp-1/`)- })- })-- describe('file switching', () => {- it('clears breakpoint display when switching files', async () => {- const mockGet = jest.spyOn(api, 'get')-- // Backend correctly returns different breakpoints for different files- mockGet.mockImplementation((url: string) => {- if (url.includes('breakpoint_hits')) {- return Promise.resolve({ results: [], count: 0, has_more: false })- }- if (url.includes('filename=capture_event.py')) {- // File A has 2 breakpoints- return Promise.resolve({- results: mockBreakpoints.filter(- (bp) => bp.filename === 'capture_event.py' && bp.repository === 'PostHog/posthog'- ),- count: 2,- has_more: false,- })- }- if (url.includes('filename=other_file.py')) {- // File B has NO breakpoints- return Promise.resolve({ results: [], count: 0, has_more: false })- }- return Promise.resolve({ results: [], count: 0, has_more: false })- })-- logic = liveDebuggerLogic()- logic.mount()-- // Load file A which has breakpoints- logic.actions.setSelectedFilePath('capture_event.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- expect(logic.values.breakpointLines).toEqual([100, 200])- expect(logic.values.breakpoints.length).toBe(2)-- // Switch to file B which has NO breakpoints- logic.actions.setSelectedFilePath('other_file.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- // The breakpoints should be cleared- expect(logic.values.breakpoints).toEqual([])- expect(logic.values.breakpointLines).toEqual([])- })-- it('replaces breakpoints when switching between files with different breakpoints', async () => {- const fileABreakpoints: Breakpoint[] = [- {- id: 'bp-a1',- repository: 'PostHog/posthog',- filename: 'fileA.py',- line_number: 10,- enabled: true,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- {- id: 'bp-a2',- repository: 'PostHog/posthog',- filename: 'fileA.py',- line_number: 20,- enabled: true,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- ]-- const fileBBreakpoints: Breakpoint[] = [- {- id: 'bp-b1',- repository: 'PostHog/posthog',- filename: 'fileB.py',- line_number: 30,- enabled: true,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- ]-- const mockGet = jest.spyOn(api, 'get')- mockGet.mockImplementation((url: string) => {- if (url.includes('breakpoint_hits')) {- return Promise.resolve({ results: [], count: 0, has_more: false })- }- if (url.includes('filename=fileA.py')) {- return Promise.resolve({ results: fileABreakpoints, count: 2, has_more: false })- }- if (url.includes('filename=fileB.py')) {- return Promise.resolve({ results: fileBBreakpoints, count: 1, has_more: false })- }- return Promise.resolve({ results: [], count: 0, has_more: false })- })-- logic = liveDebuggerLogic()- logic.mount()-- // Select fileA- logic.actions.setSelectedFilePath('fileA.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- expect(logic.values.breakpointLines).toEqual([10, 20])- expect(logic.values.breakpoints.map((bp) => bp.id)).toEqual(['bp-a1', 'bp-a2'])-- // Switch to fileB- logic.actions.setSelectedFilePath('fileB.py')- await expectLogic(logic).toDispatchActions(['loadBreakpointsSuccess'])-- expect(logic.values.breakpointLines).toEqual([30])- expect(logic.values.breakpoints.map((bp) => bp.id)).toEqual(['bp-b1'])- })- })-})diff --git a/products/live_debugger/frontend/liveDebuggerLogic.ts b/products/live_debugger/frontend/liveDebuggerLogic.tsdeleted file mode 100644index 73d9fb51d94c..000000000000--- a/products/live_debugger/frontend/liveDebuggerLogic.ts+++ /dev/null@@ -1,486 +0,0 @@-import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'--import api from 'lib/api'-import { teamLogic } from 'scenes/teamLogic'--export interface Breakpoint {- id: string- repository: string | null- filename: string- line_number: number- enabled: boolean- condition?: string- created_at: string- updated_at: string-}--export interface BreakpointInstance {- id: string- lineNumber: number- functionName?: string- timestamp: string- variables: Record<string, any>- stackTrace?: any[]- breakpoint_id?: string- filename: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface liveDebuggerLogicValues {- currentProjectId: number | string // teamLogic- breakpointInstances: BreakpointInstance[]- breakpointInstancesLoading: boolean- breakpointLines: number[]- breakpoints: Breakpoint[]- breakpointsByLine: Record<number, Breakpoint>- breakpointsLoading: boolean- currentRepository: string- hitCountsByLine: Record<number, number>- hitsForSelectedLine: BreakpointInstance[]- instancesByLine: Record<number, BreakpointInstance[]>- newHitsByLine: Set<number>- newInstanceIds: Set<string>- previousInstanceIds: Set<string>- seenInstanceIds: Set<string>- selectedFilePath: string- selectedInstance: BreakpointInstance | null- selectedInstanceId: string | null- selectedLineForHits: number | null- visibleBreakpointIds: string[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface liveDebuggerLogicActions {- clearAllBreakpoints: () => {- value: true- }- loadBreakpointInstances: () => any- loadBreakpointInstancesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadBreakpointInstancesSuccess: (- breakpointInstances: BreakpointInstance[],- payload?: any- ) => {- breakpointInstances: BreakpointInstance[]- payload?: any- }- loadBreakpoints: () => any- loadBreakpointsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadBreakpointsSuccess: (- breakpoints: Breakpoint[],- payload?: any- ) => {- breakpoints: Breakpoint[]- payload?: any- }- markInstanceAsOld: (instanceId: string) => {- instanceId: string- }- selectInstance: (instanceId: string | null) => {- instanceId: string | null- }- setCurrentRepository: (repository: string) => {- repository: string- }- setHoveredLine: (lineNumber: number | null) => {- lineNumber: number | null- }- setSelectedFilePath: (filePath: string) => {- filePath: string- }- showHitsForLine: (lineNumber: number | null) => {- lineNumber: number | null- }- startPollingBreakpoints: () => {- value: true- }- stopPollingBreakpoints: () => {- value: true- }- toggleBreakpoint: (- filename: string,- lineNumber: number,- repository: string- ) => {- filename: string- lineNumber: number- repository: string- }- toggleBreakpointForFile: (- filename: string,- lineNumber: number,- repository: string- ) => {- filename: string- lineNumber: number- repository: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface liveDebuggerLogicMeta {- __keaTypeGenInternalSelectorTypes: {- selectedInstance: (- selectedInstanceId: string | null,- breakpointInstances: BreakpointInstance[]- ) => BreakpointInstance | null- visibleBreakpointIds: (breakpoints: Breakpoint[]) => string[]- breakpointLines: (breakpoints: Breakpoint[], selectedFilePath: string) => number[]- breakpointsByLine: (breakpoints: Breakpoint[], selectedFilePath: string) => Record<number, Breakpoint>- instancesByLine: (- breakpointInstances: BreakpointInstance[],- selectedFilePath: string- ) => Record<number, BreakpointInstance[]>- newInstanceIds: (breakpointInstances: BreakpointInstance[], seenInstanceIds: Set<string>) => Set<string>- hitCountsByLine: (breakpointInstances: BreakpointInstance[], selectedFilePath: string) => Record<number, number>- newHitsByLine: (- breakpointInstances: BreakpointInstance[],- seenInstanceIds: Set<string>,- selectedFilePath: string- ) => Set<number>- hitsForSelectedLine: (- selectedLineForHits: number | null,- instancesByLine: Record<number, BreakpointInstance[]>- ) => BreakpointInstance[]- }-}--export type liveDebuggerLogicType = MakeLogicType<- liveDebuggerLogicValues,- liveDebuggerLogicActions,- Record<string, any>,- liveDebuggerLogicMeta->--export const liveDebuggerLogic = kea<liveDebuggerLogicType>([- path(['products', 'live_debugger', 'frontend', 'liveDebuggerLogic']),- connect(() => ({ values: [teamLogic, ['currentProjectId']] })),-- actions({- toggleBreakpoint: (filename: string, lineNumber: number, repository: string) => ({- filename,- lineNumber,- repository,- }),- toggleBreakpointForFile: (filename: string, lineNumber: number, repository: string) => ({- filename,- lineNumber,- repository,- }),- setHoveredLine: (lineNumber: number | null) => ({ lineNumber }),- selectInstance: (instanceId: string | null) => ({ instanceId }),- clearAllBreakpoints: true,- markInstanceAsOld: (instanceId: string) => ({ instanceId }),- showHitsForLine: (lineNumber: number | null) => ({ lineNumber }),- startPollingBreakpoints: true,- stopPollingBreakpoints: true,- setSelectedFilePath: (filePath: string) => ({ filePath }),- setCurrentRepository: (repository: string) => ({ repository }),- }),-- loaders(({ values }) => ({- breakpoints: [- [] as Breakpoint[],- {- loadBreakpoints: async () => {- // Only load when both repository and file are selected- if (!values.currentRepository || !values.selectedFilePath) {- return []- }-- const params = new URLSearchParams()- params.append('repository', values.currentRepository)- params.append('filename', values.selectedFilePath)-- const queryString = params.toString()- const url = `api/projects/${values.currentProjectId}/live_debugger_breakpoints/?${queryString}`- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.- const response = await api.get(url)- return response.results || []- },- },- ],- breakpointInstances: [- [] as BreakpointInstance[],- {- loadBreakpointInstances: async () => {- // Filter hits by currently loaded breakpoints (for efficiency)- const breakpointIds = values.breakpoints.map((bp) => bp.id)-- const params = new URLSearchParams()- breakpointIds.forEach((id: string) => params.append('breakpoint_ids', id))-- const queryString = params.toString()- const url = `api/projects/${values.currentProjectId}/live_debugger_breakpoints/breakpoint_hits/${queryString ? `?${queryString}` : ''}`- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.- const response = await api.get(url)- return response.results || []- },- },- ],- })),-- reducers({- currentRepository: [- 'PostHog/posthog' as string,- {- setCurrentRepository: (_, { repository }) => repository,- },- ],- selectedFilePath: [- '',- {- setSelectedFilePath: (_, { filePath }) => filePath,- },- ],- selectedInstanceId: [- null as string | null,- {- selectInstance: (_, { instanceId }) => instanceId,- },- ],- seenInstanceIds: [- new Set<string>(),- {- markInstanceAsOld: (state, { instanceId }) => {- return new Set([...state, instanceId])- },- loadBreakpointInstancesSuccess: (state) => {- const newState = new Set(state)- return newState- },- },- ],- previousInstanceIds: [- new Set<string>(),- {- loadBreakpointInstancesSuccess: (_, { breakpointInstances }) => {- return new Set(breakpointInstances.map((instance) => instance.id))- },- },- ],- selectedLineForHits: [- null as number | null,- {- showHitsForLine: (_, { lineNumber }) => lineNumber,- },- ],- }),-- listeners(({ actions, values, cache }) => ({- loadBreakpointInstancesSuccess: ({ breakpointInstances }) => {- const newIds = breakpointInstances- .map((instance) => instance.id)- .filter((id) => !values.seenInstanceIds.has(id))-- if (newIds.length > 0) {- setTimeout(() => {- newIds.forEach((id) => actions.markInstanceAsOld(id))- }, 2000)- }- },- toggleBreakpoint: async ({ filename, lineNumber, repository }) => {- const existingBreakpoint = Array.isArray(values.breakpoints)- ? values.breakpoints.find(- (bp) => bp.line_number === lineNumber && bp.filename === filename && bp.repository === repository- )- : undefined-- if (existingBreakpoint) {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. liveDebuggerBreakpointsDestroy() from 'products/live_debugger/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- await api.delete(- `api/projects/${values.currentProjectId}/live_debugger_breakpoints/${existingBreakpoint.id}/`- )- } else {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use liveDebuggerBreakpointsCreate() from 'products/live_debugger/frontend/generated/api' instead.- await api.create(`api/projects/${values.currentProjectId}/live_debugger_breakpoints/`, {- repository,- filename,- line_number: lineNumber,- enabled: true,- })- }-- actions.loadBreakpoints()- actions.loadBreakpointInstances()- },- toggleBreakpointForFile: async ({ filename, lineNumber, repository }) => {- const existingBreakpoint = Array.isArray(values.breakpoints)- ? values.breakpoints.find(- (bp) => bp.line_number === lineNumber && bp.filename === filename && bp.repository === repository- )- : undefined-- if (existingBreakpoint) {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. liveDebuggerBreakpointsDestroy() from 'products/live_debugger/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- await api.delete(- `api/projects/${values.currentProjectId}/live_debugger_breakpoints/${existingBreakpoint.id}/`- )- } else {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use liveDebuggerBreakpointsCreate() from 'products/live_debugger/frontend/generated/api' instead.- await api.create(`api/projects/${values.currentProjectId}/live_debugger_breakpoints/`, {- repository,- filename,- line_number: lineNumber,- enabled: true,- })- }-- actions.loadBreakpoints()- actions.loadBreakpointInstances()- },- clearAllBreakpoints: async () => {- if (Array.isArray(values.breakpoints)) {- await Promise.all(- values.breakpoints.map((bp) =>- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. liveDebuggerBreakpointsDestroy() from 'products/live_debugger/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- api.delete(`api/projects/${values.currentProjectId}/live_debugger_breakpoints/${bp.id}/`)- )- )- }-- actions.loadBreakpoints()- actions.loadBreakpointInstances()- },- startPollingBreakpoints: () => {- actions.loadBreakpoints()- actions.loadBreakpointInstances()-- cache.disposables.add(() => {- const interval = setInterval(() => {- actions.loadBreakpoints()- actions.loadBreakpointInstances()- }, 15000)- return () => clearInterval(interval)- }, 'breakpointPolling')- },- stopPollingBreakpoints: () => {- cache.disposables.dispose('breakpointPolling')- },- setCurrentRepository: () => {- // Reload breakpoints when repository changes (only if file is selected)- if (values.selectedFilePath) {- actions.loadBreakpoints()- }- },- setSelectedFilePath: () => {- // Reload breakpoints when file path changes (only if repository is set)- if (values.currentRepository) {- actions.loadBreakpoints()- }- },- loadBreakpointsSuccess: () => {- // Reload instances when breakpoints change (the list of IDs has changed)- actions.loadBreakpointInstances()- },- })),-- selectors({- selectedInstance: [- (s) => [s.selectedInstanceId, s.breakpointInstances],- (selectedId: string | null, instances: BreakpointInstance[]): BreakpointInstance | null =>- instances.find((i) => i.id === selectedId) || null,- ],- visibleBreakpointIds: [- (s) => [s.breakpoints],- (breakpoints: Breakpoint[]): string[] => breakpoints.map((bp) => bp.id),- ],- breakpointLines: [- (s) => [s.breakpoints, s.selectedFilePath],- (breakpoints: Breakpoint[], selectedFilePath: string): number[] => {- if (!Array.isArray(breakpoints) || !selectedFilePath) {- return []- }- return breakpoints- .filter((bp) => bp.filename === selectedFilePath)- .map((bp) => bp.line_number)- .sort((a, b) => a - b)- },- ],- breakpointsByLine: [- (s) => [s.breakpoints, s.selectedFilePath],- (breakpoints: Breakpoint[], selectedFilePath: string): Record<number, Breakpoint> => {- const byLine: Record<number, Breakpoint> = {}- if (Array.isArray(breakpoints) && selectedFilePath) {- breakpoints- .filter((bp) => bp.filename === selectedFilePath)- .forEach((bp) => {- byLine[bp.line_number] = bp- })- }- return byLine- },- ],- instancesByLine: [- (s) => [s.breakpointInstances, s.selectedFilePath],- (instances: BreakpointInstance[], selectedFilePath: string): Record<number, BreakpointInstance[]> => {- const grouped: Record<number, BreakpointInstance[]> = {}- instances- .filter((instance) => !selectedFilePath || instance.filename === selectedFilePath)- .forEach((instance) => {- if (!grouped[instance.lineNumber]) {- grouped[instance.lineNumber] = []- }- grouped[instance.lineNumber].push(instance)- })- return grouped- },- ],- newInstanceIds: [- (s) => [s.breakpointInstances, s.seenInstanceIds],- (instances: BreakpointInstance[], seenIds: Set<string>): Set<string> => {- return new Set(instances.filter((instance) => !seenIds.has(instance.id)).map((instance) => instance.id))- },- ],- hitCountsByLine: [- (s) => [s.breakpointInstances, s.selectedFilePath],- (instances: BreakpointInstance[], selectedFilePath: string): Record<number, number> => {- const counts: Record<number, number> = {}- instances- .filter((instance) => !selectedFilePath || instance.filename === selectedFilePath)- .forEach((instance) => {- counts[instance.lineNumber] = (counts[instance.lineNumber] || 0) + 1- })- return counts- },- ],- newHitsByLine: [- (s) => [s.breakpointInstances, s.seenInstanceIds, s.selectedFilePath],- (instances: BreakpointInstance[], seenIds: Set<string>, selectedFilePath: string): Set<number> => {- const newInstances = instances- .filter((instance) => !seenIds.has(instance.id))- .filter((instance) => !selectedFilePath || instance.filename === selectedFilePath)- return new Set(newInstances.map((instance) => instance.lineNumber))- },- ],- hitsForSelectedLine: [- (s) => [s.selectedLineForHits, s.instancesByLine],- (- selectedLine: number | null,- instancesByLine: Record<number, BreakpointInstance[]>- ): BreakpointInstance[] => {- if (!selectedLine) {- return []- }- return instancesByLine[selectedLine] || []- },- ],- }),-- events(({ actions }) => ({- afterMount: [actions.startPollingBreakpoints],- beforeUnmount: [actions.stopPollingBreakpoints],- })),-])diff --git a/products/live_debugger/frontend/repo_browser/RepositoryBrowser.tsx b/products/live_debugger/frontend/repo_browser/RepositoryBrowser.tsxdeleted file mode 100644index 0e0cd9567a8d..000000000000--- a/products/live_debugger/frontend/repo_browser/RepositoryBrowser.tsx+++ /dev/null@@ -1,108 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonInput } from 'lib/lemon-ui/LemonInput'-import { LemonTree } from 'lib/lemon-ui/LemonTree/LemonTree'--import { CodeLine } from '../CodeLine'-import { liveDebuggerLogic } from '../liveDebuggerLogic'-import { repoBrowserLogic } from './repoBrowserLogic'--export function RepositoryBrowser(): JSX.Element {- const { fileSearchQuery, repositoryTreeLoading, treeData, codeLines, selectedFilePath } =- useValues(repoBrowserLogic)-- const { loadFileContent, setFileSearchQuery } = useActions(repoBrowserLogic)-- const { breakpoints, breakpointsByLine, instancesByLine, hitCountsByLine, newHitsByLine, currentRepository } =- useValues(liveDebuggerLogic)-- const { clearAllBreakpoints, toggleBreakpoint, showHitsForLine, setSelectedFilePath } =- useActions(liveDebuggerLogic)-- return (- <>- <div className="flex-1 border rounded bg-bg-light overflow-hidden flex flex-col">- <div className="p-2 border-b bg-bg-3000">- <span className="font-semibold">Files</span>- </div>- <div className="p-2 border-b">- <LemonInput- type="search"- placeholder="Search files..."- value={fileSearchQuery}- onChange={(value) => setFileSearchQuery(value)}- fullWidth- />- </div>- <div className="flex-1 overflow-auto">- {repositoryTreeLoading ? (- <div className="p-4 text-center text-muted">Loading repository...</div>- ) : treeData.length === 0 ? (- <div className="p-4 text-center text-muted">- {fileSearchQuery ? 'No files found' : 'No Python files in repository'}- </div>- ) : (- <LemonTree- data={treeData}- onFolderClick={() => {}}- onItemClick={(item) => {- if (item?.record?.type === 'file') {- loadFileContent(item.record.fullPath)- setSelectedFilePath(item.record.fullPath)- }- }}- />- )}- </div>- </div>-- <div className="flex-[2] border rounded bg-bg-light overflow-hidden flex flex-col">- <div className="flex items-center justify-between p-2 border-b bg-bg-3000">- <span className="font-semibold">{selectedFilePath ? selectedFilePath : 'Code'}</span>- <LemonButton- size="small"- type="secondary"- onClick={clearAllBreakpoints}- disabled={!breakpoints || breakpoints.length === 0}- >- Clear all breakpoints- </LemonButton>- </div>- <div className="flex-1 overflow-auto font-mono text-xs">- {!codeLines ? (- <div className="flex items-center justify-center h-full text-muted p-4 text-center">- <p>Select a file from the file browser to view its contents and set breakpoints</p>- </div>- ) : (- codeLines.map((line, index) => {- const lineNumber = index + 1- const hasBreakpoint = !!breakpointsByLine[lineNumber]- const hasInstances = !!instancesByLine[lineNumber]?.length- const hitCount = hitCountsByLine[lineNumber] || 0- const hasNewHits = newHitsByLine.has(lineNumber)-- return (- <CodeLine- key={index}- line={line}- lineNumber={lineNumber}- hasBreakpoint={hasBreakpoint}- hasInstances={hasInstances}- hitCount={hitCount}- hasNewHits={hasNewHits}- onClick={() => {- if (selectedFilePath) {- toggleBreakpoint(selectedFilePath, lineNumber, currentRepository)- }- }}- onHitCountClick={() => showHitsForLine(lineNumber)}- />- )- })- )}- </div>- </div>- </>- )-}diff --git a/products/live_debugger/frontend/repo_browser/githubClient.ts b/products/live_debugger/frontend/repo_browser/githubClient.tsdeleted file mode 100644index 63955096ba3b..000000000000--- a/products/live_debugger/frontend/repo_browser/githubClient.ts+++ /dev/null@@ -1,69 +0,0 @@-// Default repository configuration-export const DEFAULT_OWNER = 'PostHog'-export const DEFAULT_REPO = 'posthog'-export const DEFAULT_BRANCH = 'master'--export interface RepositoryConfig {- owner: string- repo: string- branch: string-}--export interface GitHubTreeItem {- path: string- mode: string- type: 'blob' | 'tree'- sha: string- size?: number- url: string-}--export interface GitHubTreeResponse {- sha: string- url: string- tree: GitHubTreeItem[]- truncated: boolean-}--export interface GitHubFileContent {- name: string- path: string- sha: string- size: number- url: string- html_url: string- git_url: string- download_url: string- type: string- content: string- encoding: string-}--export async function loadRepositoryTree(- owner: string = DEFAULT_OWNER,- repo: string = DEFAULT_REPO,- branch: string = DEFAULT_BRANCH-): Promise<GitHubTreeResponse> {- const branchResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/branches/${branch}`)- const branchData = await branchResponse.json()- const sha = branchData.commit.sha-- const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`)-- return (await response.json()) as GitHubTreeResponse-}--export async function loadFileContent(- filePath: string,- owner: string = DEFAULT_OWNER,- repo: string = DEFAULT_REPO-): Promise<GitHubFileContent> {- const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${filePath}`)- const fileContent = (await response.json()) as GitHubFileContent-- if (fileContent.encoding === 'base64') {- fileContent.content = atob(fileContent.content)- }-- return fileContent-}diff --git a/products/live_debugger/frontend/repo_browser/repoBrowserLogic.ts b/products/live_debugger/frontend/repo_browser/repoBrowserLogic.tsdeleted file mode 100644index 09da4963e95b..000000000000--- a/products/live_debugger/frontend/repo_browser/repoBrowserLogic.ts+++ /dev/null@@ -1,266 +0,0 @@-import _Fuse from 'fuse.js'-import { MakeLogicType, actions, events, kea, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'--import type { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'-import { createFuse } from 'lib/utils/fuseSearch'--import {- GitHubFileContent,- GitHubTreeItem,- GitHubTreeResponse,- loadFileContent,- loadRepositoryTree,-} from './githubClient'--// Hack so kea-typegen picks up the type-export type Fuse<T> = _Fuse<T>--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface repoBrowserLogicValues {- codeLines: string[]- fileContent: GitHubFileContent | null- fileContentLoading: boolean- fileSearchQuery: string- fuzzyIndex: Fuse<GitHubTreeItem>- relevantFiles: GitHubTreeItem[]- repositoryTree: GitHubTreeResponse | null- repositoryTreeLoading: boolean- selectedFilePath: string | null- treeData: TreeDataItem[]- visibleFilesAndFolders: GitHubTreeItem[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface repoBrowserLogicActions {- loadFileContent: (filePath: string) => {- filePath: string- }- loadFileContentFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadFileContentSuccess: (- fileContent: GitHubFileContent,- payload?: {- filePath: string- }- ) => {- fileContent: GitHubFileContent- payload?: {- filePath: string- }- }- loadRepositoryTree: () => any- loadRepositoryTreeFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadRepositoryTreeSuccess: (- repositoryTree: GitHubTreeResponse,- payload?: any- ) => {- repositoryTree: GitHubTreeResponse- payload?: any- }- setExpandedFolderPaths: (paths: string[]) => {- paths: string[]- }- setFileSearchQuery: (query: string) => {- query: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface repoBrowserLogicMeta {- __keaTypeGenInternalSelectorTypes: {- codeLines: (fileContent: GitHubFileContent | null) => string[]- relevantFiles: (repositoryTree: GitHubTreeResponse | null) => GitHubTreeItem[]- fuzzyIndex: (relevantFiles: GitHubTreeItem[]) => Fuse<GitHubTreeItem>- visibleFilesAndFolders: (- fileSearchQuery: string,- relevantFiles: GitHubTreeItem[],- fuzzyIndex: Fuse<GitHubTreeItem>- ) => GitHubTreeItem[]- treeData: (visibleFilesAndFolders: GitHubTreeItem[]) => TreeDataItem[]- }-}--export type repoBrowserLogicType = MakeLogicType<- repoBrowserLogicValues,- repoBrowserLogicActions,- Record<string, any>,- repoBrowserLogicMeta->--export const repoBrowserLogic = kea<repoBrowserLogicType>([- path(['products', 'live_debugger', 'frontend', 'repo_browser', 'repoBrowserLogic']),-- actions({- setFileSearchQuery: (query: string) => ({ query }),- loadFileContent: (filePath: string) => ({ filePath }),- setExpandedFolderPaths: (paths: string[]) => ({ paths }),- }),-- loaders(() => ({- repositoryTree: [null as GitHubTreeResponse | null, { loadRepositoryTree: async () => loadRepositoryTree() }],- fileContent: [- null as GitHubFileContent | null,- { loadFileContent: async ({ filePath }) => loadFileContent(filePath) },- ],- })),-- reducers({- fileSearchQuery: [- '',- {- setFileSearchQuery: (_, { query }) => query,- },- ],- repositoryTree: [- null as GitHubTreeResponse | null,- {- repositoryTreeSuccess: (_, { repositoryTree }) => repositoryTree,- },- ],- fileContent: [- null as GitHubFileContent | null,- {- fileContentSuccess: (_, { fileContent }) => fileContent,- },- ],- selectedFilePath: [- null as string | null,- {- loadFileContent: (_, { filePath }) => filePath,- },- ],- }),-- selectors({- codeLines: [- (s) => [s.fileContent],- (fileContent: GitHubFileContent | null): string[] => {- if (!fileContent) {- return []- }-- return fileContent.content.split('\n')- },- ],- relevantFiles: [- (s) => [s.repositoryTree],- (tree: GitHubTreeResponse): GitHubTreeItem[] => {- if (!tree) {- return []- }-- return tree.tree.filter(- (item) => item.type === 'tree' || (item.type === 'blob' && item.path.endsWith('.py'))- )- },- ],- fuzzyIndex: [- (s) => [s.relevantFiles],- (relevantFiles: GitHubTreeItem[]): Fuse<GitHubTreeItem> => {- return createFuse(relevantFiles, {- keys: ['path', 'name'],- threshold: 0.3,- })- },- ],- visibleFilesAndFolders: [- (s) => [s.fileSearchQuery, s.relevantFiles, s.fuzzyIndex],- (- fileSearchQuery: string,- relevantFiles: GitHubTreeItem[],- fuzzyIndex: Fuse<GitHubTreeItem>- ): GitHubTreeItem[] => {- if (fileSearchQuery) {- return fuzzyIndex.search(fileSearchQuery).map((r) => r.item)- }-- return relevantFiles- },- ],- treeData: [- (s) => [s.visibleFilesAndFolders],- (visibleFilesAndFolders: GitHubTreeItem[]): TreeDataItem[] => {- if (!visibleFilesAndFolders) {- return []- }-- // NOTE(Marce): The assumption is a folder will always appear before- // the containing items in the return data. It seems to hold.- const folders = new Map<string, TreeDataItem>()- const rootElements: TreeDataItem[] = []-- visibleFilesAndFolders.forEach((item: GitHubTreeItem) => {- const { pathPrefix, filename, fullPath } = extractPathAndFilename(item)-- const recordType = item.type === 'tree' ? 'folder' : 'file'- const children = item.type === 'tree' ? [] : undefined-- const parent = folders.get(pathPrefix)- const newNode: TreeDataItem = {- id: item.sha,- name: filename,- record: { type: recordType, fullPath: fullPath },- children,- }-- if (parent) {- // NOTE(Marce): We initialize all folders with an empty- // childrens array, so this is safe to do here.- parent.children!.push(newNode)- parent.children?.sort(filesSortFn)- } else {- rootElements.push(newNode)- }-- if (item.type === 'tree') {- folders.set(fullPath, newNode)- }- })-- rootElements.sort(filesSortFn)- return rootElements- },- ],- }),-- events(({ actions }) => ({- afterMount: [actions.loadRepositoryTree],- })),-])--function extractPathAndFilename(item: GitHubTreeItem): { pathPrefix: string; filename: string; fullPath: string } {- // This is very hacky, probably need to use a path handling library- const sections = item.path.split('/')- const filename = sections.at(-1)!- const pathPrefix = sections.slice(0, -1).join('/')-- return { filename, fullPath: item.path, pathPrefix }-}--function filesSortFn(a: TreeDataItem, b: TreeDataItem): -1 | 0 | 1 {- if (a.record!.type !== b.record!.type) {- if (a.record!.type === 'folder') {- return -1- }- return 1- }-- if (a.name < b.name) {- return -1- } else if (b.name < a.name) {- return 1- }- return 0-}diff --git a/products/live_debugger/frontend/serde.test.ts b/products/live_debugger/frontend/serde.test.tsdeleted file mode 100644index ed842188bb04..000000000000--- a/products/live_debugger/frontend/serde.test.ts+++ /dev/null@@ -1,430 +0,0 @@-import { parseJsonPickleVariable } from './serde'--describe('parseJsonPickleVariable', () => {- describe('simple types', () => {- it('should parse null', () => {- const result = parseJsonPickleVariable('null')- expect(result).toEqual({- type: 'simple',- value: null,- })- })-- it('should parse boolean true', () => {- const result = parseJsonPickleVariable('true')- expect(result).toEqual({- type: 'simple',- value: true,- })- })-- it('should parse boolean false', () => {- const result = parseJsonPickleVariable('false')- expect(result).toEqual({- type: 'simple',- value: false,- })- })-- it('should parse integer numbers', () => {- const result = parseJsonPickleVariable('42')- expect(result).toEqual({- type: 'simple',- value: 42,- })- })-- it('should parse float numbers', () => {- const result = parseJsonPickleVariable('3.14159')- expect(result).toEqual({- type: 'simple',- value: 3.14159,- })- })-- it('should parse negative numbers', () => {- const result = parseJsonPickleVariable('-123')- expect(result).toEqual({- type: 'simple',- value: -123,- })- })-- it('should parse simple strings', () => {- const result = parseJsonPickleVariable('"hello world"')- expect(result).toEqual({- type: 'simple',- value: 'hello world',- })- })-- it('should parse empty strings', () => {- const result = parseJsonPickleVariable('""')- expect(result).toEqual({- type: 'simple',- value: '',- })- })- })-- describe('complex types without metadata', () => {- it('should parse simple arrays', () => {- const result = parseJsonPickleVariable('[1, 2, 3]')- expect(result).toEqual({- type: 'complex',- value: [1, 2, 3],- typeName: undefined,- })- })-- it('should parse empty arrays', () => {- const result = parseJsonPickleVariable('[]')- expect(result).toEqual({- type: 'complex',- value: [],- typeName: undefined,- })- })-- it('should parse simple objects', () => {- const result = parseJsonPickleVariable('{"name": "Alice", "age": 30}')- expect(result).toEqual({- type: 'complex',- value: { name: 'Alice', age: 30 },- typeName: undefined,- })- })-- it('should parse empty objects', () => {- const result = parseJsonPickleVariable('{}')- expect(result).toEqual({- type: 'complex',- value: {},- typeName: undefined,- })- })-- it('should parse nested objects', () => {- const result = parseJsonPickleVariable('{"user": {"name": "Bob", "settings": {"theme": "dark"}}}')- expect(result).toEqual({- type: 'complex',- value: {- user: {- name: 'Bob',- settings: {- theme: 'dark',- },- },- },- typeName: undefined,- })- })-- it('should parse arrays with mixed types', () => {- const result = parseJsonPickleVariable('[1, "text", true, null, {"key": "value"}]')- expect(result).toEqual({- type: 'complex',- value: [1, 'text', true, null, { key: 'value' }],- typeName: undefined,- })- })- })-- describe('jsonpickle metadata handling', () => {- it('should extract py/object type name', () => {- const result = parseJsonPickleVariable('{"py/object": "posthog.models.User", "name": "Alice"}')- expect(result).toEqual({- type: 'complex',- value: { name: 'Alice' },- typeName: 'posthog.models.User',- })- })-- it('should remove all py/ prefixed keys', () => {- const result = parseJsonPickleVariable(- JSON.stringify({- 'py/object': 'SomeClass',- 'py/id': 123,- 'py/state': 'active',- name: 'Test',- value: 42,- })- )- expect(result).toEqual({- type: 'complex',- value: {- name: 'Test',- value: 42,- },- typeName: 'SomeClass',- })- })-- it('should clean metadata from nested objects', () => {- const result = parseJsonPickleVariable(- JSON.stringify({- 'py/object': 'Parent',- child: {- 'py/object': 'Child',- 'py/ref': 1,- name: 'Nested',- },- items: [- {- 'py/object': 'Item',- value: 1,- },- ],- })- )- expect(result).toEqual({- type: 'complex',- value: {- child: {- name: 'Nested',- },- items: [- {- value: 1,- },- ],- },- typeName: 'Parent',- })- })-- it('should clean metadata from arrays of objects', () => {- const result = parseJsonPickleVariable(- JSON.stringify([- { 'py/object': 'Item1', name: 'First' },- { 'py/object': 'Item2', name: 'Second' },- ])- )- expect(result).toEqual({- type: 'complex',- value: [{ name: 'First' }, { name: 'Second' }],- typeName: undefined,- })- })-- it('should preserve keys that contain py/ but do not start with it', () => {- const result = parseJsonPickleVariable('{"python_version": "3.9", "py/object": "Test"}')- expect(result).toEqual({- type: 'complex',- value: { python_version: '3.9' },- typeName: 'Test',- })- })- })-- describe('already parsed values (non-strings)', () => {- it('should handle already parsed numbers', () => {- const result = parseJsonPickleVariable(42)- expect(result).toEqual({- type: 'simple',- value: 42,- })- })-- it('should handle already parsed booleans', () => {- const result = parseJsonPickleVariable(true)- expect(result).toEqual({- type: 'simple',- value: true,- })- })-- it('should handle already parsed null', () => {- const result = parseJsonPickleVariable(null)- expect(result).toEqual({- type: 'simple',- value: null,- })- })-- it('should handle already parsed objects', () => {- const obj = { name: 'Test', value: 123 }- const result = parseJsonPickleVariable(obj)- expect(result).toEqual({- type: 'complex',- value: obj,- })- })-- it('should handle already parsed arrays', () => {- const arr = [1, 2, 3]- const result = parseJsonPickleVariable(arr)- expect(result).toEqual({- type: 'complex',- value: arr,- })- })- })-- describe('invalid JSON handling', () => {- it('should treat invalid JSON as simple string', () => {- const result = parseJsonPickleVariable('not valid json')- expect(result).toEqual({- type: 'simple',- value: 'not valid json',- })- })-- it('should handle malformed JSON objects', () => {- const result = parseJsonPickleVariable('{name: "missing quotes"}')- expect(result).toEqual({- type: 'simple',- value: '{name: "missing quotes"}',- })- })-- it('should handle truncated JSON', () => {- const result = parseJsonPickleVariable('{"incomplete": ')- expect(result).toEqual({- type: 'simple',- value: '{"incomplete": ',- })- })- })-- describe('edge cases', () => {- it('should handle empty string', () => {- const result = parseJsonPickleVariable('')- expect(result).toEqual({- type: 'simple',- value: '',- })- })-- it('should handle deeply nested structures', () => {- const deeplyNested = {- 'py/object': 'Level1',- level2: {- 'py/object': 'Level2',- level3: {- 'py/object': 'Level3',- level4: {- 'py/ref': 999,- data: 'deep',- },- },- },- }- const result = parseJsonPickleVariable(JSON.stringify(deeplyNested))- expect(result).toEqual({- type: 'complex',- value: {- level2: {- level3: {- level4: {- data: 'deep',- },- },- },- },- typeName: 'Level1',- })- })-- it('should handle objects with only metadata keys', () => {- const result = parseJsonPickleVariable('{"py/object": "EmptyClass", "py/id": 1}')- expect(result).toEqual({- type: 'complex',- value: {},- typeName: 'EmptyClass',- })- })-- it('should handle unicode strings', () => {- const result = parseJsonPickleVariable('"Hello 世界 🌍"')- expect(result).toEqual({- type: 'simple',- value: 'Hello 世界 🌍',- })- })-- it('should handle special characters in strings', () => {- const result = parseJsonPickleVariable('"Line 1\\nLine 2\\tTabbed"')- expect(result).toEqual({- type: 'simple',- value: 'Line 1\nLine 2\tTabbed',- })- })-- it('should handle large numbers', () => {- const result = parseJsonPickleVariable('9007199254740991')- expect(result).toEqual({- type: 'simple',- value: 9007199254740991,- })- })- })-- describe('real-world jsonpickle examples', () => {- it('should parse a typical Django model instance', () => {- const djangoModel = {- 'py/object': 'posthog.models.User',- 'py/id': 42,- id: 123,- email: '[email protected]',- is_active: true,- created_at: '2024-01-01T00:00:00Z',- }- const result = parseJsonPickleVariable(JSON.stringify(djangoModel))- expect(result).toEqual({- type: 'complex',- value: {- id: 123,- email: '[email protected]',- is_active: true,- created_at: '2024-01-01T00:00:00Z',- },- typeName: 'posthog.models.User',- })- })-- it('should parse a list of model instances', () => {- const modelList = [- {- 'py/object': 'posthog.models.Event',- 'py/id': 1,- event: 'pageview',- distinct_id: 'user1',- },- {- 'py/object': 'posthog.models.Event',- 'py/id': 2,- event: 'click',- distinct_id: 'user2',- },- ]- const result = parseJsonPickleVariable(JSON.stringify(modelList))- expect(result).toEqual({- type: 'complex',- value: [- {- event: 'pageview',- distinct_id: 'user1',- },- {- event: 'click',- distinct_id: 'user2',- },- ],- typeName: undefined,- })- })-- it('should parse datetime objects with timezone info', () => {- const datetimeObj = {- 'py/object': 'datetime.datetime',- 'py/reduce': [{ 'py/type': 'datetime.datetime' }, ['2024', '01', '15', '10', '30', '45']],- __value__: '2024-01-15T10:30:45',- }- const result = parseJsonPickleVariable(JSON.stringify(datetimeObj))- expect(result.type).toBe('complex')- expect(result.typeName).toBe('datetime.datetime')- expect(result.value.__value__).toBe('2024-01-15T10:30:45')- })- })-})diff --git a/products/live_debugger/frontend/serde.ts b/products/live_debugger/frontend/serde.tsdeleted file mode 100644index 147bb1113e06..000000000000--- a/products/live_debugger/frontend/serde.ts+++ /dev/null@@ -1,68 +0,0 @@-interface ParsedVariable {- type: 'simple' | 'complex'- value: any- typeName?: string-}--/**- * Parse and clean jsonpickle serialized variables.- * Returns an object with type ('simple' or 'complex'), the cleaned value, and optional type name.- */-export function parseJsonPickleVariable(value: any): ParsedVariable {- // If it's already not a string, return as-is- if (typeof value !== 'string') {- return { type: typeof value === 'object' && value !== null ? 'complex' : 'simple', value }- }-- try {- const parsed = JSON.parse(value)-- // Simple types: null, boolean, number, or plain string- if (parsed === null || typeof parsed === 'boolean' || typeof parsed === 'number') {- return { type: 'simple', value: parsed }- }-- if (typeof parsed === 'string') {- return { type: 'simple', value: parsed }- }-- // Complex types: objects and arrays- if (typeof parsed === 'object') {- // Extract type name from py/object if present- const typeName = parsed['py/object'] ? String(parsed['py/object']) : undefined-- // Clean jsonpickle metadata (keys starting with 'py/')- const cleaned = cleanJsonPickleMetadata(parsed)- return { type: 'complex', value: cleaned, typeName }- }-- return { type: 'simple', value: parsed }- } catch {- // If parsing fails, treat as simple string- return { type: 'simple', value }- }-}--/**- * Recursively remove jsonpickle metadata keys (py/*) from objects- */-function cleanJsonPickleMetadata(obj: any): any {- if (obj === null || typeof obj !== 'object') {- return obj- }-- if (Array.isArray(obj)) {- return obj.map(cleanJsonPickleMetadata)- }-- const cleaned: Record<string, any> = {}- for (const [key, value] of Object.entries(obj)) {- // Skip jsonpickle metadata keys- if (key.startsWith('py/')) {- continue- }- cleaned[key] = cleanJsonPickleMetadata(value)- }-- return cleaned-}diff --git a/products/live_debugger/manifest.tsx b/products/live_debugger/manifest.tsxdeleted file mode 100644index 03491d1f46d3..000000000000--- a/products/live_debugger/manifest.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { FEATURE_FLAGS } from 'lib/constants'-import { urls } from 'scenes/urls'--import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'--import { ProductManifest } from '../../frontend/src/types'--export const manifest: ProductManifest = {- name: 'Live Debugger',- scenes: {- LiveDebugger: {- name: 'Live debugger',- import: () => import('./frontend/LiveDebugger'),- projectBased: true,- description: 'Set breakpoints in your running code and inspect the state captured when they hit.',- },- },- routes: {- '/live-debugger': ['LiveDebugger', 'liveDebugger'],- },- redirects: {},- urls: {- liveDebugger: (): string => '/live-debugger',- },- fileSystemTypes: {- live_debugger: {- name: 'Live Debugger',- iconType: 'live_debugger',- href: () => urls.liveDebugger(),- iconColor: ['var(--color-product-live-debugger-light)'],- filterKey: 'live_debugger',- flag: FEATURE_FLAGS.LIVE_DEBUGGER,- },- },- treeItemsNew: [],- treeItemsProducts: [- {- path: 'Live Debugger',- displayLabel: 'Live debugger',- intents: [ProductKey.LIVE_DEBUGGER],- sceneKey: 'LiveDebugger',- category: ProductItemCategory.UNRELEASED,- type: 'live_debugger',- href: urls.liveDebugger(),- flag: FEATURE_FLAGS.LIVE_DEBUGGER,- iconType: 'live_debugger',- tags: ['alpha'],- iconColor: ['var(--color-product-live-debugger-light)', 'var(--color-product-live-debugger-dark)'],- },- ],-}diff --git a/products/live_debugger/package.json b/products/live_debugger/package.jsonindex 76b573a62007..ba07004fc235 100644--- a/products/live_debugger/package.json+++ b/products/live_debugger/package.json@@ -1,23 +1,6 @@{"name": "@posthog/products-live-debugger","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"- },- "dependencies": {- "fuse.js": "catalog:"- },- "devDependencies": {- "kea-test-utils": "catalog:"- },- "peerDependencies": {- "@posthog/icons": "catalog:",- "@posthog/lemon-ui": "*",- "@types/react": "*",- "@types/react-dom": "*",- "clsx": "*",- "kea": "catalog:",- "kea-loaders": "catalog:",- "react": "*",- "react-dom": "*"+ "backend:test": "echo 'vestigial app — no tests'"}}diff --git a/products/ruff.toml b/products/ruff.tomlindex 89d730278b0d..3054559cbcec 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -98,7 +98,6 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"feature_flags/**" = ["PLC0415"]"growth/**" = ["PLC0415"]"legal_documents/**" = ["PLC0415"]-"live_debugger/**" = ["PLC0415"]"ai_observability/**" = ["PLC0415"]"logs/**" = ["PLC0415"]"managed_migrations/**" = ["PLC0415"]diff --git a/pyproject.toml b/pyproject.tomlindex d1c55c56912f..aaded0a14616 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -800,7 +800,6 @@ ignore_imports = ["products.growth.backend.routes -> products.growth.backend.api.ai_enrichment","products.growth.backend.routes -> products.growth.backend.api.identity_matching","products.growth.backend.routes -> products.growth.backend.api.product_push",- "products.live_debugger.backend.routes -> products.live_debugger.backend.api","products.managed_migrations.backend.routes -> products.managed_migrations.backend.api.batch_imports","products.managed_migrations.backend.routes -> products.managed_migrations.backend.api.support_batch_imports","products.marketing_analytics.backend.routes -> products.marketing_analytics.backend.api",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 528dfd929d06..b5e36dd356e0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4538,38 +4538,6 @@ export namespace Schemas {active_version: AppVersionContract;}- /**- * Schema for a single active breakpoint- */- export interface ActiveBreakpoint {- /** Unique identifier for the breakpoint */- id: string;- /**- * Repository identifier (e.g., 'PostHog/posthog')- * @nullable- */- repository?: string | null;- /** File path where the breakpoint is set */- filename: string;- /** Line number of the breakpoint */- line_number: number;- /** Whether the breakpoint is enabled */- enabled: boolean;- /**- * Optional condition for the breakpoint- * @nullable- */- condition?: string | null;- }-- /**- * Response schema for active breakpoints endpoint- */- export interface ActiveBreakpointsResponse {- /** List of active breakpoints */- breakpoints: ActiveBreakpoint[];- }-/*** * `not_started` - not_started* * `queued` - queued@@ -17835,45 +17803,6 @@ export namespace Schemas {value: string;}- /**- * Local variables at the time of the hit- */- export type BreakpointHitVariables = { [key: string]: unknown };-- /**- * Schema for a single breakpoint hit event- */- export interface BreakpointHit {- /** Unique identifier for the hit event */- id: string;- /** Line number where the breakpoint was hit */- lineNumber: number;- /** Name of the function where breakpoint was hit */- functionName: string;- /** When the breakpoint was hit */- timestamp: string;- /** Local variables at the time of the hit */- variables: BreakpointHitVariables;- /** Stack trace at the time of the hit */- stackTrace: unknown[];- /** ID of the breakpoint that was hit */- breakpoint_id: string;- /** Filename where the breakpoint was hit */- filename: string;- }-- /**- * Response schema for breakpoint hits endpoint- */- export interface BreakpointHitsResponse {- /** List of breakpoint hit events */- results: BreakpointHit[];- /** Number of results returned */- count: number;- /** Whether there are more results available */- has_more: boolean;- }-export interface BriefAnchors {/** IDs of the dashboards this brief is anchored on. */dashboards?: number[];@@ -59171,23 +59100,6 @@ export namespace Schemas {status: BatchExportRunStatusEnum;}- export interface LiveDebuggerBreakpoint {- readonly id: string;- /** @nullable */- repository?: string | null;- filename: string;- /**- * @minimum 0- * @maximum 2147483647- */- line_number: number;- enabled?: boolean;- /** @nullable */- condition?: string | null;- readonly created_at: string;- readonly updated_at: string;- }-export interface LlmEvalReportSignalExtra {evaluation_id: string;evaluation_name: string;@@ -67477,15 +67389,6 @@ export namespace Schemas {results: ListOutput[];}- export interface PaginatedLiveDebuggerBreakpointList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: LiveDebuggerBreakpoint[];- }-export interface PaginatedLogsAlertConfigurationList {count: number;/** @nullable */@@ -77863,23 +77766,6 @@ export namespace Schemas {version_description?: string;}- export interface PatchedLiveDebuggerBreakpoint {- readonly id?: string;- /** @nullable */- repository?: string | null;- filename?: string;- /**- * @minimum 0- * @maximum 2147483647- */- line_number?: number;- enabled?: boolean;- /** @nullable */- condition?: string | null;- readonly created_at?: string;- readonly updated_at?: string;- }-export interface PatchedLogsAlertConfiguration {/** Unique identifier for this alert. */readonly id?: string;@@ -119512,49 +119398,6 @@ export namespace Schemas {export type JsSnippetVersionPartialUpdate200 = { [key: string]: unknown };- export type LiveDebuggerBreakpointsListParams = {- filename?: string;- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- repository?: string;- };-- export type LiveDebuggerBreakpointsActiveRetrieveParams = {- /**- * Only return enabled breakpoints- */- enabled?: boolean;- /**- * Filter breakpoints for a specific file- */- filename?: string;- /**- * Filter breakpoints for a specific repository (e.g., 'PostHog/posthog')- */- repository?: string;- };-- export type LiveDebuggerBreakpointsBreakpointHitsRetrieveParams = {- /**- * Filter hits for specific breakpoints (repeat parameter for multiple IDs, e.g., ?breakpoint_ids=uuid1&breakpoint_ids=uuid2)- */- breakpoint_ids?: string;- /**- * Number of hits to return (default: 100, max: 1000)- */- limit?: number;- /**- * Pagination offset for retrieving additional results (default: 0)- */- offset?: number;- };-export type LlmAnalyticsClusteringJobsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 0d7872b9fa8c..4bb86d1d4bc9 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -1059,11 +1059,6 @@"params": [],"scope": "project"},- "liveDebugger": {- "template": "/live-debugger",- "params": [],- "scope": "project"- },"login": {"template": "/login","params": [],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 4e679c20ce6e..135e4c930a55 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},diff --git a/tach.toml b/tach.tomlindex 3a05c0804090..0694b72ff087 100644--- a/tach.toml+++ b/tach.toml@@ -523,11 +523,10 @@ depends_on = ["posthog"]layer = "modules"[[modules]]+# Retired product. The app keeps its model and migration history so that Django keeps+# cascading deletes into its table until a later migration drops it.path = "products.live_debugger"-depends_on = [- "ee",- "posthog", "products.access_control",-]+depends_on = ["posthog"]layer = "modules"[[modules]]