Commit 39a111af authored by Jude Gao's avatar Jude Gao

Add Insights DevTools panel with pull-based architecture

Implements a new DevTools panel that displays application insights using an
on-demand pull model instead of HMR push. The panel shows security and
serialization issues with expert prompts that can be copied for AI analysis.

Key features:
- Generic /__nextjs_insights API endpoint for extensible insight types
- Pull-based architecture: panel fetches data on mount and via refresh button
- Flattened insight display: each issue shown as separate card (not grouped)
- Copy expert prompt button on each insight for AI assistance
- Compact file location display with full details
- Proper scrollability for multiple insights
- Generic UI design (no hardcoded categories)

Technical implementation:
- Added getInsightsMiddleware() for both Turbopack and Webpack
- Removed all HMR push complexity (message types, state, dispatcher)
- Flattened API response: one object per issue with expertPrompt field
- Pull model eliminates state synchronization issues
- Fully type-safe with proper error handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 553b84b6
......@@ -11,6 +11,7 @@ export type PanelStateKind =
| 'segment-explorer'
| 'panel-selector'
| 'turbo-info'
| 'insights'
export const PanelRouterContext = createContext<{
panel: PanelStateKind | null
......
......@@ -8,6 +8,7 @@ import {
import { PageSegmentTree } from '../components/overview/segment-explorer'
import { TurbopackInfoBody } from '../components/errors/dev-tools-indicator/dev-tools-info/turbopack-info'
import { DevToolsHeader } from '../components/errors/dev-tools-indicator/dev-tools-info/dev-tools-header'
import { BoundaryInsightsPanel } from '../components/boundary-insights/boundary-insights-panel'
import { useDelayedRender } from '../hooks/use-delayed-render'
import {
MENU_CURVE,
......@@ -61,6 +62,15 @@ const MenuPanel = () => {
}
},
},
{
title: 'View application insights and recommendations',
label: 'Insights',
value: <ChevronRight />,
onClick: () => setPanel('insights'),
attributes: {
'data-insights': true,
},
},
state.staticIndicator === 'disabled'
? undefined
: state.staticIndicator === 'pending'
......@@ -254,6 +264,27 @@ export const PanelRouter = () => {
</div>
</DynamicPanel>
</PanelRoute>
<PanelRoute name="insights">
<DynamicPanel
sharePanelSizeGlobally={false}
draggable
sizeConfig={{
kind: 'resizable',
maxHeight: '90vh',
maxWidth: '90vw',
minHeight: 300 / state.scale,
minWidth: 450 / state.scale,
initialSize: {
height: 500 / state.scale,
width: 600 / state.scale,
},
}}
header={<DevToolsHeader title="Insights" />}
>
<BoundaryInsightsPanel />
</DynamicPanel>
</PanelRoute>
</>
)
}
......
......@@ -13,6 +13,7 @@ export interface AnalyzedBoundary {
localName: string
propsType: PropsTypeInfo | null
analysisError: string | null
jsxLocation?: JsxLocation
}
export interface BoundaryWithLocation {
......@@ -60,6 +61,7 @@ export async function analyzeBoundaries(
localName: boundary.importInfo.localName,
propsType,
analysisError,
jsxLocation: boundary.jsxLocation,
})
}
......@@ -248,3 +250,136 @@ export function formatBoundaryAnalysis(analyzed: AnalyzedBoundary[]): string {
return lines.join('\n')
}
/**
* Converts analyzed boundaries to BoundaryInsights for DevTools panel display.
*/
export function toBoundaryInsights(analyzed: AnalyzedBoundary[]): Array<{
id: string
serverFile: string
clientFile: string
localName: string
warnings: Array<{
category: 'sensitive-data' | 'non-serializable'
severity: 'warning' | 'error'
propName: string
propPath: string
message: string
}>
jsxLocation?: {
line: number
column: number
}
}> {
return analyzed
.map((boundary) => {
if (!boundary.propsType) return null
const warnings: Array<{
category: 'sensitive-data' | 'non-serializable'
severity: 'warning' | 'error'
propName: string
propPath: string
message: string
}> = []
// Collect sensitive data warnings
const flags = boundary.propsType.sensitiveFlags
if (flags.hasPassword) {
for (const propName of boundary.propsType.sensitiveProps.password) {
warnings.push({
category: 'sensitive-data',
severity: 'warning',
propName,
propPath: boundary.propsType.sensitiveSource[propName] || propName,
message: `Password data is being passed to a client component`,
})
}
}
if (flags.hasSecret) {
for (const propName of boundary.propsType.sensitiveProps.secret) {
warnings.push({
category: 'sensitive-data',
severity: 'warning',
propName,
propPath: boundary.propsType.sensitiveSource[propName] || propName,
message: `Secret data is being passed to a client component`,
})
}
}
if (flags.hasToken) {
for (const propName of boundary.propsType.sensitiveProps.token) {
warnings.push({
category: 'sensitive-data',
severity: 'warning',
propName,
propPath: boundary.propsType.sensitiveSource[propName] || propName,
message: `Token data is being passed to a client component`,
})
}
}
if (flags.hasApiKey) {
for (const propName of boundary.propsType.sensitiveProps.apiKey) {
warnings.push({
category: 'sensitive-data',
severity: 'warning',
propName,
propPath: boundary.propsType.sensitiveSource[propName] || propName,
message: `API key is being passed to a client component`,
})
}
}
if (flags.hasCredential) {
for (const propName of boundary.propsType.sensitiveProps.credential) {
warnings.push({
category: 'sensitive-data',
severity: 'warning',
propName,
propPath: boundary.propsType.sensitiveSource[propName] || propName,
message: `Credential data is being passed to a client component`,
})
}
}
// Collect non-serializable warnings
if (
boundary.propsType.functionProps &&
boundary.propsType.functionProps.length > 0
) {
for (const funcProp of boundary.propsType.functionProps) {
const value = boundary.propsType.propValues[funcProp]
warnings.push({
category: 'non-serializable',
severity: 'warning',
propName: funcProp,
propPath: value ? `${funcProp} = {${value}}` : funcProp,
message: `Function is being passed to a client component (not a Server Action)`,
})
}
}
if (warnings.length === 0) return null
return {
id: boundary.id,
serverFile: boundary.serverFile,
clientFile: boundary.clientFile,
localName: boundary.localName,
warnings,
jsxLocation: boundary.jsxLocation
? {
line: boundary.jsxLocation.line,
column: boundary.jsxLocation.column,
}
: undefined,
}
})
.filter(
(insight): insight is NonNullable<typeof insight> => insight !== null
)
}
......@@ -29,10 +29,10 @@ import { createDefineEnv, getBindingsSync } from '../../build/swc'
import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { analyzeBoundaries, formatBoundaryAnalysis } from '../boundary-analysis'
import {
getOverlayMiddleware,
getSourceMapMiddleware,
getInsightsMiddleware,
getOriginalStackFrames,
} from './middleware-turbopack'
import { PageNotFoundError } from '../../shared/lib/utils'
......@@ -712,51 +712,6 @@ export async function createHotReloaderTurbopack(
},
})
// === BOUNDARY ANALYSIS PROOF OF CONCEPT ===
// handleEntrypoints above triggers subscribeToChanges which initiates compilation
// Give it a moment to complete, then analyze boundaries
;(async () => {
try {
// Load TypeScript module
let typescript: typeof import('typescript/lib/tsserverlibrary')
try {
// eslint-disable-next-line import/no-extraneous-dependencies -- dev-only code
typescript = require('typescript') as typeof import('typescript')
} catch (e) {
console.log(
'[BOUNDARY] TypeScript not available, skipping type analysis'
)
return
}
// Small delay to let initial compilation complete
await new Promise((resolve) => setTimeout(resolve, 5000))
console.log('[BOUNDARY] Starting boundary analysis...')
for (const [_pathname, route] of currentEntrypoints.app) {
if (route.type === 'app-page' && route.htmlEndpoint) {
const boundaries = await route.htmlEndpoint.getBoundaries()
if (boundaries.boundaries.length > 0) {
// Analyze boundaries with TypeScript
const analyzed = await analyzeBoundaries(
typescript,
projectPath,
boundaries.boundaries
)
// Format and log
const output = formatBoundaryAnalysis(analyzed)
console.log(output)
}
}
}
} catch (err) {
console.log('[BOUNDARY] Analysis error:', err)
}
})()
// === END BOUNDARY ANALYSIS ===
// Reload matchers when the files have been compiled
await propagateServerField(opts, 'reloadMatchers', undefined)
......@@ -811,6 +766,11 @@ export async function createHotReloaderTurbopack(
isSrcDir: opts.isSrcDir,
}),
getSourceMapMiddleware(project),
getInsightsMiddleware({
project,
projectPath,
currentEntrypoints: currentEntrypoints.app,
}),
getNextErrorFeedbackMiddleware(opts.telemetry),
getDevOverlayFontMiddleware(),
getDisableDevIndicatorMiddleware(),
......
......@@ -10,6 +10,7 @@ import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import {
getOverlayMiddleware,
getSourceMapMiddleware,
getInsightsMiddleware,
getOriginalStackFrames,
} from './middleware-webpack'
import { WebpackHotMiddleware } from './hot-middleware'
......@@ -1656,6 +1657,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
serverStats: () => this.serverStats,
edgeServerStats: () => this.edgeServerStats,
}),
getInsightsMiddleware(),
getNextErrorFeedbackMiddleware(this.telemetry),
getDevOverlayFontMiddleware(),
getDisableDevIndicatorMiddleware(),
......
......@@ -697,3 +697,28 @@ export function getSourceMapMiddleware(options: {
return middlewareResponse.json(res, source.sourceMap)
}
}
export function getInsightsMiddleware() {
return async function (
req: IncomingMessage,
res: ServerResponse,
next: () => void
): Promise<void> {
const { pathname } = new URL(`http://n${req.url}`)
if (pathname !== '/__nextjs_insights') {
return next()
}
if (req.method !== 'GET') {
return middlewareResponse.badRequest(res)
}
// Insights are currently only supported in Turbopack
// Return empty insights for webpack mode
return middlewareResponse.json(res, {
insights: [],
error: 'Insights are only available with Turbopack',
})
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment