Unverified Commit 7d030a02 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[devtool] copy decoded info of error details (#81735)

Change the copy button's content from the original error stack trace to a prompt template with error details from the error page and ask AI to fix it. You can copy it for either bug reporting or asking AI agent to explain/fix the errors for you.

### Example content

A runtime error prompt
```
Fix this error in Next.js app:

## Error Type
Runtime Error

## Error Message
Error on client
    at Page (app/runtime-error/page.tsx:5:11)

## Code Frame
  3 | export default function Page() {
  4 |   if (typeof window !== 'undefined') {
> 5 |     throw new Error('Error on client')
    |           ^
  6 |   }
  7 |   return <p>page</p>
  8 | }

Next.js version: 15.4.2-canary.3 (Webpack)

Explain what's wrong and fix it.
```

### Recordings

| build error | runtime error |
|:--|:--|
| <video src="https://github.com/user-attachments/assets/f31c935e-797c-48c7-8e80-5c1bdcde7c5c"> | <video src="https://github.com/user-attachments/assets/15987538-af32-4a32-90e7-1bbf08f1d57b"> |
parent cf1b7194
......@@ -133,20 +133,35 @@ function useCopyModern(content: string) {
const useCopy =
typeof React.useActionState === 'function' ? useCopyModern : useCopyLegacy
export function CopyButton({
actionLabel,
successLabel,
content,
icon,
disabled,
...props
}: React.HTMLProps<HTMLButtonElement> & {
type CopyButtonProps = React.HTMLProps<HTMLButtonElement> & {
actionLabel: string
successLabel: string
content: string
icon?: React.ReactNode
}) {
const [copyState, copy, reset, isPending] = useCopy(content)
}
export function CopyButton(
props: CopyButtonProps & { content?: string; getContent?: () => string }
) {
const {
content,
getContent,
actionLabel,
successLabel,
icon,
disabled,
...rest
} = props
const getContentString = (): string => {
if (content) {
return content
}
if (getContent) {
return getContent()
}
return ''
}
const contentString = getContentString()
const [copyState, copy, reset, isPending] = useCopy(contentString)
const error = copyState.state === 'error' ? copyState.error : null
React.useEffect(() => {
......@@ -186,7 +201,7 @@ export function CopyButton({
return (
<button
{...props}
{...rest}
type="button"
title={label}
aria-label={label}
......
......@@ -29,6 +29,7 @@ const renderTestComponent = () => {
installed: '15.0.0',
staleness: 'fresh',
}}
generateErrorInfo={() => ''}
>
Module not found: Cannot find module './missing-module'
</ErrorOverlayLayout>
......
......@@ -52,6 +52,7 @@ export interface ErrorOverlayLayoutProps extends ErrorBaseProps {
activeIdx?: number
setActiveIndex?: (index: number) => void
dialogResizerRef?: React.RefObject<HTMLDivElement | null>
generateErrorInfo: () => string
}
export function ErrorOverlayLayout({
......@@ -70,6 +71,7 @@ export function ErrorOverlayLayout({
setActiveIndex,
isTurbopack,
dialogResizerRef,
generateErrorInfo,
// This prop is used to animate the dialog, it comes from a parent component (<ErrorOverlay>)
// If it's not being passed, we should just render the component as it is being
// used without the context of a parent component that controls its state (e.g. Storybook).
......@@ -151,7 +153,11 @@ export function ErrorOverlayLayout({
/>
)}
</span>
<ErrorOverlayToolbar error={error} debugInfo={debugInfo} />
<ErrorOverlayToolbar
error={error}
debugInfo={debugInfo}
generateErrorInfo={generateErrorInfo}
/>
</div>
<ErrorMessage errorMessage={errorMessage} />
</ErrorOverlayDialogHeader>
......
import type { Meta, StoryObj } from '@storybook/react'
import { CopyStackTraceButton } from './copy-stack-trace-button'
import { CopyErrorButton } from './copy-error-button'
import { withShadowPortal } from '../../../storybook/with-shadow-portal'
const meta: Meta<typeof CopyStackTraceButton> = {
component: CopyStackTraceButton,
const meta: Meta<typeof CopyErrorButton> = {
component: CopyErrorButton,
parameters: {
layout: 'centered',
},
......@@ -11,7 +11,7 @@ const meta: Meta<typeof CopyStackTraceButton> = {
}
export default meta
type Story = StoryObj<typeof CopyStackTraceButton>
type Story = StoryObj<typeof CopyErrorButton>
export const WithStackTrace: Story = {
args: {
......
import { CopyButton } from '../../copy-button'
export function CopyStackTraceButton({ error }: { error: Error }) {
export function CopyErrorButton({
error,
generateErrorInfo,
}: {
error: Error
generateErrorInfo: () => string
}) {
return (
<CopyButton
data-nextjs-data-runtime-error-copy-stack
className="copy-stack-trace-button"
actionLabel="Copy Stack Trace"
successLabel="Stack Trace Copied"
content={error.stack || ''}
disabled={!error.stack}
className="copy-error-button"
actionLabel="Copy Error Info"
successLabel="Error Info Copied"
getContent={generateErrorInfo}
disabled={!error}
/>
)
}
import type { DebugInfo } from '../../../../shared/types'
import { NodejsInspectorButton } from './nodejs-inspector-button'
import { CopyStackTraceButton } from './copy-stack-trace-button'
import { CopyErrorButton } from './copy-error-button'
import { DocsLinkButton } from './docs-link-button'
type ErrorOverlayToolbarProps = {
error: Error
debugInfo: DebugInfo | undefined
feedbackButton?: React.ReactNode
generateErrorInfo: () => string
}
export function ErrorOverlayToolbar({
error,
debugInfo,
feedbackButton,
generateErrorInfo,
}: ErrorOverlayToolbarProps) {
return (
<span className="error-overlay-toolbar">
{/* TODO: Move the button inside and remove the feedback on the footer of the error overlay. */}
{feedbackButton}
<CopyStackTraceButton error={error} />
<CopyErrorButton error={error} generateErrorInfo={generateErrorInfo} />
<DocsLinkButton errorMessage={error.message} />
<NodejsInspectorButton
devtoolsFrontendUrl={debugInfo?.devtoolsFrontendUrl}
......@@ -34,7 +36,7 @@ export const styles = `
}
.nodejs-inspector-button,
.copy-stack-trace-button,
.copy-error-button,
.docs-link-button {
display: flex;
justify-content: center;
......
......@@ -37,12 +37,38 @@ export const BuildError: React.FC<BuildErrorProps> = function BuildError({
[message]
)
const generateErrorInfo = useCallback(() => {
const parts: string[] = []
// 1. Error Type
parts.push(`## Error Type\nBuild Error`)
// 2. Error Message
if (formattedMessage) {
parts.push(`## Error Message\n${formattedMessage}`)
}
// 3. Build Output (decoded stderr)
if (message) {
const decodedOutput = stripAnsi(message)
parts.push(`## Build Output\n${decodedOutput}`)
}
// Format as AI prompt
const errorInfo = `${parts.join('\n\n')}
Next.js version: ${props.versionInfo.installed} (${process.env.__NEXT_BUNDLER})\n`
return errorInfo
}, [message, formattedMessage, props.versionInfo])
return (
<ErrorOverlayLayout
errorType="Build Error"
errorMessage={formattedMessage}
onClose={noop}
error={error}
generateErrorInfo={generateErrorInfo}
{...props}
>
<Terminal content={message} />
......
import { useMemo, useRef, Suspense } from 'react'
import { useMemo, useRef, Suspense, useCallback } from 'react'
import type { DebugInfo } from '../../shared/types'
import { Overlay, OverlayBackdrop } from '../components/overlay'
import { RuntimeError } from './runtime-error'
......@@ -15,9 +15,12 @@ import {
NEXTJS_HYDRATION_ERROR_LINK,
} from '../../shared/react-19-hydration-error'
import type { ReadyRuntimeError } from '../utils/get-error-by-type'
import { useFrames } from '../utils/get-error-by-type'
import type { ErrorBaseProps } from '../components/errors/error-overlay/error-overlay'
import type { HydrationErrorState } from '../../shared/hydration-error'
import { useActiveRuntimeError } from '../hooks/use-active-runtime-error'
import { formatCodeFrame } from '../components/code-frame/parse-code-frame'
import stripAnsi from 'next/dist/compiled/strip-ansi'
export interface ErrorsProps extends ErrorBaseProps {
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
......@@ -132,6 +135,83 @@ export function Errors({
setActiveIndex,
} = useActiveRuntimeError({ runtimeErrors, getSquashedHydrationErrorDetails })
// Get parsed frames data
const frames = useFrames(activeError)
const firstFrame = useMemo(() => {
const firstFirstPartyFrameIndex = frames.findIndex(
(entry) =>
!entry.ignored &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
return frames[firstFirstPartyFrameIndex] ?? null
}, [frames])
const generateErrorInfo = useCallback(() => {
if (!activeError) return ''
const parts: string[] = []
// 1. Error Type
if (errorType) {
parts.push(`## Error Type\n${errorType}`)
}
// 2. Error Message
const error = activeError.error
let message = error.message
if ('environmentName' in error && error.environmentName) {
const envPrefix = `[ ${error.environmentName} ] `
if (message.startsWith(envPrefix)) {
message = message.slice(envPrefix.length)
}
}
if (message) {
parts.push(`## Error Message\n${message}`)
}
// Append call stack
if (frames.length > 0) {
const visibleFrames = frames.filter((frame) => !frame.ignored)
if (visibleFrames.length > 0) {
const stackLines = visibleFrames
.map((frame) => {
if (frame.originalStackFrame) {
const { methodName, file, line1, column1 } =
frame.originalStackFrame
return ` at ${methodName} (${file}:${line1}:${column1})`
} else if (frame.sourceStackFrame) {
const { methodName, file, line1, column1 } =
frame.sourceStackFrame
return ` at ${methodName} (${file}:${line1}:${column1})`
}
return ''
})
.filter(Boolean)
if (stackLines.length > 0) {
parts.push(`\n${stackLines.join('\n')}`)
}
}
}
// 3. Code Frame (decoded)
if (firstFrame?.originalCodeFrame) {
const decodedCodeFrame = stripAnsi(
formatCodeFrame(firstFrame.originalCodeFrame)
)
parts.push(`## Code Frame\n${decodedCodeFrame}`)
}
// Format as markdown error info
const errorInfo = `${parts.join('\n\n')}
Next.js version: ${props.versionInfo.installed} (${process.env.__NEXT_BUNDLER})\n`
return errorInfo
}, [activeError, errorType, firstFrame, frames, props.versionInfo])
if (isLoading) {
// TODO: better loading state
return (
......@@ -168,6 +248,7 @@ export function Errors({
activeIdx={activeIdx}
setActiveIndex={setActiveIndex}
dialogResizerRef={dialogResizerRef}
generateErrorInfo={generateErrorInfo}
{...props}
>
<div className="error-overlay-notes-container">
......
......@@ -14,7 +14,11 @@ export type ReadyRuntimeError = {
type: 'runtime' | 'console' | 'recoverable'
}
export const useFrames = (error: ReadyRuntimeError): OriginalStackFrame[] => {
export const useFrames = (
error: ReadyRuntimeError | null
): OriginalStackFrame[] => {
if (!error) return []
if ('use' in React) {
const frames = error.frames
......
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