Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(error-tracking): link existing provider issues from the issue page (#79955)

Catalin838a7349b5ec
diff --git a/posthog/models/integration/gitlab.py b/posthog/models/integration/gitlab.py
index 5dc0f8cb3fc8..c946a4372db0 100644
--- a/posthog/models/integration/gitlab.py
+++ b/posthog/models/integration/gitlab.py
@@ -115,7 +115,11 @@ class GitLabIntegration:
if not allowed:
raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")
- params: dict[str, str | int] = {"search": query, "per_page": limit, "in": "title"}
+ # A blank query lists the project's recent issues instead of filtering.
+ params: dict[str, str | int] = {"per_page": limit, "order_by": "updated_at"}
+ if query.strip():
+ params["search"] = query
+ params["in"] = "title"
response = requests.get(
url,
headers={"PRIVATE-TOKEN": access_token},
diff --git a/posthog/models/integration/linear.py b/posthog/models/integration/linear.py
index bcd45e0174dc..cbf557bfd11d 100644
--- a/posthog/models/integration/linear.py
+++ b/posthog/models/integration/linear.py
@@ -81,18 +81,33 @@ class LinearIntegration:
raise ValidationError("Failed to attach the PostHog link to the Linear issue")
def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:
- """Search existing Linear issues by title / identifier for the link-existing flow."""
- search_query = """
- query SearchIssues($term: String!, $first: Int!) {
- searchIssues(term: $term, first: $first) {
- nodes { identifier title url }
- }
- }
+ """Search existing Linear issues by title / identifier for the link-existing flow.
+
+ A blank query lists recently updated issues instead - searchIssues requires a term.
"""
- body = self.query(search_query, variables={"term": query, "first": limit})
- if body.get("errors") or common.dot_get(body, "data.searchIssues") is None:
+ if query.strip():
+ search_query = """
+ query SearchIssues($term: String!, $first: Int!) {
+ searchIssues(term: $term, first: $first) {
+ nodes { identifier title url }
+ }
+ }
+ """
+ body = self.query(search_query, variables={"term": query, "first": limit})
+ nodes_path = "data.searchIssues"
+ else:
+ recent_query = """
+ query RecentIssues($first: Int!) {
+ issues(first: $first, orderBy: updatedAt) {
+ nodes { identifier title url }
+ }
+ }
+ """
+ body = self.query(recent_query, variables={"first": limit})
+ nodes_path = "data.issues"
+ if body.get("errors") or common.dot_get(body, nodes_path) is None:
raise ValidationError("Failed to search Linear issues")
- nodes = common.dot_get(body, "data.searchIssues.nodes") or []
+ nodes = common.dot_get(body, f"{nodes_path}.nodes") or []
results: list[dict[str, Any]] = []
for node in nodes:
identifier = node.get("identifier")
diff --git a/posthog/models/test/integration/test_linear.py b/posthog/models/test/integration/test_linear.py
index 0f352f76a946..bedd445422d6 100644
--- a/posthog/models/test/integration/test_linear.py
+++ b/posthog/models/test/integration/test_linear.py
@@ -25,6 +25,16 @@ class TestLinearIntegrationModel(BaseTest):
with self.assertRaises(ValidationError):
linear.search_issues("boom")
+ def test_search_issues_lists_recent_issues_for_blank_query(self):
+ # searchIssues requires a term, so a blank picker query must use the plain issues
+ # listing instead of silently returning nothing.
+ linear = LinearIntegration(self.create_integration())
+ body = {"data": {"issues": {"nodes": [{"identifier": "ENG-7", "title": "Recent", "url": "https://l/7"}]}}}
+ with patch.object(linear, "query", return_value=body) as mock_query:
+ results = linear.search_issues(" ")
+ assert [result["id"] for result in results] == ["ENG-7"]
+ assert "searchIssues" not in mock_query.call_args.args[0]
+
@parameterized.expand(
[
("top_level_errors", {"errors": [{"message": "forbidden"}]}),
diff --git a/products/error_tracking/backend/presentation/views/external_references.py b/products/error_tracking/backend/presentation/views/external_references.py
index 22da12cda956..8d9f5faeea1a 100644
--- a/products/error_tracking/backend/presentation/views/external_references.py
+++ b/products/error_tracking/backend/presentation/views/external_references.py
@@ -114,7 +114,13 @@ class ErrorTrackingExternalIssueSearchQuerySerializer(serializers.Serializer):
help_text="ID of the connected integration to search issues in.",
)
search = serializers.CharField(
- help_text="Text to match against existing issue titles / keys in the provider.",
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=(
+ "Text to match against existing issue titles / keys in the provider. GitHub matches it "
+ "as an exact phrase. Leave blank for recent issues."
+ ),
)
repository = serializers.CharField(
required=False,
diff --git a/products/error_tracking/frontend/components/ExternalReferences.tsx b/products/error_tracking/frontend/components/ExternalReferences.tsx
index 04ec8190e1dd..029dac742c2e 100644
--- a/products/error_tracking/frontend/components/ExternalReferences.tsx
+++ b/products/error_tracking/frontend/components/ExternalReferences.tsx
@@ -2,14 +2,15 @@ import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { IconPlus } from '@posthog/icons'
-import { LemonDialog, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'
+import { LemonDialog, LemonInput, LemonInputSelect, LemonTextArea, Link } from '@posthog/lemon-ui'
import { ErrorTrackingFingerprint } from 'lib/components/Errors/types'
-import { GitHubRepositorySelectField } from 'lib/integrations/GitHubIntegrationHelpers'
+import { GitHubRepositoryPicker, GitHubRepositorySelectField } from 'lib/integrations/GitHubIntegrationHelpers'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { JiraProjectSelectField } from 'lib/integrations/JiraIntegrationHelpers'
import { LinearTeamSelectField } from 'lib/integrations/LinearIntegrationHelpers'
import { ICONS } from 'lib/integrations/utils'
+import { IconLink } from 'lib/lemon-ui/icons'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import {
@@ -26,16 +27,32 @@ import { urls } from 'scenes/urls'
import { ErrorTrackingExternalReference, ErrorTrackingRelationalIssue } from '~/queries/schema/schema-general'
import { IntegrationKind, IntegrationType } from '~/types'
+import {
+ ErrorTrackingExternalIssueResultApi,
+ ErrorTrackingExternalIssueResultApiExternalContext,
+} from '../generated/api.schemas'
import { errorTrackingIssueSceneLogic } from '../scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'
+import { externalIssueSearchLogic } from './externalIssueSearchLogic'
const ERROR_TRACKING_INTEGRATIONS = ['linear', 'github', 'gitlab', 'jira'] as const satisfies readonly IntegrationKind[]
type onSubmitFormType = (integrationId: number, config: Record<string, string>) => void
+type onSubmitLinkType = (
+ integrationId: number,
+ externalContext: ErrorTrackingExternalIssueResultApiExternalContext
+) => void
type ErrorTrackingIntegrationKind = (typeof ERROR_TRACKING_INTEGRATIONS)[number]
type ErrorTrackingIntegration = IntegrationType & { kind: ErrorTrackingIntegrationKind }
const POSTHOG_HTML_LINE_BREAKS = '\n<br/>\n<br/>\n'
+const PROVIDER_LABELS: Record<ErrorTrackingIntegrationKind, string> = {
+ github: 'GitHub',
+ gitlab: 'GitLab',
+ linear: 'Linear',
+ jira: 'Jira',
+}
+
const EXTERNAL_REFERENCE_FORM_BUILDERS: Record<
ErrorTrackingIntegrationKind,
(
@@ -53,7 +70,7 @@ const EXTERNAL_REFERENCE_FORM_BUILDERS: Record<
export const ExternalReferences = (): JSX.Element | null => {
const { issue, issueLoading, issueFingerprints } = useValues(errorTrackingIssueSceneLogic)
- const { createExternalReference } = useActions(errorTrackingIssueSceneLogic)
+ const { createExternalReference, linkExternalReference } = useActions(errorTrackingIssueSceneLogic)
const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)
if (!issue || integrationsLoading) {
@@ -68,7 +85,7 @@ export const ExternalReferences = (): JSX.Element | null => {
const errorTrackingIntegrations = getIntegrationsByKind([...ERROR_TRACKING_INTEGRATIONS])
const externalReferences = issue.external_issues ?? []
- const creatingIssue = issue && issueLoading
+ const busy = !!issue && issueLoading
const onClickCreateIssue = (integration: IntegrationType): void => {
const buildForm = EXTERNAL_REFERENCE_FORM_BUILDERS[integration.kind as ErrorTrackingIntegrationKind]
@@ -83,8 +100,12 @@ export const ExternalReferences = (): JSX.Element | null => {
}
}
+ const onClickLinkIssue = (integration: IntegrationType): void => {
+ linkExistingIssueForm(integration as ErrorTrackingIntegration, linkExternalReference)
+ }
+
return (
- <div>
+ <div className="flex flex-col gap-y-1">
{externalReferences.map((reference: ErrorTrackingExternalReference) => (
<Link
key={reference.id}
@@ -105,42 +126,81 @@ export const ExternalReferences = (): JSX.Element | null => {
))}
{errorTrackingIntegrations.length === 0 ? (
<SetupIntegrationsButton />
- ) : errorTrackingIntegrations.length > 1 ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <ButtonPrimitive fullWidth disabled={creatingIssue}>
- <IconPlus />
- {creatingIssue ? 'Creating issue...' : 'Create issue'}
- </ButtonPrimitive>
- </DropdownMenuTrigger>
-
- <DropdownMenuContent loop matchTriggerWidth>
- <DropdownMenuGroup>
- {errorTrackingIntegrations.map((integration: IntegrationType) => (
- <DropdownMenuItem key={integration.id} asChild>
- <ButtonPrimitive menuItem onClick={() => onClickCreateIssue(integration)}>
- <IntegrationIcon kind={integration.kind} />
- {integration.display_name}
- </ButtonPrimitive>
- </DropdownMenuItem>
- ))}
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
) : (
- <ButtonPrimitive
- fullWidth
- onClick={() => onClickCreateIssue(errorTrackingIntegrations[0])}
- disabled={issueLoading}
- >
- <IntegrationIcon kind={errorTrackingIntegrations[0].kind} />
- {creatingIssue ? 'Creating issue...' : 'Create issue'}
- </ButtonPrimitive>
+ <>
+ <IntegrationActionButton
+ integrations={errorTrackingIntegrations}
+ icon={<IconPlus />}
+ label="Create issue"
+ busyLabel="Creating issue..."
+ busy={busy}
+ onSelect={onClickCreateIssue}
+ />
+ <IntegrationActionButton
+ integrations={errorTrackingIntegrations}
+ icon={<IconLink />}
+ label="Link existing issue"
+ busyLabel="Linking issue..."
+ busy={busy}
+ onSelect={onClickLinkIssue}
+ />
+ </>
)}
</div>
)
}
+// Renders one action (create / link) as a single button for one integration, or a dropdown to pick
+// the integration when several are connected.
+function IntegrationActionButton({
+ integrations,
+ icon,
+ label,
+ busyLabel,
+ busy,
+ onSelect,
+}: {
+ integrations: IntegrationType[]
+ icon: JSX.Element
+ label: string
+ busyLabel: string
+ busy: boolean
+ onSelect: (integration: IntegrationType) => void
+}): JSX.Element {
+ if (integrations.length === 1) {
+ return (
+ <ButtonPrimitive fullWidth onClick={() => onSelect(integrations[0])} disabled={busy}>
+ {icon}
+ {busy ? busyLabel : label}
+ </ButtonPrimitive>
+ )
+ }
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ButtonPrimitive fullWidth disabled={busy}>
+ {icon}
+ {busy ? busyLabel : label}
+ </ButtonPrimitive>
+ </DropdownMenuTrigger>
+
+ <DropdownMenuContent loop matchTriggerWidth>
+ <DropdownMenuGroup>
+ {integrations.map((integration: IntegrationType) => (
+ <DropdownMenuItem key={integration.id} asChild>
+ <ButtonPrimitive menuItem onClick={() => onSelect(integration)}>
+ <IntegrationIcon kind={integration.kind} />
+ {integration.display_name}
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
function SetupIntegrationsButton(): JSX.Element {
return (
<Link
@@ -316,6 +376,101 @@ function createJiraIssueForm(
})
}
+function linkExistingIssueForm(integration: ErrorTrackingIntegration, onSubmit: onSubmitLinkType): void {
+ const label = PROVIDER_LABELS[integration.kind]
+ LemonDialog.openForm({
+ title: `Link existing ${label} issue`,
+ shouldAwaitSubmit: true,
+ initialValues: { externalContext: null as ErrorTrackingExternalIssueResultApiExternalContext | null },
+ content: (
+ <LemonField name="externalContext" label="Issue">
+ <ExistingIssueSelect integrationId={integration.id} kind={integration.kind} />
+ </LemonField>
+ ),
+ errors: {
+ externalContext: (externalContext) => (!externalContext ? 'You must select an issue' : undefined),
+ },
+ onSubmit: ({ externalContext }) => {
+ if (externalContext) {
+ onSubmit(integration.id, externalContext)
+ }
+ },
+ })
+}
+
+// Searchable picker of existing provider issues. Designed to sit inside a LemonField, so it takes the
+// field's value/onChange and emits the selected issue's external_context (the payload the backend stores).
+// Searchable picker of existing provider issues. Search state lives in externalIssueSearchLogic;
+// this component only bridges the LemonField value/onChange to the selected issue's external_context.
+function ExistingIssueSelect({
+ integrationId,
+ kind,
+ value,
+ onChange,
+}: {
+ integrationId: number
+ kind: ErrorTrackingIntegrationKind
+ value?: ErrorTrackingExternalIssueResultApiExternalContext | null
+ onChange?: (value: ErrorTrackingExternalIssueResultApiExternalContext | null) => void
+}): JSX.Element {
+ const requiresRepository = kind === 'github'
+ const logic = externalIssueSearchLogic({ integrationId, requiresRepository })
+ const { repository, results, resultsLoading } = useValues(logic)
+ const { setRepository, inputChanged, issueSelected } = useActions(logic)
+
+ const optionKey = (result: ErrorTrackingExternalIssueResultApi): string => result.url || `${result.id}`
+ const options = results.map((result) => ({
+ key: optionKey(result),
+ label: result.title,
+ }))
+ const selectedResult = value ? results.find((result) => result.external_context === value) : undefined
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ {requiresRepository && (
+ <GitHubRepositoryPicker
+ integrationId={integrationId}
+ value={repository}
+ onChange={(newRepository) => {
+ setRepository(newRepository ?? '')
+ onChange?.(null)
+ }}
+ />
+ )}
+ <LemonInputSelect
+ mode="single"
+ data-attr="select-existing-issue"
+ placeholder={
+ requiresRepository && !repository ? 'Select a repository first...' : 'Search for an issue...'
+ }
+ disabled={requiresRepository && !repository}
+ loading={resultsLoading}
+ // Results are already filtered by the provider; the client-side fuzzy filter
+ // would hide valid matches whose titles don't contain the raw query text.
+ disableFiltering
+ options={options}
+ value={selectedResult ? [optionKey(selectedResult)] : []}
+ onInputChange={(query) => {
+ inputChanged(query)
+ // Typing a new query invalidates the current pick - submitting while results
+ // refresh must not link the previously selected issue.
+ if (query.trim() && value) {
+ onChange?.(null)
+ }
+ }}
+ onChange={(selection) => {
+ const key = selection[0] ?? null
+ const selected = results.find((result) => optionKey(result) === key)
+ if (selected) {
+ issueSelected()
+ }
+ onChange?.(selected ? selected.external_context : null)
+ }}
+ />
+ </div>
+ )
+}
+
const IntegrationIcon = ({ kind }: { kind: IntegrationKind }): JSX.Element => {
return <img src={ICONS[kind]} className="w-5 h-5 rounded-sm" />
}
diff --git a/products/error_tracking/frontend/components/externalIssueSearchLogic.ts b/products/error_tracking/frontend/components/externalIssueSearchLogic.ts
new file mode 100644
index 000000000000..07bd6314f4fb
--- /dev/null
+++ b/products/error_tracking/frontend/components/externalIssueSearchLogic.ts
@@ -0,0 +1,128 @@
+import { LogicWrapper, MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { errorTrackingExternalReferencesSearchIssuesRetrieve } from '../generated/api'
+import { ErrorTrackingExternalIssueResultApi } from '../generated/api.schemas'
+
+export interface ExternalIssueSearchLogicProps {
+ integrationId: number
+ requiresRepository: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface externalIssueSearchLogicValues {
+ repository: string
+ results: ErrorTrackingExternalIssueResultApi[]
+ resultsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface externalIssueSearchLogicActions {
+ inputChanged: (query: string) => {
+ query: string
+ }
+ issueSelected: () => {
+ value: true
+ }
+ searchIssues: (query: any) => any
+ searchIssuesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ searchIssuesSuccess: (
+ results: ErrorTrackingExternalIssueResultApi[],
+ payload?: any
+ ) => {
+ results: ErrorTrackingExternalIssueResultApi[]
+ payload?: any
+ }
+ setRepository: (repository: string) => {
+ repository: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface externalIssueSearchLogicMeta {
+ key: number
+}
+
+export type externalIssueSearchLogicType = MakeLogicType<
+ externalIssueSearchLogicValues,
+ externalIssueSearchLogicActions,
+ ExternalIssueSearchLogicProps,
+ externalIssueSearchLogicMeta
+>
+
+export const externalIssueSearchLogic: LogicWrapper<externalIssueSearchLogicType> = kea<externalIssueSearchLogicType>([
+ props({} as ExternalIssueSearchLogicProps),
+ key((props) => props.integrationId),
+ path((key) => ['products', 'error_tracking', 'components', 'externalIssueSearchLogic', key]),
+ actions({
+ setRepository: (repository: string) => ({ repository }),
+ inputChanged: (query: string) => ({ query }),
+ issueSelected: true,
+ }),
+ loaders(({ props, values }) => ({
+ results: [
+ [] as ErrorTrackingExternalIssueResultApi[],
+ {
+ searchIssues: async (query, breakpoint) => {
+ const search = query.trim()
+ if (props.requiresRepository && !values.repository) {
+ return values.results
+ }
+ // The breakpoint debounces typing and cancels superseded searches, so a slow
+ // response can never overwrite the results of a newer query.
+ await breakpoint(300)
+ const response = await errorTrackingExternalReferencesSearchIssuesRetrieve(
+ String(teamLogic.values.currentTeamId),
+ {
+ integration_id: props.integrationId,
+ search,
+ repository: props.requiresRepository ? values.repository : undefined,
+ }
+ )
+ breakpoint()
+ return response.issues
+ },
+ },
+ ],
+ })),
+ reducers({
+ repository: [
+ '',
+ {
+ setRepository: (_, { repository }) => repository,
+ },
+ ],
+ results: {
+ // Stale options must not stay selectable while a new search is pending.
+ searchIssues: (state, query) => (typeof query === 'string' && query.trim() ? [] : state),
+ setRepository: () => [],
+ },
+ }),
+ listeners(({ actions, cache }) => ({
+ setRepository: () => actions.searchIssues(''),
+ issueSelected: () => {
+ cache.suppressNextBlankSearch = true
+ },
+ inputChanged: ({ query }) => {
+ // Selecting an option makes LemonInputSelect clear its input, which is
+ // indistinguishable from the user clearing a search - except that it directly
+ // follows issueSelected. Only a genuine clear reloads the recent issues.
+ if (!query.trim() && cache.suppressNextBlankSearch) {
+ cache.suppressNextBlankSearch = false
+ return
+ }
+ actions.searchIssues(query)
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.searchIssues('')
+ }),
+])
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index db69324f0585..33a4de809d71 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -2023,10 +2023,9 @@ export type ErrorTrackingExternalReferencesSearchIssuesRetrieveParams = {
*/
repository?: string
/**
- * Text to match against existing issue titles / keys in the provider.
- * @minLength 1
+ * Text to match against existing issue titles / keys in the provider. GitHub matches it as an exact phrase. Leave blank for recent issues.
*/
- search: string
+ search?: string
}
export type ErrorTrackingFingerprintsListParams = {
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
index 311cb94c7755..193a1ee36c01 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
@@ -31,6 +31,7 @@ import { objectsEqual } from 'lib/utils/objects'
import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'
import { Scene } from 'scenes/sceneTypes'
import { Params } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
@@ -59,6 +60,8 @@ import {
triggerFilterActions,
updateFilterSearchParams,
} from '../../components/IssueFilters/issueFiltersLogic'
+import { errorTrackingExternalReferencesLinkIssueCreate } from '../../generated/api'
+import { ErrorTrackingExternalReferenceLinkApiExternalContext } from '../../generated/api.schemas'
import { errorTrackingIssueEventsQuery, errorTrackingIssueQuery } from '../../queries'
import { syncSearchParams } from '../../utils'
import { ERROR_TRACKING_DETAILS_RESOLUTION, dateRangeToIsoBounds } from '../../utils'
@@ -219,6 +222,53 @@ export interface errorTrackingIssueSceneLogicActions {
integrationId: number
}
}
+ linkExternalReference: (
+ integrationId: IntegrationType['id'],
+ externalContext: ErrorTrackingExternalReferenceLinkApiExternalContext
+ ) => {
+ externalContext: ErrorTrackingExternalReferenceLinkApiExternalContext
+ integrationId: number
+ }
+ linkExternalReferenceFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ linkExternalReferenceSuccess: (
+ issue: {
+ assignee: ErrorTrackingIssueAssignee | null
+ cohort?: ErrorTrackingIssueCohort | undefined
+ description: string | null
+ external_issues: ErrorTrackingExternalReference[]
+ first_seen: string
+ id: string
+ name: string | null
+ severity?: ErrorTrackingQueryIssueSeverity | null | undefined
+ status: ErrorTrackingIssueStatus
+ } | null,
+ payload?: {
+ externalContext: ErrorTrackingExternalReferenceLinkApiExternalContext
+ integrationId: number
+ }
+ ) => {
+ issue: {
+ assignee: ErrorTrackingIssueAssignee | null
+ cohort?: ErrorTrackingIssueCohort | undefined
+ description: string | null
+ external_issues: ErrorTrackingExternalReference[]
+ first_seen: string
+ id: string
+ name: string | null
+ severity?: ErrorTrackingQueryIssueSeverity | null | undefined
+ status: ErrorTrackingIssueStatus
+ } | null
+ payload?: {
+ externalContext: ErrorTrackingExternalReferenceLinkApiExternalContext
+ integrationId: number
+ }
+ }
loadInitialEvent: (timestamp: string) => {
timestamp: string
}
@@ -641,6 +691,13 @@ export const errorTrackingIssueSceneLogic = kea<errorTrackingIssueSceneLogicType
integrationId,
config,
}),
+ linkExternalReference: (
+ integrationId: IntegrationType['id'],
+ externalContext: ErrorTrackingExternalReferenceLinkApiExternalContext
+ ) => ({
+ integrationId,
+ externalContext,
+ }),
updateAssignee: (assignee: ErrorTrackingIssue['assignee']) => ({ assignee }),
updateStatus: (status: ErrorTrackingIssue['status']) => ({ status }),
updateSeverity: (severity: ErrorTrackingQueryIssueSeverity | null) => ({ severity }),
@@ -712,6 +769,28 @@ export const errorTrackingIssueSceneLogic = kea<errorTrackingIssueSceneLogicType
}
return null
},
+ linkExternalReference: async ({ integrationId, externalContext }) => {
+ if (values.issue) {
+ // The generated client types integration.kind as a plain string; the
+ // canonical schema type narrows it to IntegrationKind.
+ const response = (await errorTrackingExternalReferencesLinkIssueCreate(
+ String(teamLogic.values.currentTeamId),
+ { integration_id: integrationId, issue: props.id, external_context: externalContext }
+ )) as ErrorTrackingExternalReference
+ posthog.capture('error_tracking_issue_pushed', {
+ issue_id: props.id,
+ destination: response.integration.kind,
+ linked_existing: true,
+ })
+ // Linking is idempotent server-side: re-linking returns the existing
+ // reference, which must not be appended twice.
+ const externalIssues = (values.issue.external_issues ?? []).filter(
+ (reference) => reference.id !== response.id
+ )
+ return { ...values.issue, external_issues: [...externalIssues, response] }
+ }
+ return null
+ },
updateAssignee: ({ assignee }) => {
if (values.issue) {
return { ...values.issue, assignee }
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d987b74a7459..e50697c37916 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89386,10 +89386,9 @@ export namespace Schemas {
*/
repository?: string;
/**
- * Text to match against existing issue titles / keys in the provider.
- * @minLength 1
+ * Text to match against existing issue titles / keys in the provider. GitHub matches it as an exact phrase. Leave blank for recent issues.
*/
- search: string;
+ search?: string;
};
export type ErrorTrackingFingerprintsListParams = {