: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(integrations): add issue search and Linear attachments to providers (#79953)
Catalin186bca7c3f72
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex c4176523e728..0b4a549e4cdf 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -3269,7 +3269,26 @@ class LinearIntegration:variables={"title": title, "description": description, "teamId": linear_team_id},)linear_issue_id = dot_get(body, "data.issueCreate.issue.identifier")+ # Linear reports failures in a 200 body; without this check a failed create would+ # persist a reference with id None. Nothing was created, so raising is safe.+ if body.get("errors") or not linear_issue_id:+ raise ValidationError("Failed to create the Linear issue")+ # Best-effort: the Linear issue already exists at this point, so failing the whole+ # create over a missing back-link would produce duplicate issues on retry.+ try:+ self.create_attachment(linear_issue_id, attachment_url)+ except ValidationError:+ logger.warning("linear_issue_attachment_failed", issue_id=linear_issue_id)++ return {"id": linear_issue_id}++ def create_attachment(self, issue_id: str, url: str) -> None:+ """Attach a PostHog issue link to a Linear issue (shows as a back-link in Linear).++ Raises on failure: Linear reports errors in the GraphQL body with HTTP 200,+ and the mutation itself can report success=false.+ """link_attachment_query = """mutation AttachmentCreate($issueId: String!, $title: String!, $url: String!) {attachmentCreate(input: { issueId: $issueId, title: $title, url: $url }) {@@ -3277,12 +3296,41 @@ class LinearIntegration:}}"""- self.query(+ body = self.query(link_attachment_query,- variables={"issueId": linear_issue_id, "title": "PostHog issue", "url": attachment_url},+ variables={"issueId": issue_id, "title": "PostHog issue", "url": url},)-- return {"id": linear_issue_id}+ if body.get("errors") or not dot_get(body, "data.attachmentCreate.success"):+ 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 }+ }+ }+ """+ body = self.query(search_query, variables={"term": query, "first": limit})+ if body.get("errors") or dot_get(body, "data.searchIssues") is None:+ raise ValidationError("Failed to search Linear issues")+ nodes = dot_get(body, "data.searchIssues.nodes") or []+ results: list[dict[str, Any]] = []+ for node in nodes:+ identifier = node.get("identifier")+ if not identifier:+ continue+ results.append(+ {+ "id": identifier,+ "title": node.get("title") or identifier,+ "url": node.get("url") or "",+ # Matches the shape LinearIntegration.create_issue stores.+ "external_context": {"id": identifier},+ }+ )+ return resultsdef query(self, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:response = requests.post(@@ -3439,6 +3487,55 @@ class JiraIntegration:return {"key": issue["key"], "id": issue.get("id", "")}+ def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:+ """Search existing Jira issues for the link-existing flow.++ Uses Jira's purpose-built issue picker endpoint, which matches on summary and+ issue key without us having to build (and escape) a JQL string from user input.+ """+ cloud_id = self.cloud_id()+ if not cloud_id:+ raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")++ self._ensure_token_valid()++ response = requests.get(+ f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue/picker",+ headers={+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "Accept": "application/json",+ },+ # Without currentJQL the picker only returns history suggestions (issues the+ # user recently viewed); this constant JQL makes it search all accessible issues.+ params={"query": query, "currentJQL": "order by created DESC", "showSubTasks": "true"},+ timeout=10,+ )+ if response.status_code != 200:+ raise ValidationError(f"Failed to search Jira issues (status {response.status_code})")+ body = response.json()++ site_url = self.site_url()+ results: list[dict[str, Any]] = []+ seen_keys: set[str] = set()+ for section in body.get("sections", []) or []:+ for issue in section.get("issues", []) or []:+ key = issue.get("key")+ if not key or key in seen_keys:+ continue+ seen_keys.add(key)+ results.append(+ {+ "id": str(issue.get("id", "")),+ "title": issue.get("summaryText") or issue.get("summary") or key,+ "url": f"{site_url}/browse/{key}" if site_url else "",+ # Matches the shape JiraIntegration.create_issue stores.+ "external_context": {"key": key, "id": str(issue.get("id", ""))},+ }+ )+ if len(results) >= limit:+ return results+ return results+# Default branches change rarely; a multi-hour TTL is plenty to avoid hitting# GitHub on every paginated branch request while keeping the window in which a@@ -3758,6 +3855,58 @@ class GitHubIntegration(GitHubIntegrationBase):return {"number": issue["number"], "repository": repository}+ 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}"+ if not _is_safe_github_repo_path(repo_path):+ raise GitHubIntegrationError(f"GitHubIntegration: invalid repository path {repo_path!r}")++ # `repository` is stored bare in external_context so build_external_issue_url can re-prefix+ # the org, matching what create_issue persists.+ repository_name = repo_path.split("/", 1)[1]++ # 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.+ search_term = query.replace("\\", " ").replace('"', " ").strip()+ q = f'repo:{repo_path} "{search_term}" in:title type:issue' if search_term else f"repo:{repo_path} type:issue"++ response = self.api_request(+ "GET",+ "/search/issues",+ endpoint="/search/issues",+ params={"q": q, "per_page": limit},+ )+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"GitHubIntegration: failed to search issues in {repo_path}: {response.text[:300]}",+ status_code=response.status_code,+ )++ results: list[dict[str, Any]] = []+ for issue in response.json().get("items", []) or []:+ number = issue.get("number")+ if number is None:+ continue+ # The issues search API returns pull requests too; those aren't linkable issues.+ if issue.get("pull_request"):+ continue+ # Search-syntax operators in the user's query (e.g. "foo OR bar") can escape the+ # repo: qualifier, so drop anything that isn't actually from the chosen repository.+ repository_url = issue.get("repository_url") or ""+ if not repository_url.lower().endswith(f"/repos/{repo_path.lower()}"):+ continue+ results.append(+ {+ "id": str(number),+ "title": issue.get("title") or f"#{number}",+ "url": issue.get("html_url") or "",+ # Matches the shape GitHubIntegration.create_issue stores.+ "external_context": {"repository": repository_name, "number": number},+ }+ )+ return results+def create_branch(self, repository: str, branch_name: str, base_branch: str | None = None) -> dict[str, Any]:"""Create a new branch from a base branch."""org = self.organization()@@ -4144,6 +4293,49 @@ class GitLabIntegration:return {"issue_id": issue["iid"]}+ 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."""+ 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"+ allowed, error = is_url_allowed(url)+ if not allowed:+ raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")++ params: dict[str, str | int] = {"search": query, "per_page": limit, "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 []++ results: list[dict[str, Any]] = []+ for issue in issues:+ iid = issue.get("iid")+ if iid is None:+ continue+ results.append(+ {+ "id": str(iid),+ "title": issue.get("title") or f"#{iid}",+ "url": issue.get("web_url") or "",+ # Matches the shape GitLabIntegration.create_issue stores.+ "external_context": {"issue_id": iid},+ }+ )+ return results+class MetaGraphIntegration:"""Token handling shared by the Meta Graph OAuth kinds (Meta Ads, Instagram).diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 503202fe6580..daa278886b2d 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -203,6 +203,58 @@ class TestLinearIntegrationModel(BaseTest):sensitive_config={"access_token": "ACCESS_TOKEN"},)+ def test_search_issues_raises_on_graphql_errors(self):+ # An expired token or GraphQL error must not be reported as a valid empty result.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value={"errors": [{"message": "unauthorized"}]}):+ with self.assertRaises(ValidationError):+ linear.search_issues("boom")++ @parameterized.expand(+ [+ ("top_level_errors", {"errors": [{"message": "forbidden"}]}),+ ("mutation_failure", {"data": {"attachmentCreate": {"success": False}}}),+ ]+ )+ def test_create_attachment_raises_on_failure(self, _name, response_body):+ # Linear reports failures in a 200 body; treating them as success would let callers+ # persist references whose promised back-link was never created.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value=response_body):+ with self.assertRaises(ValidationError):+ linear.create_attachment("LIN-123", "https://us.posthog.com/error_tracking/issue-id")++ def test_create_issue_raises_when_issue_creation_fails(self):+ # A failed issueCreate must not fall through to an attachment attempt and a+ # persisted {"id": None} reference.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value={"errors": [{"message": "forbidden"}]}) as mock_query:+ with self.assertRaises(ValidationError):+ linear.create_issue(+ "https://us.posthog.com/error_tracking/issue-id",+ {"team_id": "team-id", "title": "Title", "description": "Description"},+ )+ assert mock_query.call_count == 1++ def test_create_issue_succeeds_when_attachment_fails(self):+ # The Linear issue already exists when the attachment fires, so a failed back-link+ # must not fail the create (retrying would duplicate the issue).+ linear = LinearIntegration(self.create_integration())+ with patch.object(+ linear,+ "query",+ side_effect=[+ {"data": {"issueCreate": {"issue": {"identifier": "LIN-123"}}}},+ {"errors": [{"message": "rate limited"}]},+ ],+ ):+ result = linear.create_issue(+ "https://us.posthog.com/error_tracking/issue-id",+ {"team_id": "team-id", "title": "Title", "description": "Description"},+ )++ assert result == {"id": "LIN-123"}+def test_create_issue_passes_user_fields_as_graphql_variables(self):linear = LinearIntegration(self.create_integration())with patch.object(@@ -2265,6 +2317,46 @@ class TestGitHubIntegrationModel(BaseTest):assert result["success"] is Falsemock_patch.assert_not_called()+ def test_search_issues_drops_results_from_other_repositories(self):+ # Search-syntax operators in the query (e.g. "foo OR bar") can escape the repo:+ # qualifier, so results must be filtered by the repository they actually belong to.+ 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 = {+ "items": [+ {+ "number": 1,+ "title": "In repo",+ "html_url": "https://github.com/PostHog/posthog/issues/1",+ "repository_url": "https://api.github.com/repos/PostHog/posthog",+ },+ {+ "number": 2,+ "title": "Other repo",+ "html_url": "https://github.com/PostHog/other/issues/2",+ "repository_url": "https://api.github.com/repos/PostHog/other",+ },+ {+ "number": 3,+ "title": "A pull request",+ "html_url": "https://github.com/PostHog/posthog/pull/3",+ "repository_url": "https://api.github.com/repos/PostHog/posthog",+ "pull_request": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/3"},+ },+ ]+ }+ with patch.object(github, "api_request", return_value=mock_response) as mock_request:+ results = github.search_issues("posthog", 'crash" repo:microsoft/vscode "')+ assert [result["id"] for result in results] == ["1"]+ assert results[0]["external_context"] == {"repository": "posthog", "number": 1}+ # The user's text is quoted so its qualifiers and operators match literally instead of+ # rewriting the query and filling the result page with foreign matches.+ 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_comment_on_pull_request_posts_to_issues_endpoint(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)