: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(error-tracking): include stack trace in created external issues (#110122)
Aleksander Błaszkiewicze8f9ea2c7b86
diff --git a/posthog/models/integration/jira.py b/posthog/models/integration/jira.pyindex d0c98046ddf6..534ddbda009f 100644--- a/posthog/models/integration/jira.py+++ b/posthog/models/integration/jira.py@@ -1,5 +1,6 @@"""Jira integration."""+import reimport timefrom datetime import timedeltafrom typing import Any, NoReturn@@ -14,6 +15,57 @@ from . import common, model, oauthlogger = structlog.get_logger(__name__)+OPENING_FENCE = re.compile(r"(?P<fence>`{3,})(?P<language>[^`]*)")+CLOSING_FENCE = re.compile(r"(?P<fence>`{3,})[ \t]*")+++def description_to_adf(description: str) -> dict[str, Any]:+ """Markdown code fences become ADF code blocks, because Jira shows the backticks literally otherwise.++ The fences follow CommonMark, so Jira shows the same blocks that GitHub would: a closing fence is at least as+ long as its opening fence, and a fence without a closing line runs to the end. Each line is read once, so a+ description with many unclosed fences still converts in linear time.+ """+ content: list[dict[str, Any]] = []+ text_lines: list[str] = []+ code_lines: list[str] = []+ fence = ""+ language = ""++ def add_paragraph() -> None:+ text = "\n".join(text_lines).strip("\n")+ text_lines.clear()+ # Jira rejects an empty text node.+ if text.strip():+ content.append({"type": "paragraph", "content": [{"type": "text", "text": text}]})++ def add_code_block(language: str) -> None:+ code_block: dict[str, Any] = {"type": "codeBlock", "content": []}+ if language:+ code_block["attrs"] = {"language": language}+ if code := "\n".join(code_lines):+ code_block["content"] = [{"type": "text", "text": code}]+ code_lines.clear()+ content.append(code_block)++ for line in description.split("\n"):+ if not fence:+ if opening := OPENING_FENCE.fullmatch(line):+ add_paragraph()+ fence, language = opening["fence"], opening["language"].strip()+ else:+ text_lines.append(line)+ elif (closing := CLOSING_FENCE.fullmatch(line)) and len(closing["fence"]) >= len(fence):+ add_code_block(language)+ fence = ""+ else:+ code_lines.append(line)+ if fence:+ add_code_block(language)+ add_paragraph()++ return {"type": "doc", "version": 1, "content": content}+class JiraIntegration:integration: model.Integration@@ -117,21 +169,11 @@ class JiraIntegration:description = config.get("description")project_key = config.get("project_key")- # Jira uses Atlassian Document Format (ADF) for descriptionpayload = {"fields": {"project": {"key": project_key},"summary": title,- "description": {- "type": "doc",- "version": 1,- "content": [- {- "type": "paragraph",- "content": [{"type": "text", "text": description}],- }- ],- },+ "description": description_to_adf(description or ""),"issuetype": {"name": "Task"},}}diff --git a/posthog/models/test/integration/test_jira.py b/posthog/models/test/integration/test_jira.pyindex f9f528d12c49..e95553b78c52 100644--- a/posthog/models/test/integration/test_jira.py+++ b/posthog/models/test/integration/test_jira.py@@ -3,6 +3,7 @@import pytestfrom unittest.mock import MagicMock, patch+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom posthog.models.integration import Integration, JiraIntegration@@ -70,3 +71,78 @@ class TestJiraIntegrationModel:"integration_id": 123,"team_id": 456,}++ @parameterized.expand(+ [+ (+ "plain_text_stays_one_paragraph",+ "Details\nPostHog issue: https://example.com/issue/1",+ [+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": "Details\nPostHog issue: https://example.com/issue/1"}],+ }+ ],+ ),+ (+ "fence_becomes_code_block",+ 'Checkout failed\n\n```\nTypeError: boom\n File "app.js", line: 3\n```\n\nPostHog issue: https://example.com/issue/1',+ [+ {"type": "paragraph", "content": [{"type": "text", "text": "Checkout failed"}]},+ {+ "type": "codeBlock",+ "content": [{"type": "text", "text": 'TypeError: boom\n File "app.js", line: 3'}],+ },+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": "PostHog issue: https://example.com/issue/1"}],+ },+ ],+ ),+ (+ "longer_closing_fence_closes_block",+ "```\nboom\n````\nafter",+ [+ {"type": "codeBlock", "content": [{"type": "text", "text": "boom"}]},+ {"type": "paragraph", "content": [{"type": "text", "text": "after"}]},+ ],+ ),+ (+ "unclosed_fence_runs_to_end",+ "Details\n```js\nboom\n\nPostHog issue: https://example.com/issue/1",+ [+ {"type": "paragraph", "content": [{"type": "text", "text": "Details"}]},+ {+ "type": "codeBlock",+ "attrs": {"language": "js"},+ "content": [{"type": "text", "text": "boom\n\nPostHog issue: https://example.com/issue/1"}],+ },+ ],+ ),+ (+ "shorter_inner_fence_stays_in_code",+ "````python\nprint('x')\n```\n````",+ [+ {+ "type": "codeBlock",+ "attrs": {"language": "python"},+ "content": [{"type": "text", "text": "print('x')\n```"}],+ }+ ],+ ),+ ]+ )+ @patch("posthog.models.integration.jira.requests.post")+ def test_create_issue_converts_description_to_adf(self, _name, description, expected_content, mock_post):+ mock_post.return_value.status_code = 201+ mock_post.return_value.json.return_value = {"key": "ENG-1", "id": "10001"}++ JiraIntegration(self.integration()).create_issue(+ {"project_key": "ENG", "title": "Checkout failed", "description": description}+ )++ assert mock_post.call_args.kwargs["json"]["fields"]["description"] == {+ "type": "doc",+ "version": 1,+ "content": expected_content,+ }diff --git a/products/error_tracking/frontend/components/ExternalReferences.tsx b/products/error_tracking/frontend/components/ExternalReferences.tsxindex 869274eaa583..49eb49241f4b 100644--- a/products/error_tracking/frontend/components/ExternalReferences.tsx+++ b/products/error_tracking/frontend/components/ExternalReferences.tsx@@ -1,9 +1,10 @@-import { useActions, useValues } from 'kea'+import { BuiltLogic, useActions, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'import { IconPlus } from '@posthog/icons'import { LemonDialog, LemonInput, LemonInputSelect, LemonTextArea, Link } from '@posthog/lemon-ui'+import { stackFrameLogic } from 'lib/components/Errors/Frame/stackFrameLogic'import { ErrorTrackingFingerprint } from 'lib/components/Errors/types'import { GitHubRepositoryPicker, GitHubRepositorySelectField } from 'lib/integrations/GitHubIntegrationHelpers'import { integrationsLogic } from 'lib/integrations/integrationsLogic'@@ -31,20 +32,27 @@ import {ErrorTrackingExternalIssueResultApi,ErrorTrackingExternalIssueResultApiExternalContext,} from '../generated/api.schemas'-import { errorTrackingIssueSceneLogic } from '../scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'+import {+ errorTrackingIssueSceneLogic,+ errorTrackingIssueSceneLogicType,+} from '../scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'+import { appendStacktrace, getStacktrace } from './externalIssueBody'import { externalIssueSearchLogic } from './externalIssueSearchLogic'+import { IncludeStacktraceField } from './IncludeStacktraceField'const ERROR_TRACKING_INTEGRATIONS = ['linear', 'github', 'gitlab', 'jira'] as const satisfies readonly IntegrationKind[]-type onSubmitFormType = (integrationId: number, config: Record<string, string>) => void+type onSubmitFormType = (integrationId: number, config: Record<string, string>, includeStacktrace: boolean) => voidtype onSubmitLinkType = (integrationId: number,externalContext: ErrorTrackingExternalIssueResultApiExternalContext) => voidtype ErrorTrackingIntegrationKind = (typeof ERROR_TRACKING_INTEGRATIONS)[number]type ErrorTrackingIntegration = IntegrationType & { kind: ErrorTrackingIntegrationKind }+type ErrorTrackingIssueSceneBuiltLogic = BuiltLogic<errorTrackingIssueSceneLogicType>-const POSTHOG_HTML_LINE_BREAKS = '\n<br/>\n<br/>\n'+// The dialog otherwise sizes to its widest line, so it would resize when the stack trace preview is shown or hidden.+const CREATE_ISSUE_DIALOG_WIDTH = '40rem'const PROVIDER_LABELS: Record<ErrorTrackingIntegrationKind, string> = {github: 'GitHub',@@ -58,6 +66,7 @@ const EXTERNAL_REFERENCE_FORM_BUILDERS: Record<(issue: ErrorTrackingRelationalIssue,issueUrl: string,+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,integration: ErrorTrackingIntegration,onSubmit: onSubmitFormType) => void@@ -69,8 +78,9 @@ const EXTERNAL_REFERENCE_FORM_BUILDERS: Record<}export const ExternalReferences = (): JSX.Element | null => {- const { issue, issueLoading, issueFingerprints } = useValues(errorTrackingIssueSceneLogic)- const { createExternalReference, linkExternalReference } = useActions(errorTrackingIssueSceneLogic)+ const sceneLogic = useMountedLogic(errorTrackingIssueSceneLogic)+ const { issue, issueLoading, issueFingerprints } = useValues(sceneLogic)+ const { createExternalReference, linkExternalReference } = useActions(sceneLogic)const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)if (!issue || integrationsLoading) {@@ -94,6 +104,7 @@ export const ExternalReferences = (): JSX.Element | null => {buildForm(issue,getIssueUrl(issueFingerprints),+ sceneLogic,integration as ErrorTrackingIntegration,createExternalReference)@@ -235,26 +246,37 @@ function getIssueUrl(fingerprints: ErrorTrackingFingerprint[]): string {return `${window.location.origin}${window.location.pathname}`}-function getIssueMarkdownBody(issue: ErrorTrackingRelationalIssue, issueUrl: string): string {- return `${issue.description ?? ''}${POSTHOG_HTML_LINE_BREAKS}**PostHog issue:** ${issueUrl}`-}--function getIssuePlaintextBody(issue: ErrorTrackingRelationalIssue, issueUrl: string): string {- return `${issue.description ?? ''}\n\nPostHog issue: ${issueUrl}`+// The event and its frame records can finish loading after the dialog opens, so the trace is built at submit time.+function getSubmittedBody(+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,+ text: string,+ includeStacktrace: boolean+): string {+ if (!includeStacktrace) {+ return text+ }+ const { selectedEvent, initialEvent } = sceneLogic.values+ return appendStacktrace(+ text,+ getStacktrace(selectedEvent ?? initialEvent, stackFrameLogic.values.stackFrameRecords)+ )}function createGitHubIssueForm(issue: ErrorTrackingRelationalIssue,issueUrl: string,+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,integration: ErrorTrackingIntegration,onSubmit: onSubmitFormType): void {LemonDialog.openForm({title: 'Create GitHub issue',+ width: CREATE_ISSUE_DIALOG_WIDTH,shouldAwaitSubmit: true,initialValues: {title: issue.name,- body: getIssueMarkdownBody(issue, issueUrl),+ body: `**PostHog issue:** ${issueUrl}`,+ includeStacktrace: true,integrationId: integration.id,repositories: [],},@@ -265,8 +287,9 @@ function createGitHubIssueForm(<LemonInput data-attr="issue-title" placeholder="Issue title" size="small" /></LemonField><LemonField name="body" label="Body">- <LemonTextArea data-attr="issue-body" placeholder="Start typing..." />+ <LemonTextArea data-attr="issue-body" placeholder="Start typing..." maxRows={12} /></LemonField>+ <IncludeStacktraceField sceneLogic={sceneLogic} bodyField="body" /></div>),errors: {@@ -274,8 +297,13 @@ function createGitHubIssueForm(repositories: (repositories) =>repositories && repositories.length === 0 ? 'You must choose a repository' : undefined,},- onSubmit: ({ title, body, repositories }) => {- onSubmit(integration.id, { repository: repositories[0], title, body })+ onSubmit: ({ title, body, includeStacktrace, repositories }) => {+ const submittedBody = getSubmittedBody(sceneLogic, body, includeStacktrace)+ onSubmit(+ integration.id,+ { repository: repositories[0], title, body: submittedBody },+ submittedBody !== body+ )},})}@@ -283,15 +311,18 @@ function createGitHubIssueForm(function createGitLabIssueForm(issue: ErrorTrackingRelationalIssue,issueUrl: string,+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,integration: ErrorTrackingIntegration,onSubmit: onSubmitFormType): void {LemonDialog.openForm({title: 'Create GitLab issue',+ width: CREATE_ISSUE_DIALOG_WIDTH,shouldAwaitSubmit: true,initialValues: {title: issue.name,- body: getIssueMarkdownBody(issue, issueUrl),+ body: `**PostHog issue:** ${issueUrl}`,+ includeStacktrace: true,integrationId: integration.id,},content: (@@ -300,15 +331,17 @@ function createGitLabIssueForm(<LemonInput data-attr="issue-title" placeholder="Issue title" size="small" /></LemonField><LemonField name="body" label="Body">- <LemonTextArea data-attr="issue-body" placeholder="Start typing..." />+ <LemonTextArea data-attr="issue-body" placeholder="Start typing..." maxRows={12} /></LemonField>+ <IncludeStacktraceField sceneLogic={sceneLogic} bodyField="body" /></div>),errors: {title: (title) => (!title ? 'You must enter a title' : undefined),},- onSubmit: ({ title, body }) => {- onSubmit(integration.id, { title, body })+ onSubmit: ({ title, body, includeStacktrace }) => {+ const submittedBody = getSubmittedBody(sceneLogic, body, includeStacktrace)+ onSubmit(integration.id, { title, body: submittedBody }, submittedBody !== body)},})}@@ -316,15 +349,18 @@ function createGitLabIssueForm(function createLinearIssueForm(issue: ErrorTrackingRelationalIssue,_issueUrl: string,+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,integration: ErrorTrackingIntegration,onSubmit: onSubmitFormType): void {LemonDialog.openForm({title: 'Create Linear issue',+ width: CREATE_ISSUE_DIALOG_WIDTH,shouldAwaitSubmit: true,initialValues: {title: issue.name,- description: issue.description,+ description: '',+ includeStacktrace: true,integrationId: integration.id,teamIds: [],},@@ -335,16 +371,22 @@ function createLinearIssueForm(<LemonInput data-attr="issue-title" placeholder="Issue title" size="small" /></LemonField><LemonField name="description" label="Description">- <LemonTextArea data-attr="issue-description" placeholder="Start typing..." />+ <LemonTextArea data-attr="issue-description" placeholder="Start typing..." maxRows={12} /></LemonField>+ <IncludeStacktraceField sceneLogic={sceneLogic} bodyField="description" /></div>),errors: {title: (title) => (!title ? 'You must enter a title' : undefined),teamIds: (teamIds) => (teamIds && teamIds.length === 0 ? 'You must choose a team' : undefined),},- onSubmit: ({ title, description, teamIds }) => {- onSubmit(integration.id, { team_id: teamIds[0], title, description })+ onSubmit: ({ title, description, includeStacktrace, teamIds }) => {+ const submittedDescription = getSubmittedBody(sceneLogic, description, includeStacktrace)+ onSubmit(+ integration.id,+ { team_id: teamIds[0], title, description: submittedDescription },+ submittedDescription !== description+ )},})}@@ -352,15 +394,18 @@ function createLinearIssueForm(function createJiraIssueForm(issue: ErrorTrackingRelationalIssue,issueUrl: string,+ sceneLogic: ErrorTrackingIssueSceneBuiltLogic,integration: ErrorTrackingIntegration,onSubmit: onSubmitFormType): void {LemonDialog.openForm({title: 'Create Jira issue',+ width: CREATE_ISSUE_DIALOG_WIDTH,shouldAwaitSubmit: true,initialValues: {title: issue.name,- description: getIssuePlaintextBody(issue, issueUrl),+ description: `PostHog issue: ${issueUrl}`,+ includeStacktrace: true,integrationId: integration.id,projectKeys: [],},@@ -371,8 +416,9 @@ function createJiraIssueForm(<LemonInput data-attr="jira-issue-title" placeholder="Issue summary" size="small" /></LemonField><LemonField name="description" label="Description">- <LemonTextArea data-attr="jira-issue-description" placeholder="Start typing..." />+ <LemonTextArea data-attr="jira-issue-description" placeholder="Start typing..." maxRows={12} /></LemonField>+ <IncludeStacktraceField sceneLogic={sceneLogic} bodyField="description" /></div>),errors: {@@ -380,8 +426,13 @@ function createJiraIssueForm(projectKeys: (projectKeys) =>projectKeys && projectKeys.length === 0 ? 'You must choose a project' : undefined,},- onSubmit: ({ title, description, projectKeys }) => {- onSubmit(integration.id, { project_key: projectKeys[0], title, description })+ onSubmit: ({ title, description, includeStacktrace, projectKeys }) => {+ const submittedDescription = getSubmittedBody(sceneLogic, description, includeStacktrace)+ onSubmit(+ integration.id,+ { project_key: projectKeys[0], title, description: submittedDescription },+ submittedDescription !== description+ )},})}diff --git a/products/error_tracking/frontend/components/IncludeStacktraceField.tsx b/products/error_tracking/frontend/components/IncludeStacktraceField.tsxnew file mode 100644index 000000000000..656a4f7f8082--- /dev/null+++ b/products/error_tracking/frontend/components/IncludeStacktraceField.tsx@@ -0,0 +1,61 @@+import { BuiltLogic, useValues } from 'kea'+import { FormContext } from 'kea-forms'+import { useContext } from 'react'++import { LemonCheckbox } from '@posthog/lemon-ui'++import { CodeSnippet } from 'lib/components/CodeSnippet'+import { stackFrameLogic } from 'lib/components/Errors/Frame/stackFrameLogic'+import { LemonField } from 'lib/lemon-ui/LemonField'++import type { errorTrackingIssueSceneLogicType } from '../scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'+import { MAX_ISSUE_BODY_LENGTH, fitStacktrace, getStacktrace } from './externalIssueBody'++export function IncludeStacktraceField({+ sceneLogic,+ bodyField,+}: {+ sceneLogic: BuiltLogic<errorTrackingIssueSceneLogicType>+ bodyField: string+}): JSX.Element | null {+ // The event can finish loading after the dialog opens, so it is read from the scene rather than passed in.+ const { selectedEvent, initialEvent } = useValues(sceneLogic)+ const { stackFrameRecords } = useValues(stackFrameLogic)+ // How much of the trace fits depends on the body, which lives in the dialog's form.+ const { logic: formLogic, formKey } = useContext(FormContext)+ const body: string = useValues(formLogic as BuiltLogic)[formKey]?.[bodyField] ?? ''++ const stacktrace = getStacktrace(selectedEvent ?? initialEvent, stackFrameRecords)+ const trace = fitStacktrace(body, stacktrace)++ if (!stacktrace) {+ return null+ }++ return (+ <LemonField name="includeStacktrace">+ {({ value, onChange }) => (+ <div className="flex flex-col gap-y-2">+ <LemonCheckbox+ data-attr="external-issue-include-stacktrace"+ checked={!!value}+ onChange={onChange}+ label="Include stack trace"+ />+ {value && trace && (+ <CodeSnippet compact wrap thing="stack trace" maxLinesWithoutExpansion={3}>+ {trace}+ </CodeSnippet>+ )}+ {value && trace !== stacktrace && (+ <span className="text-xs text-secondary">+ {trace+ ? `The end is cut to keep the issue under ${MAX_ISSUE_BODY_LENGTH.toLocaleString()} characters.`+ : 'The body is too long to add the stack trace.'}+ </span>+ )}+ </div>+ )}+ </LemonField>+ )+}diff --git a/products/error_tracking/frontend/components/externalIssueBody.test.ts b/products/error_tracking/frontend/components/externalIssueBody.test.tsnew file mode 100644index 000000000000..24d16ae1b131--- /dev/null+++ b/products/error_tracking/frontend/components/externalIssueBody.test.ts@@ -0,0 +1,52 @@+import { appendStacktrace, fitStacktrace, MAX_ISSUE_BODY_LENGTH } from './externalIssueBody'++const TRACE = 'TypeError: boom\n File "app.js", line: 3'++describe('appendStacktrace', () => {+ test.each([+ ['returns the text unchanged without a trace', 'PostHog issue: url', '', 'PostHog issue: url'],+ [+ 'puts the trace after the text',+ 'Details\n\nPostHog issue: url\n\n',+ TRACE,+ `Details\n\nPostHog issue: url\n\n\`\`\`\n${TRACE}\n\`\`\``,+ ],+ ['puts only the trace in an empty body', '', TRACE, `\`\`\`\n${TRACE}\n\`\`\``],+ [+ 'uses a fence longer than any backtick run in the trace',+ 'Details',+ 'Error\n const s = ```x```',+ 'Details\n\n````\nError\n const s = ```x```\n````',+ ],+ ])('%s', (_name, text, stacktrace, expected) => {+ expect(appendStacktrace(text, stacktrace)).toEqual(expected)+ })++ test.each([+ ['short text', 'PostHog issue: url'],+ ['text that leaves room for part of the trace', 'x'.repeat(MAX_ISSUE_BODY_LENGTH - 200)],+ ])('cuts a long trace at a line break so the body fits, with %s', (_name, text) => {+ const lines = Array.from({ length: 2000 }, (_, index) => ` File "app.js", line: ${index}, in: handler`)+ const stacktrace = lines.join('\n')+ const body = appendStacktrace(text, stacktrace)++ expect(body.length).toBeLessThanOrEqual(MAX_ISSUE_BODY_LENGTH)+ expect(body.startsWith(`${text}\n\n\`\`\`\n${lines[0]}`)).toBe(true)+ expect(body.endsWith(', in: handler\n...\n```')).toBe(true)+ // The dialog previews fitStacktrace, so it must be exactly the trace that goes into the body.+ expect(body).toEqual(`${text}\n\n\`\`\`\n${fitStacktrace(text, stacktrace)}\n\`\`\``)+ })++ test('leaves the trace out when the text leaves no room for it', () => {+ const text = 'x'.repeat(MAX_ISSUE_BODY_LENGTH)++ expect(appendStacktrace(text, TRACE)).toEqual(text)+ expect(fitStacktrace(text, TRACE)).toEqual('')+ })++ test('handles a trace with more backtick runs than a function call takes arguments', () => {+ const stacktrace = '`a'.repeat(200_000)++ expect(appendStacktrace('', stacktrace).startsWith('```\n`a`a')).toBe(true)+ })+})diff --git a/products/error_tracking/frontend/components/externalIssueBody.ts b/products/error_tracking/frontend/components/externalIssueBody.tsnew file mode 100644index 000000000000..5f3ea0e0e7af--- /dev/null+++ b/products/error_tracking/frontend/components/externalIssueBody.ts@@ -0,0 +1,62 @@+import { isStoredCrashFirst } from 'lib/components/Errors/displayOrder'+import { ErrorEventType } from 'lib/components/Errors/types'+import { getExceptionList } from 'lib/components/Errors/utils'++import { generateStacktraceText } from '../hooks/use-stacktrace-display'++// Jira rejects a description over 32,767 characters. That is the lowest limit of the four providers, so every body stays under it.+export const MAX_ISSUE_BODY_LENGTH = 32767++const TRUNCATION_MARKER = '\n...'++export function getStacktrace(event: ErrorEventType | null, stackFrameRecords: Record<string, any>): string {+ if (!event) {+ return ''+ }+ return generateStacktraceText(getExceptionList(event.properties), stackFrameRecords, {+ includeInAppMarkers: false,+ storedCrashFirst: isStoredCrashFirst(event.properties?.$lib, event.timestamp),+ })+}++/** Adds the stack trace as a Markdown code block after the text, cut at a line break if the body would be too long. */+export function appendStacktrace(text: string, stacktrace: string): string {+ const trace = fitStacktrace(text, stacktrace)+ if (!trace) {+ return text+ }+ const head = text.trimEnd()+ const fence = codeFence(trace)+ return `${head}${head ? '\n\n' : ''}${fence}\n${trace}\n${fence}`+}++/** The part of the stack trace that `appendStacktrace` adds after the text, or an empty string if none fits. */+export function fitStacktrace(text: string, stacktrace: string): string {+ if (!stacktrace) {+ return ''+ }+ const head = text.trimEnd()+ const separator = head ? '\n\n' : ''+ const fence = codeFence(stacktrace)+ const room = MAX_ISSUE_BODY_LENGTH - head.length - separator.length - 2 * (fence.length + 1)+ return truncateAtLineBreak(stacktrace, room)+}++// Source lines in the stack trace can contain backticks, so the fence must be longer than any run of them.+// A trace can have more runs than a function call takes arguments, so the longest run is found without spreading them.+function codeFence(text: string): string {+ const longestBacktickRun = (text.match(/`+/g) ?? []).reduce((longest, run) => Math.max(longest, run.length), 0)+ return '`'.repeat(Math.max(3, longestBacktickRun + 1))+}++function truncateAtLineBreak(text: string, maxLength: number): string {+ if (text.length <= maxLength) {+ return text+ }+ const limit = maxLength - TRUNCATION_MARKER.length+ if (limit <= 0) {+ return ''+ }+ const lastLineBreak = text.lastIndexOf('\n', limit)+ return `${text.slice(0, lastLineBreak > 0 ? lastLineBreak : limit)}${TRUNCATION_MARKER}`+}diff --git a/products/error_tracking/frontend/hooks/use-stacktrace-display.tsx b/products/error_tracking/frontend/hooks/use-stacktrace-display.tsxindex ffd2b6112b0e..d5b6d5315f56 100644--- a/products/error_tracking/frontend/hooks/use-stacktrace-display.tsx+++ b/products/error_tracking/frontend/hooks/use-stacktrace-display.tsx@@ -10,37 +10,46 @@ export const useStacktraceDisplay = (): { ready: boolean; stacktraceText: stringconst { exceptionList, stackFrameRecords, stackFrameRecordsLoading, framesStoredCrashFirst } =useValues(errorPropertiesLogic)- const stacktraceText = useMemo(() => {- return exceptionList- .map((exception) =>- generateExceptionText(exception, stackFrameRecords, {- includeInAppMarkers: true,- storedCrashFirst: framesStoredCrashFirst,- })- )- .join('\n\n')- }, [exceptionList, stackFrameRecords, framesStoredCrashFirst])-- const copyableStacktraceText = useMemo(() => {- return exceptionList- .map((exception) =>- generateExceptionText(exception, stackFrameRecords, {- includeInAppMarkers: false,- storedCrashFirst: framesStoredCrashFirst,- })- )- .join('\n\n')- }, [exceptionList, stackFrameRecords, framesStoredCrashFirst])+ const stacktraceText = useMemo(+ () =>+ generateStacktraceText(exceptionList, stackFrameRecords, {+ includeInAppMarkers: true,+ storedCrashFirst: framesStoredCrashFirst,+ }),+ [exceptionList, stackFrameRecords, framesStoredCrashFirst]+ )++ const copyableStacktraceText = useMemo(+ () =>+ generateStacktraceText(exceptionList, stackFrameRecords, {+ includeInAppMarkers: false,+ storedCrashFirst: framesStoredCrashFirst,+ }),+ [exceptionList, stackFrameRecords, framesStoredCrashFirst]+ )const ready = exceptionList.length > 0 && !stackFrameRecordsLoadingreturn { ready, stacktraceText, copyableStacktraceText }}+interface StacktraceTextOptions {+ includeInAppMarkers: boolean+ storedCrashFirst: boolean+}++export function generateStacktraceText(+ exceptionList: ErrorTrackingException[],+ stackFrameRecords: Record<string, any>,+ options: StacktraceTextOptions+): string {+ return exceptionList.map((exception) => generateExceptionText(exception, stackFrameRecords, options)).join('\n\n')+}+function generateExceptionText(exception: ErrorTrackingException,stackFrameRecords: Record<string, any>,- options: { includeInAppMarkers: boolean; storedCrashFirst: boolean }+ options: StacktraceTextOptions): string {let result = `${formatType(exception)}${exception.value ? `: ${exception.value}` : ''}`diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.tsindex 61acecb25ac5..9cb1d92e95c8 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts@@ -187,9 +187,11 @@ export interface errorTrackingIssueSceneLogicActions {loadLinkedReports: () => any // linkedReportsLogiccreateExternalReference: (integrationId: IntegrationType['id'],- config: Record<string, string>+ config: Record<string, string>,+ includeStacktrace: boolean) => {config: Record<string, string>+ includeStacktrace: booleanintegrationId: number}createExternalReferenceFailure: (@@ -213,6 +215,7 @@ export interface errorTrackingIssueSceneLogicActions {} | null,payload?: {config: Record<string, string>+ includeStacktrace: booleanintegrationId: number}) => {@@ -229,6 +232,7 @@ export interface errorTrackingIssueSceneLogicActions {} | nullpayload?: {config: Record<string, string>+ includeStacktrace: booleanintegrationId: number}}@@ -698,9 +702,14 @@ export const errorTrackingIssueSceneLogic = kea<errorTrackingIssueSceneLogicTypeselectEvent: (event: ErrorEventType | null) => ({event,}),- createExternalReference: (integrationId: IntegrationType['id'], config: Record<string, string>) => ({+ createExternalReference: (+ integrationId: IntegrationType['id'],+ config: Record<string, string>,+ includeStacktrace: boolean+ ) => ({integrationId,config,+ includeStacktrace,}),linkExternalReference: (integrationId: IntegrationType['id'],@@ -768,12 +777,13 @@ export const errorTrackingIssueSceneLogic = kea<errorTrackingIssueSceneLogicTypeissue: {setIssue: ({ issue }) => issue,loadIssue: async () => await api.errorTracking.getIssue(props.id, props.fingerprint),- createExternalReference: async ({ integrationId, config }) => {+ createExternalReference: async ({ integrationId, config, includeStacktrace }) => {if (values.issue) {const response = await api.errorTracking.createExternalReference(props.id, integrationId, config)posthog.capture('error_tracking_issue_pushed', {issue_id: props.id,destination: response.integration.kind,+ stacktrace_included: includeStacktrace,})const externalIssues = values.issue.external_issues ?? []return { ...values.issue, external_issues: [...externalIssues, response] }