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): improve external reference search and labels (#101826)

Hugues Pouillot282ab9d3ae91
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 7e1a15986842..503301835d34 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -22532,6 +22532,9 @@
"ErrorTrackingExternalReference": {
"additionalProperties": false,
"properties": {
+ "external_id": {
+ "type": "string"
+ },
"external_url": {
"type": "string"
},
@@ -22540,9 +22543,12 @@
},
"integration": {
"$ref": "#/definitions/ErrorTrackingExternalReferenceIntegration"
+ },
+ "title": {
+ "type": "string"
}
},
- "required": ["id", "external_url", "integration"],
+ "required": ["id", "external_url", "external_id", "title", "integration"],
"type": "object"
},
"ErrorTrackingExternalReferenceIntegration": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 58435d373fd1..50087b057db8 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4385,6 +4385,8 @@ export type ErrorTrackingExternalReferenceIntegration = Pick<IntegrationType, 'i
export interface ErrorTrackingExternalReference {
id: string
external_url: string
+ external_id: string
+ title: string
integration: ErrorTrackingExternalReferenceIntegration
}
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index 77c0fd9cc016..3d92659e89ff 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -416,6 +416,30 @@ class GitHubIntegration(GitHubIntegrationBase):
status_code=response.status_code,
)
+ def _get_issue_by_number(self, repo_path: str, repository_name: str, issue_number: int) -> dict[str, Any] | None:
+ response = self.api_request(
+ "GET",
+ f"/repos/{repo_path}/issues/{issue_number}",
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}",
+ )
+ if response.status_code not in {200, 404}:
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: failed to retrieve issue {repo_path}#{issue_number}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ if response.status_code == 404:
+ return None
+
+ issue = response.json()
+ if issue.get("pull_request"):
+ return None
+ return {
+ "id": str(issue_number),
+ "title": issue.get("title") or f"#{issue_number}",
+ "url": issue.get("html_url") or "",
+ "external_context": {"repository": repository_name, "number": issue_number},
+ }
+
def search_issues(self, repository: str, query: str, *, limit: int = 25) -> list[dict[str, Any]]:
"""Search existing GitHub issues in a repository for the link-existing flow."""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
@@ -426,6 +450,12 @@ class GitHubIntegration(GitHubIntegrationBase):
# the org, matching what create_issue persists.
repository_name = repo_path.split("/", 1)[1]
+ issue_number_match = re.fullmatch(r"#?([1-9][0-9]{0,9})", query.strip())
+ if issue_number_match:
+ issue = self._get_issue_by_number(repo_path, repository_name, int(issue_number_match.group(1)))
+ if issue:
+ return [issue]
+
# Quote the user's text so search syntax in it (qualifiers like repo:, operators like OR)
# is matched literally instead of rewriting the query, which would fill the result page
# with foreign matches and hide valid ones.
diff --git a/posthog/models/integration/gitlab.py b/posthog/models/integration/gitlab.py
index be498230c27d..3d56f2e68eeb 100644
--- a/posthog/models/integration/gitlab.py
+++ b/posthog/models/integration/gitlab.py
@@ -1,6 +1,8 @@
"""GitLab integration."""
+import re
from typing import Any
+from urllib.parse import urlparse
import requests
@@ -17,12 +19,18 @@ class GitLabIntegration:
integration: model.Integration
@staticmethod
- def get(hostname: str, endpoint: str, project_access_token: str) -> dict:
- url = f"{hostname}/api/v4/{endpoint}"
+ def _validate_api_url(url: str) -> None:
+ if urlparse(url).scheme != "https":
+ raise GitLabIntegrationError("Invalid GitLab hostname: HTTPS is required")
allowed, error = is_url_allowed(url)
if not allowed:
raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")
+ @staticmethod
+ def get(hostname: str, endpoint: str, project_access_token: str) -> dict:
+ url = f"{hostname}/api/v4/{endpoint}"
+ GitLabIntegration._validate_api_url(url)
+
response = requests.get(
url,
headers={"PRIVATE-TOKEN": project_access_token},
@@ -36,9 +44,7 @@ class GitLabIntegration:
@staticmethod
def post(hostname: str, endpoint: str, project_access_token: str, json: dict) -> dict:
url = f"{hostname}/api/v4/{endpoint}"
- allowed, error = is_url_allowed(url)
- if not allowed:
- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")
+ GitLabIntegration._validate_api_url(url)
response = requests.post(
url,
@@ -111,9 +117,7 @@ class GitLabIntegration:
access_token = self.integration.sensitive_config.get("access_token")
url = f"{hostname}/api/v4/projects/{project_id}/issues/{issue_id}"
- allowed, error = is_url_allowed(url)
- if not allowed:
- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")
+ self._validate_api_url(url)
response = requests.put(
url,
@@ -125,37 +129,30 @@ class GitLabIntegration:
if response.status_code != 200:
raise GitLabIntegrationError(f"GitLabIntegration: failed to close issue: {response.text[:300]}")
- def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:
- """Search existing GitLab issues in the connected project for the link-existing flow."""
+ def _get_issue_by_iid(self, issue_iid: int) -> dict[str, Any] | None:
hostname = self.integration.config.get("hostname")
project_id = self.integration.config.get("project_id")
access_token = self.integration.sensitive_config.get("access_token")
+ url = f"{hostname}/api/v4/projects/{project_id}/issues/{issue_iid}"
+ self._validate_api_url(url)
- url = f"{hostname}/api/v4/projects/{project_id}/issues"
- allowed, error = is_url_allowed(url)
- if not allowed:
- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")
-
- # 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},
- params=params,
allow_redirects=False,
timeout=10,
)
+ if response.status_code == 404:
+ return None
if response.status_code != 200:
raise GitLabIntegrationError(
- f"GitLabIntegration: failed to search issues: {response.text[:300]}",
+ f"GitLabIntegration: failed to retrieve issue: {response.text[:300]}",
)
- issues = response.json()
- if not isinstance(issues, list):
- return []
+ issue = response.json()
+ return issue if isinstance(issue, dict) else None
+ @staticmethod
+ def _issue_results(issues: list[dict[str, Any]]) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
for issue in issues:
iid = issue.get("iid")
@@ -171,3 +168,39 @@ class GitLabIntegration:
}
)
return results
+
+ def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:
+ """Search existing GitLab issues in the connected project for the link-existing flow."""
+ issue_id_match = re.fullmatch(r"#?([1-9][0-9]{0,9})", query.strip())
+ if issue_id_match:
+ issue = self._get_issue_by_iid(int(issue_id_match.group(1)))
+ if issue:
+ return self._issue_results([issue])
+
+ hostname = self.integration.config.get("hostname")
+ project_id = self.integration.config.get("project_id")
+ access_token = self.integration.sensitive_config.get("access_token")
+ url = f"{hostname}/api/v4/projects/{project_id}/issues"
+ self._validate_api_url(url)
+
+ # 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},
+ params=params,
+ allow_redirects=False,
+ timeout=10,
+ )
+ if response.status_code != 200:
+ raise GitLabIntegrationError(
+ f"GitLabIntegration: failed to search issues: {response.text[:300]}",
+ )
+ issues = response.json()
+ if not isinstance(issues, list):
+ return []
+
+ return self._issue_results(issues)
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 025dfcea3337..37834439c974 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -891,6 +891,57 @@ class TestGitHubIntegrationModel(BaseTest):
sent_query = mock_request.call_args.kwargs["params"]["q"]
assert sent_query == 'repo:PostHog/posthog "crash repo:microsoft/vscode" in:title type:issue'
+ def test_search_issues_retrieves_an_issue_by_number(self):
+ integration = self.create_integration(
+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
+ )
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = {
+ "number": 42,
+ "title": "Checkout failed",
+ "html_url": "https://github.com/PostHog/posthog/issues/42",
+ }
+
+ with patch.object(github, "api_request", return_value=mock_response) as mock_request:
+ results = github.search_issues("posthog", "#42")
+
+ assert results == [
+ {
+ "id": "42",
+ "title": "Checkout failed",
+ "url": "https://github.com/PostHog/posthog/issues/42",
+ "external_context": {"repository": "posthog", "number": 42},
+ }
+ ]
+ assert mock_request.call_args.args == ("GET", "/repos/PostHog/posthog/issues/42")
+
+ def test_search_issues_falls_back_to_title_search_when_number_is_not_found(self):
+ integration = self.create_integration(
+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
+ )
+ github = GitHubIntegration(integration)
+ not_found_response = MagicMock(status_code=404)
+ search_response = MagicMock(status_code=200)
+ search_response.json.return_value = {
+ "items": [
+ {
+ "number": 84,
+ "title": "Migration for #42",
+ "html_url": "https://github.com/PostHog/posthog/issues/84",
+ "repository_url": "https://api.github.com/repos/PostHog/posthog",
+ }
+ ]
+ }
+
+ with patch.object(github, "api_request", side_effect=[not_found_response, search_response]) as mock_request:
+ results = github.search_issues("posthog", "#42")
+
+ assert [result["id"] for result in results] == ["84"]
+ assert mock_request.call_count == 2
+ assert mock_request.call_args.args == ("GET", "/search/issues")
+ assert mock_request.call_args.kwargs["params"]["q"] == 'repo:PostHog/posthog "#42" in:title type:issue'
+
def test_comment_on_pull_request_posts_to_issues_endpoint(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
github = GitHubIntegration(integration)
diff --git a/posthog/models/test/integration/test_gitlab.py b/posthog/models/test/integration/test_gitlab.py
index 8fbf55f8c56a..bb6f172e7475 100644
--- a/posthog/models/test/integration/test_gitlab.py
+++ b/posthog/models/test/integration/test_gitlab.py
@@ -1,7 +1,7 @@
"""Tests for the GitLab integration."""
import pytest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
class TestGitLabIntegrationSSRFProtection:
@@ -50,6 +50,16 @@ class TestGitLabIntegrationSSRFProtection:
mock_get.assert_not_called()
+ @patch("posthog.models.integration.gitlab.requests.get")
+ @patch("posthog.models.integration.gitlab.is_url_allowed", return_value=(True, None))
+ def test_get_rejects_http_before_sending_credentials(self, _mock_is_url_allowed, mock_get):
+ from posthog.models.integration import GitLabIntegration, GitLabIntegrationError
+
+ with pytest.raises(GitLabIntegrationError, match="HTTPS is required"):
+ GitLabIntegration.get("http://gitlab.example.com", "projects/1", "token123")
+
+ mock_get.assert_not_called()
+
@patch("posthog.models.integration.gitlab.requests.post")
@patch("posthog.models.integration.gitlab.is_url_allowed")
def test_post_validates_url_before_request(self, mock_is_url_allowed, mock_post):
@@ -62,3 +72,52 @@ class TestGitLabIntegrationSSRFProtection:
GitLabIntegration.post("http://192.168.1.1", "projects/1/issues", "token123", {"title": "test"})
mock_post.assert_not_called()
+
+
+class TestGitLabIntegrationModel:
+ @patch("posthog.models.integration.gitlab.requests.get")
+ @patch("posthog.models.integration.gitlab.is_url_allowed", return_value=(True, None))
+ def test_search_issues_filters_by_issue_id(self, _mock_is_url_allowed, mock_get):
+ from posthog.models.integration import GitLabIntegration
+
+ integration = MagicMock(
+ kind="gitlab",
+ config={"hostname": "https://gitlab.com", "project_id": 1},
+ sensitive_config={"access_token": "token123"},
+ )
+ mock_get.return_value.status_code = 200
+ mock_get.return_value.json.return_value = {
+ "iid": 42,
+ "title": "Checkout failed",
+ "web_url": "https://gitlab.com/acme/app/-/issues/42",
+ }
+
+ results = GitLabIntegration(integration).search_issues("#42")
+
+ assert results[0]["id"] == "42"
+ assert mock_get.call_args.args[0] == "https://gitlab.com/api/v4/projects/1/issues/42"
+ assert "params" not in mock_get.call_args.kwargs
+
+ @patch("posthog.models.integration.gitlab.requests.get")
+ @patch("posthog.models.integration.gitlab.is_url_allowed", return_value=(True, None))
+ def test_search_issues_falls_back_to_title_search_when_issue_id_is_not_found(self, _mock_is_url_allowed, mock_get):
+ from posthog.models.integration import GitLabIntegration
+
+ integration = MagicMock(
+ kind="gitlab",
+ config={"hostname": "https://gitlab.com", "project_id": 1},
+ sensitive_config={"access_token": "token123"},
+ )
+ issue_id_response = MagicMock(status_code=404)
+ title_response = MagicMock(status_code=200)
+ title_response.json.return_value = [
+ {"iid": 84, "title": "Migration for #42", "web_url": "https://gitlab.com/acme/app/-/issues/84"}
+ ]
+ mock_get.side_effect = [issue_id_response, title_response]
+
+ results = GitLabIntegration(integration).search_issues("#42")
+
+ assert [result["id"] for result in results] == ["84"]
+ assert mock_get.call_count == 2
+ assert mock_get.call_args.kwargs["params"]["search"] == "#42"
+ assert "iids[]" not in mock_get.call_args.kwargs["params"]
diff --git a/posthog/schema.py b/posthog/schema.py
index ff39d293c268..80f6e964e17f 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -17354,9 +17354,11 @@ class ErrorTrackingExternalReference(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ external_id: str
external_url: str
id: str
integration: ErrorTrackingExternalReferenceIntegration
+ title: str
class ErrorTrackingFingerprintProjectionQueryResponse(BaseModel):
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 580abbcf9149..52e71d707609 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -5351,9 +5351,11 @@ export interface ErrorTrackingExternalReferenceIntegrationApi {
}
export interface ErrorTrackingExternalReferenceApi {
+ external_id: string
external_url: string
id: string
integration: ErrorTrackingExternalReferenceIntegrationApi
+ title: string
}
export interface FirstEventApi {
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 6e917da72c89..c3fb8e982de0 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -61,6 +61,8 @@ def _to_external_reference(reference) -> contracts.ErrorTrackingExternalReferenc
display_name=integration.display_name,
),
external_url=external_references.build_external_issue_url(reference),
+ external_id=external_references.external_issue_id(reference),
+ title=external_references.external_issue_title(reference),
)
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index d8b5759f8085..9f95626b6f34 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -69,6 +69,8 @@ class ErrorTrackingExternalReference:
id: UUID
integration: ErrorTrackingExternalReferenceIntegration
external_url: str
+ external_id: str
+ title: str
@dataclass(frozen=True)
diff --git a/products/error_tracking/backend/logic/external_references.py b/products/error_tracking/backend/logic/external_references.py
index f453e6e8bffc..48a639096294 100644
--- a/products/error_tracking/backend/logic/external_references.py
+++ b/products/error_tracking/backend/logic/external_references.py
@@ -93,7 +93,7 @@ def _validate_external_reference_config(integration: Integration, config: Any) -
def _clean_existing_external_context(integration: Integration, external_context: Any) -> dict[str, Any]:
"""Validate and normalize the external_context for linking an already-existing issue.
- Keeps only the provider keys build_external_issue_url reads, so we never persist arbitrary
+ Keeps the provider identifier fields and an optional title, so we never persist arbitrary
client-supplied data on the reference.
"""
if not isinstance(external_context, dict):
@@ -128,6 +128,15 @@ def _clean_existing_external_context(integration: Integration, external_context:
# segments with traversal semantics.
raise error
cleaned[field] = value
+
+ title = external_context.get("title")
+ if title is not None:
+ if not isinstance(title, str) or not title.strip() or len(title.strip()) > 500:
+ raise ErrorTrackingExternalReferenceValidationError(
+ "External reference title must be a non-blank string with at most 500 characters."
+ )
+ cleaned["title"] = title.strip()
+
return cleaned
@@ -178,14 +187,21 @@ def create_external_reference(
if not is_supported_external_issue_provider(integration.kind):
raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
stored_context = _clean_existing_external_context(integration, external_context)
+ identifier_context = {
+ field: stored_context[field] for field in LINK_EXISTING_REQUIRED_CONTEXT_FIELDS[integration.kind]
+ }
# Linking is idempotent: retries and double-clicks must not duplicate the
# reference (references cannot be deleted) or re-attach in the provider.
# Containment (not equality) also matches references the create flow stored
# with extra provider keys alongside the identifier.
existing = ErrorTrackingExternalReference.objects.filter(
- issue=issue, integration=integration, external_context__contains=stored_context
+ issue=issue, integration=integration, external_context__contains=identifier_context
).first()
if existing is not None:
+ title = stored_context.get("title")
+ if title and (existing.external_context or {}).get("title") != title:
+ existing.external_context = {**(existing.external_context or {}), "title": title}
+ existing.save(update_fields=["external_context"])
return existing, False
if integration.kind == Integration.IntegrationKind.LINEAR:
# Linked issues get the same PostHog back-link attachment as created ones.
@@ -199,6 +215,8 @@ def create_external_reference(
_validate_external_reference_config(integration, config)
provider_config = dict(config or {})
+ title = provider_config["title"].strip()
+ provider_config["title"] = title
if integration.kind == Integration.IntegrationKind.GITHUB:
created_context = GitHubIntegration(integration).create_issue(provider_config)
@@ -212,6 +230,7 @@ def create_external_reference(
else:
raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
+ created_context["title"] = title
return ErrorTrackingExternalReference.objects.create(
issue=issue,
integration=integration,
@@ -264,3 +283,28 @@ def search_external_issues(
def build_external_issue_url(reference: ErrorTrackingExternalReference) -> str:
return external_issue_url(reference.integration, reference.external_context)
+
+
+def external_issue_id(reference: ErrorTrackingExternalReference) -> str:
+ external_context = reference.external_context or {}
+ id_field = {
+ Integration.IntegrationKind.GITHUB.value: "number",
+ Integration.IntegrationKind.GITLAB.value: "issue_id",
+ Integration.IntegrationKind.LINEAR.value: "id",
+ Integration.IntegrationKind.JIRA.value: "key",
+ }.get(reference.integration.kind)
+ value = external_context.get(id_field) if id_field else reference.external_id
+ if value is None:
+ return ""
+ external_id = str(value)
+ if reference.integration.kind in {
+ Integration.IntegrationKind.GITHUB,
+ Integration.IntegrationKind.GITLAB,
+ } and not external_id.startswith("#"):
+ return f"#{external_id}"
+ return external_id
+
+
+def external_issue_title(reference: ErrorTrackingExternalReference) -> str:
+ title = (reference.external_context or {}).get("title")
+ return title if isinstance(title, str) else ""
diff --git a/products/error_tracking/backend/presentation/views/external_references.py b/products/error_tracking/backend/presentation/views/external_references.py
index 8d9f5faeea1a..c387a3290fb0 100644
--- a/products/error_tracking/backend/presentation/views/external_references.py
+++ b/products/error_tracking/backend/presentation/views/external_references.py
@@ -58,6 +58,8 @@ class ErrorTrackingExternalReferenceResultSerializer(serializers.Serializer):
external_url = serializers.SerializerMethodField(
help_text="URL of the linked external issue in the provider's system."
)
+ external_id = serializers.CharField(read_only=True, help_text="Provider-native identifier of the linked issue.")
+ title = serializers.CharField(read_only=True, help_text="Title of the linked issue.")
@extend_schema_field(serializers.CharField())
def get_external_url(self, reference: contracts.ErrorTrackingExternalReference) -> str:
@@ -102,7 +104,7 @@ class ErrorTrackingExternalReferenceLinkSerializer(serializers.Serializer):
external_context = ExternalReferenceContextField(
write_only=True,
help_text=(
- "Identifier of the existing external issue to link, as returned by the search-issues endpoint. "
+ "Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. "
"Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; "
"linear -> {id}; jira -> {key}."
),
@@ -118,7 +120,7 @@ class ErrorTrackingExternalIssueSearchQuerySerializer(serializers.Serializer):
allow_blank=True,
default="",
help_text=(
- "Text to match against existing issue titles / keys in the provider. GitHub matches it "
+ "Text to match against existing issue titles or identifiers in the provider. GitHub matches titles "
"as an exact phrase. Leave blank for recent issues."
),
)
diff --git a/products/error_tracking/backend/test/test_facade_api.py b/products/error_tracking/backend/test/test_facade_api.py
index bf4027f72056..993fa07655cb 100644
--- a/products/error_tracking/backend/test/test_facade_api.py
+++ b/products/error_tracking/backend/test/test_facade_api.py
@@ -116,16 +116,19 @@ class TestErrorTrackingFacadeAPI(BaseTest):
sensitive_config={"access_token": "access-token"},
)
- api.create_external_reference(
+ reference = api.create_external_reference(
team_id=self.team.id,
issue_id=issue.id,
integration_id=integration.id,
- config={"team_id": "linear-team-id", "title": "Checkout TypeError", "description": ""},
+ config={"team_id": "linear-team-id", "title": " Checkout TypeError ", "description": ""},
distinct_id=self.user.id,
)
attachment_url = mock_create_issue.call_args.args[0]
+ assert mock_create_issue.call_args.args[1]["title"] == "Checkout TypeError"
assert attachment_url.endswith(f"/project/{self.team.id}/error_tracking/fingerprint/fp%2Fwith%23chars")
+ assert reference.external_id == "LIN-1"
+ assert reference.title == "Checkout TypeError"
@override_settings(LINEAR_APP_CLIENT_ID="linear-client-id", LINEAR_APP_CLIENT_SECRET="linear-client-secret")
@patch("products.error_tracking.backend.logic.external_references.LinearIntegration.create_issue")
@@ -195,7 +198,7 @@ class TestErrorTrackingFacadeAPI(BaseTest):
team_id=self.team.id,
issue_id=issue.id,
integration_id=integration.id,
- external_context={"id": "ENG-42"},
+ external_context={"id": "ENG-42", "title": "Checkout TypeError"},
distinct_id=self.user.id,
)
@@ -204,16 +207,19 @@ class TestErrorTrackingFacadeAPI(BaseTest):
assert linked_issue_id == "ENG-42"
assert f"/project/{self.team.id}/error_tracking/" in attachment_url
assert reference.external_url == "https://linear.app/acme/issue/ENG-42"
+ assert reference.external_id == "ENG-42"
+ assert reference.title == "Checkout TypeError"
# Linking the same issue again returns the existing reference without re-attaching.
duplicate = api.create_external_reference(
team_id=self.team.id,
issue_id=issue.id,
integration_id=integration.id,
- external_context={"id": "ENG-42"},
+ external_context={"id": "ENG-42", "title": "Updated title"},
distinct_id=self.user.id,
)
assert duplicate.id == reference.id
+ assert duplicate.title == "Updated title"
assert mock_create_attachment.call_count == 1
created_events = [
call
diff --git a/products/error_tracking/frontend/ErrorTracking.stories.tsx b/products/error_tracking/frontend/ErrorTracking.stories.tsx
index 96c44f336f4c..e62ac2401cdc 100644
--- a/products/error_tracking/frontend/ErrorTracking.stories.tsx
+++ b/products/error_tracking/frontend/ErrorTracking.stories.tsx
@@ -14,6 +14,7 @@ import { mswDecorator } from '~/mocks/browser'
import {
ErrorTrackingIssueRelease,
ErrorTrackingQueryResponse,
+ ErrorTrackingRelationalIssue,
ErrorTrackingReleasesQueryResponse,
NodeKind,
TrendsQueryResponse,
@@ -362,12 +363,21 @@ const STORY_ASSIGNEE_ROLES = Array.from({ length: 16 }, (_, index) => {
created_by: MOCK_DEFAULT_BASIC_USER,
}
})
-const STORY_ISSUE = {
+const STORY_ISSUE: ErrorTrackingRelationalIssue = {
...errorTrackingTypeIssue,
id: ISSUE_ID,
name: 'Non-OK response',
description: 'The billing request returned an unsuccessful response.',
first_seen: STORY_TIMESTAMPS.at(-1)!,
+ external_issues: [
+ {
+ id: '01890a1b-2c3d-4e4f-8a9b-0c1d2e3f4a6c',
+ external_url: 'https://github.com/example/example/issues/42',
+ external_id: '#42',
+ title: 'Checkout failed for annual subscriptions',
+ integration: { id: 1, kind: 'github', display_name: 'Example' },
+ },
+ ],
}
const STORY_SUMMARY_RESPONSE: ErrorTrackingQueryResponse = {
...errorTrackingQueryResponse,
diff --git a/products/error_tracking/frontend/components/ExternalReferences.tsx b/products/error_tracking/frontend/components/ExternalReferences.tsx
index 8fb22fd4e167..869274eaa583 100644
--- a/products/error_tracking/frontend/components/ExternalReferences.tsx
+++ b/products/error_tracking/frontend/components/ExternalReferences.tsx
@@ -119,8 +119,18 @@ export const ExternalReferences = (): JSX.Element | null => {
}}
>
<ButtonPrimitive fullWidth disabled={issueLoading}>
- <IntegrationIcon kind={reference.integration.kind} />
- {reference.integration.display_name}
+ <div className="flex items-center gap-2 min-w-0 w-full">
+ <IntegrationIcon kind={reference.integration.kind} />
+ <span className="truncate min-w-0 flex-1 text-left">
+ {reference.title ||
+ PROVIDER_LABELS[reference.integration.kind as ErrorTrackingIntegrationKind]}
+ </span>
+ {reference.external_id && (
+ <span className="text-sm text-muted flex-shrink-0 ml-auto">
+ {reference.external_id}
+ </span>
+ )}
+ </div>
</ButtonPrimitive>
</Link>
))}
@@ -392,7 +402,7 @@ function linkExistingIssueForm(integration: ErrorTrackingIntegration, onSubmit:
},
onSubmit: ({ externalIssue }) => {
if (externalIssue) {
- onSubmit(integration.id, externalIssue.external_context)
+ onSubmit(integration.id, { ...externalIssue.external_context, title: externalIssue.title })
}
},
})
@@ -420,12 +430,17 @@ function ExistingIssueSelect({
const selectedKey = value ? optionKey(value) : null
const options = results.map((result) => ({
key: optionKey(result),
- label: result.title,
+ label: `${result.title} ${formatExternalIssueId(result.id, kind)}`,
+ labelComponent: externalIssueOptionLabel(result, kind),
}))
// A results refresh must not visually drop a valid selection, so the selected
// issue stays in the options even when the fresh results no longer include it.
if (value && selectedKey && !options.some((option) => option.key === selectedKey)) {
- options.push({ key: selectedKey, label: value.title })
+ options.push({
+ key: selectedKey,
+ label: `${value.title} ${formatExternalIssueId(value.id, kind)}`,
+ labelComponent: externalIssueOptionLabel(value, kind),
+ })
}
return (
@@ -443,6 +458,7 @@ function ExistingIssueSelect({
<LemonInputSelect
mode="single"
data-attr="select-existing-issue"
+ popoverClassName="[&_.LemonButton__content>span]:grow [&_.LemonButton__content>span]:min-w-0"
placeholder={
requiresRepository && !repository ? 'Select a repository first...' : 'Search for an issue...'
}
@@ -476,6 +492,22 @@ function ExistingIssueSelect({
)
}
+function externalIssueOptionLabel(
+ issue: ErrorTrackingExternalIssueResultApi,
+ kind: ErrorTrackingIntegrationKind
+): JSX.Element {
+ return (
+ <span className="flex items-center justify-between gap-2 min-w-0 w-full">
+ <span className="truncate">{issue.title}</span>
+ <span className="text-muted flex-shrink-0">{formatExternalIssueId(issue.id, kind)}</span>
+ </span>
+ )
+}
+
+function formatExternalIssueId(id: string, kind: ErrorTrackingIntegrationKind): string {
+ return (kind === 'github' || kind === 'gitlab') && !id.startsWith('#') ? `#${id}` : id
+}
+
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/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index a2775ae6500c..c2f8986f6f09 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -722,6 +722,10 @@ export interface ErrorTrackingExternalReferenceResultApi {
readonly integration: ErrorTrackingExternalReferenceIntegrationResultApi
/** URL of the linked external issue in the provider's system. */
readonly external_url: string
+ /** Provider-native identifier of the linked issue. */
+ readonly external_id: string
+ /** Title of the linked issue. */
+ readonly title: string
}
export interface PaginatedErrorTrackingExternalReferenceResultListApi {
@@ -748,6 +752,10 @@ export interface ErrorTrackingExternalReferenceCreateApi {
readonly integration: ErrorTrackingExternalReferenceIntegrationResultApi
/** URL of the linked external issue in the provider's system. */
readonly external_url: string
+ /** Provider-native identifier of the linked issue. */
+ readonly external_id: string
+ /** Title of the linked issue. */
+ readonly title: string
/** ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira'). */
integration_id: number
/** Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}. */
@@ -757,7 +765,7 @@ export interface ErrorTrackingExternalReferenceCreateApi {
}
/**
- * Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
+ * Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
*/
export type ErrorTrackingExternalReferenceLinkApiExternalContext = { [key: string]: unknown }
@@ -766,7 +774,7 @@ export interface ErrorTrackingExternalReferenceLinkApi {
integration_id: number
/** ID of the error tracking issue to link the reference to. */
issue: string
- /** Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
+ /** Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
external_context: ErrorTrackingExternalReferenceLinkApiExternalContext
}
@@ -2295,7 +2303,7 @@ export type ErrorTrackingExternalReferencesSearchIssuesRetrieveParams = {
*/
repository?: string
/**
- * Text to match against existing issue titles / keys in the provider. GitHub matches it as an exact phrase. Leave blank for recent issues.
+ * Text to match against existing issue titles or identifiers in the provider. GitHub matches titles as an exact phrase. Leave blank for recent issues.
*/
search?: string
}
diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.ts
index c4d736da781b..b418c071b9bb 100644
--- a/products/error_tracking/frontend/generated/api.zod.ts
+++ b/products/error_tracking/frontend/generated/api.zod.ts
@@ -404,7 +404,7 @@ export const ErrorTrackingExternalReferencesLinkIssueCreateBody = /* @__PURE__ *
external_context: zod
.record(zod.string(), zod.unknown())
.describe(
- 'Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.'
+ 'Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.'
),
})
@@ -550,6 +550,8 @@ export const ErrorTrackingIssuesCohortUpdateBody = /* @__PURE__ */ zod
})
.describe('The connected integration this reference was created through.'),
external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
+ external_id: zod.string().describe('Provider-native identifier of the linked issue.'),
+ title: zod.string().describe('Title of the linked issue.'),
})
.describe('Read-only shape of an external reference, shared by every response.')
),
@@ -617,6 +619,8 @@ export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod
})
.describe('The connected integration this reference was created through.'),
external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
+ external_id: zod.string().describe('Provider-native identifier of the linked issue.'),
+ title: zod.string().describe('Title of the linked issue.'),
})
.describe('Read-only shape of an external reference, shared by every response.')
),
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 8b042a1f354f..3c98e4416efd 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -4311,9 +4311,11 @@ export interface ErrorTrackingExternalReferenceIntegrationApi {
}
export interface ErrorTrackingExternalReferenceApi {
+ external_id: string
external_url: string
id: string
integration: ErrorTrackingExternalReferenceIntegrationApi
+ title: string
}
export interface FirstEventApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5a373df42dc8..a2dc91309343 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7233,9 +7233,11 @@ export namespace Schemas {
}
export interface ErrorTrackingExternalReference {
+ external_id: string;
external_url: string;
id: string;
integration: ErrorTrackingExternalReferenceIntegration;
+ title: string;
}
export interface FirstEvent {
@@ -34488,6 +34490,10 @@ export namespace Schemas {
readonly integration: ErrorTrackingExternalReferenceIntegrationResult;
/** URL of the linked external issue in the provider's system. */
readonly external_url: string;
+ /** Provider-native identifier of the linked issue. */
+ readonly external_id: string;
+ /** Title of the linked issue. */
+ readonly title: string;
/** ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira'). */
integration_id: number;
/** Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}. */
@@ -34497,7 +34503,7 @@ export namespace Schemas {
}
/**
- * Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
+ * Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
*/
export type ErrorTrackingExternalReferenceLinkExternalContext = { [key: string]: unknown };
@@ -34506,7 +34512,7 @@ export namespace Schemas {
integration_id: number;
/** ID of the error tracking issue to link the reference to. */
issue: string;
- /** Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
+ /** Identifier and optional title of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
external_context: ErrorTrackingExternalReferenceLinkExternalContext;
}
@@ -34520,6 +34526,10 @@ export namespace Schemas {
readonly integration: ErrorTrackingExternalReferenceIntegrationResult;
/** URL of the linked external issue in the provider's system. */
readonly external_url: string;
+ /** Provider-native identifier of the linked issue. */
+ readonly external_id: string;
+ /** Title of the linked issue. */
+ readonly title: string;
}
export interface ErrorTrackingFingerprint {
@@ -103134,7 +103144,7 @@ export namespace Schemas {
*/
repository?: string;
/**
- * Text to match against existing issue titles / keys in the provider. GitHub matches it as an exact phrase. Leave blank for recent issues.
+ * Text to match against existing issue titles or identifiers in the provider. GitHub matches titles as an exact phrase. Leave blank for recent issues.
*/
search?: string;
};