Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(blocks): Add GitHub notification management blocks (#13634)

Reinier van der Leer5e548164e1cb
diff --git a/autogpt_platform/backend/backend/blocks/github/_api.py b/autogpt_platform/backend/backend/blocks/github/_api.py
index 03e4926673..f04f812d02 100644
--- a/autogpt_platform/backend/backend/blocks/github/_api.py
+++ b/autogpt_platform/backend/backend/blocks/github/_api.py
@@ -1,4 +1,4 @@
-from typing import overload
+from typing import Callable, Optional, overload
from urllib.parse import urlparse
from backend.blocks.github._auth import (
@@ -7,6 +7,8 @@ from backend.blocks.github._auth import (
)
from backend.util.request import URL, Requests
+GITHUB_API_URL = "https://api.github.com"
+
@overload
def _convert_to_api_url(url: str) -> str: ...
@@ -28,7 +30,7 @@ def _convert_to_api_url(url: str | URL) -> str | URL:
if len(path_parts) >= 2:
owner, repo = path_parts[0], path_parts[1]
- api_base = f"https://api.github.com/repos/{owner}/{repo}"
+ api_base = f"{GITHUB_API_URL}/repos/{owner}/{repo}"
if len(path_parts) > 2:
additional_path = "/".join(path_parts[2:])
@@ -79,9 +81,7 @@ def convert_comment_url_to_api_endpoint(comment_url: str) -> str:
owner, repo = path_parts[0], path_parts[1]
# Construct API URL for issue comments
- return (
- f"https://api.github.com/repos/{owner}/{repo}/issues/comments/{comment_id}"
- )
+ return f"{GITHUB_API_URL}/repos/{owner}/{repo}/issues/comments/{comment_id}"
# Handle PR review comments (#discussion_r)
elif "#discussion_r" in comment_url:
@@ -94,9 +94,7 @@ def convert_comment_url_to_api_endpoint(comment_url: str) -> str:
owner, repo = path_parts[0], path_parts[1]
# Construct API URL for PR review comments
- return (
- f"https://api.github.com/repos/{owner}/{repo}/pulls/comments/{comment_id}"
- )
+ return f"{GITHUB_API_URL}/repos/{owner}/{repo}/pulls/comments/{comment_id}"
# If no specific comment identifiers are found, use the general URL conversion
return _convert_to_api_url(comment_url)
@@ -107,7 +105,38 @@ def get_api(
convert_urls: bool = True,
) -> Requests:
return Requests(
- trusted_origins=["https://api.github.com", "https://github.com"],
+ trusted_origins=[GITHUB_API_URL, "https://github.com"],
extra_url_validator=_convert_to_api_url if convert_urls else None,
extra_headers=_get_headers(credentials),
)
+
+
+async def get_paginated(
+ api: Requests,
+ url: str,
+ *,
+ limit: int,
+ params: Optional[dict[str, str]] = None,
+ keep: Optional[Callable[[dict], bool]] = None,
+ max_page_size: int = 100,
+ start_page: int = 1,
+) -> list[dict]:
+ """
+ Fetches items from a paginated GitHub list endpoint until `limit` items
+ are collected or no pages are left. Items are filtered by `keep` (if given)
+ before counting towards `limit`. Fetching starts at `start_page`.
+ """
+ items: list[dict] = []
+ page_size = max_page_size if keep else min(limit, max_page_size)
+ page = start_page
+ while len(items) < limit:
+ response = await api.get(
+ url,
+ params={**(params or {}), "per_page": str(page_size), "page": str(page)},
+ )
+ batch = response.json()
+ items.extend(item for item in batch if keep is None or keep(item))
+ if len(batch) < page_size:
+ break
+ page += 1
+ return items[:limit]
diff --git a/autogpt_platform/backend/backend/blocks/github/_utils.py b/autogpt_platform/backend/backend/blocks/github/_utils.py
index 434e619750..aaf620e9ed 100644
--- a/autogpt_platform/backend/backend/blocks/github/_utils.py
+++ b/autogpt_platform/backend/backend/blocks/github/_utils.py
@@ -1,3 +1,41 @@
+import re
+from urllib.parse import urlparse
+
+_GITHUB_HOSTS = ("github.com", "www.github.com")
+_OWNER_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$")
+_REPO_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
def github_repo_path(repo_url: str) -> str:
"""Extract 'owner/repo' from a GitHub repository URL."""
return repo_url.replace("https://github.com/", "")
+
+
+def normalize_repo_path(repo: str) -> str:
+ """
+ Normalise a repository reference to 'owner/repo'. Accepts both the bare
+ 'owner/repo' form and a full github.com URL, and rejects anything else.
+
+ Unlike `github_repo_path`, this validates its input, so the result is always
+ safe to interpolate into an API path.
+ """
+ value = repo.strip()
+ if "://" in value or value.lower().startswith(_GITHUB_HOSTS):
+ parsed = urlparse(value if "://" in value else f"https://{value}")
+ if (parsed.hostname or "").lower() not in _GITHUB_HOSTS:
+ raise ValueError(
+ f"Not a github.com repository URL: {repo!r}. "
+ "Expected '{owner}/{repo}' or 'https://github.com/{owner}/{repo}'."
+ )
+ value = parsed.path
+
+ parts = [part for part in value.strip("/").split("/") if part]
+ if len(parts) == 2:
+ owner, name = parts[0], parts[1].removesuffix(".git")
+ if _OWNER_RE.match(owner) and _REPO_NAME_RE.match(name) and name.strip("."):
+ return f"{owner}/{name}"
+
+ raise ValueError(
+ f"Invalid repository {repo!r}. "
+ "Expected '{owner}/{repo}' or 'https://github.com/{owner}/{repo}'."
+ )
diff --git a/autogpt_platform/backend/backend/blocks/github/commits.py b/autogpt_platform/backend/backend/blocks/github/commits.py
index 15ade36d63..d452ac3af4 100644
--- a/autogpt_platform/backend/backend/blocks/github/commits.py
+++ b/autogpt_platform/backend/backend/blocks/github/commits.py
@@ -1,5 +1,6 @@
import asyncio
from enum import StrEnum
+from typing import Optional
from urllib.parse import quote
from typing_extensions import TypedDict
@@ -16,7 +17,7 @@ from backend.data.model import SchemaField
from backend.util.file import parse_data_uri, resolve_media_content
from backend.util.type import MediaFileType
-from ._api import get_api
+from ._api import get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -38,16 +39,56 @@ class GithubListCommitsBlock(Block):
description="Branch name to list commits from",
default="main",
)
- per_page: int = SchemaField(
- description="Number of commits to return (max 100)",
- default=30,
+ limit: int = SchemaField(
+ description="Maximum number of commits to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ per_page: Optional[int] = SchemaField(
+ description="[Legacy] Number of commits to return per page (max 100). "
+ "If set (or `page` is set), `limit` is ignored.",
+ default=None,
ge=1,
le=100,
+ advanced=True,
)
- page: int = SchemaField(
- description="Page number for pagination",
- default=1,
+ page: Optional[int] = SchemaField(
+ description="[Legacy] Page number for pagination. "
+ "If set (or `per_page` is set), `limit` is ignored.",
+ default=None,
ge=1,
+ advanced=True,
+ )
+ path: str = SchemaField(
+ description="Only include commits that touch this file or directory path",
+ placeholder="src/main.py",
+ default="",
+ advanced=True,
+ )
+ author: str = SchemaField(
+ description="Only include commits authored by this user "
+ "(GitHub username or email address)",
+ default="",
+ advanced=True,
+ )
+ committer: str = SchemaField(
+ description="Only include commits committed by this user "
+ "(GitHub username or email address)",
+ default="",
+ advanced=True,
+ )
+ since: str = SchemaField(
+ description="Only include commits after the given ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
+ until: str = SchemaField(
+ description="Only include commits before the given ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
)
class Output(BlockSchemaOutput):
@@ -76,8 +117,6 @@ class GithubListCommitsBlock(Block):
test_input={
"repo_url": "https://github.com/owner/repo",
"branch": "main",
- "per_page": 30,
- "page": 1,
"credentials": TEST_CREDENTIALS_INPUT,
},
test_credentials=TEST_CREDENTIALS,
@@ -120,17 +159,32 @@ class GithubListCommitsBlock(Block):
@staticmethod
async def list_commits(
- credentials: GithubCredentials,
- repo_url: str,
- branch: str,
- per_page: int,
- page: int,
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.CommitItem]:
api = get_api(credentials)
+ repo_url = input_data.repo_url
commits_url = repo_url + "/commits"
- params = {"sha": branch, "per_page": str(per_page), "page": str(page)}
- response = await api.get(commits_url, params=params)
- data = response.json()
+ params = {"sha": input_data.branch}
+ if input_data.path:
+ params["path"] = input_data.path
+ if input_data.author:
+ params["author"] = input_data.author
+ if input_data.committer:
+ params["committer"] = input_data.committer
+ if input_data.since:
+ params["since"] = input_data.since
+ if input_data.until:
+ params["until"] = input_data.until
+
+ # Legacy page-based fetching takes precedence over `limit` if used
+ if input_data.per_page is not None or input_data.page is not None:
+ limit = input_data.per_page or 30
+ start_page = input_data.page or 1
+ else:
+ limit, start_page = input_data.limit, 1
+ data = await get_paginated(
+ api, commits_url, limit=limit, params=params, start_page=start_page
+ )
repo_path = github_repo_path(repo_url)
return [
GithubListCommitsBlock.Output.CommitItem(
@@ -151,13 +205,7 @@ class GithubListCommitsBlock(Block):
**kwargs,
) -> BlockOutput:
try:
- commits = await self.list_commits(
- credentials,
- input_data.repo_url,
- input_data.branch,
- input_data.per_page,
- input_data.page,
- )
+ commits = await self.list_commits(credentials, input_data)
yield "commits", commits
for commit in commits:
yield "commit", commit
diff --git a/autogpt_platform/backend/backend/blocks/github/issues.py b/autogpt_platform/backend/backend/blocks/github/issues.py
index 7269c44f73..6bfc43bba0 100644
--- a/autogpt_platform/backend/backend/blocks/github/issues.py
+++ b/autogpt_platform/backend/backend/blocks/github/issues.py
@@ -1,4 +1,5 @@
import logging
+from typing import Literal
from urllib.parse import urlparse
from typing_extensions import TypedDict
@@ -12,7 +13,7 @@ from backend.blocks._base import (
)
from backend.data.model import SchemaField
-from ._api import convert_comment_url_to_api_endpoint, get_api
+from ._api import convert_comment_url_to_api_endpoint, get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -231,6 +232,19 @@ class GithubListCommentsBlock(Block):
description="URL of the GitHub issue or pull request",
placeholder="https://github.com/owner/repo/issues/1",
)
+ limit: int = SchemaField(
+ description="Maximum number of comments to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ since: str = SchemaField(
+ description="Only include comments updated after the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
class Output(BlockSchemaOutput):
class CommentItem(TypedDict):
@@ -294,7 +308,7 @@ class GithubListCommentsBlock(Block):
@staticmethod
async def list_comments(
- credentials: GithubCredentials, issue_url: str
+ credentials: GithubCredentials, issue_url: str, limit: int, since: str
) -> list[Output.CommentItem]:
parsed_url = urlparse(issue_url)
path_parts = parsed_url.path.strip("/").split("/")
@@ -310,8 +324,12 @@ class GithubListCommentsBlock(Block):
# Set convert_urls=False since we're already providing an API URL
api = get_api(credentials, convert_urls=False)
- response = await api.get(api_url)
- comments = response.json()
+ comments = await get_paginated(
+ api,
+ api_url,
+ limit=limit,
+ params={"since": since} if since else None,
+ )
parsed_comments: list[GithubListCommentsBlock.Output.CommentItem] = [
{
"id": comment["id"],
@@ -333,6 +351,8 @@ class GithubListCommentsBlock(Block):
comments = await self.list_comments(
credentials,
input_data.issue_url,
+ input_data.limit,
+ input_data.since,
)
for comment in comments:
yield "comment", comment
@@ -494,6 +514,65 @@ class GithubListIssuesBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
+ state: Literal["open", "closed", "all"] = SchemaField(
+ description="Only include issues in this state",
+ default="open",
+ )
+ include_pull_requests: bool = SchemaField(
+ description="Whether to also include pull requests in the results. "
+ "The GitHub API considers every pull request an issue.",
+ default=False,
+ )
+ labels: list[str] = SchemaField(
+ description="Only include issues that have all of these labels",
+ default_factory=list,
+ )
+ limit: int = SchemaField(
+ description="Maximum number of issues to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ assignee: str = SchemaField(
+ description="Only include issues assigned to this user. "
+ "Use 'none' for unassigned issues, or '*' for issues with any assignee.",
+ default="",
+ advanced=True,
+ )
+ creator: str = SchemaField(
+ description="Only include issues created by this user",
+ default="",
+ advanced=True,
+ )
+ mentioned: str = SchemaField(
+ description="Only include issues in which this user is mentioned",
+ default="",
+ advanced=True,
+ )
+ milestone: str = SchemaField(
+ description="Only include issues in this milestone, by milestone number. "
+ "Use 'none' for issues without a milestone, "
+ "or '*' for issues with any milestone.",
+ default="",
+ advanced=True,
+ )
+ sort: Literal["created", "updated", "comments"] = SchemaField(
+ description="What to sort the issues by",
+ default="created",
+ advanced=True,
+ )
+ direction: Literal["asc", "desc"] = SchemaField(
+ description="Sort direction",
+ default="desc",
+ advanced=True,
+ )
+ since: str = SchemaField(
+ description="Only include issues updated after the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
class Output(BlockSchemaOutput):
class IssueItem(TypedDict):
@@ -549,12 +628,40 @@ class GithubListIssuesBlock(Block):
@staticmethod
async def list_issues(
- credentials: GithubCredentials, repo_url: str
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.IssueItem]:
api = get_api(credentials)
- issues_url = repo_url + "/issues"
- response = await api.get(issues_url)
- data = response.json()
+ params = {
+ "state": input_data.state,
+ "sort": input_data.sort,
+ "direction": input_data.direction,
+ }
+ if input_data.labels:
+ params["labels"] = ",".join(input_data.labels)
+ if input_data.assignee:
+ params["assignee"] = input_data.assignee
+ if input_data.creator:
+ params["creator"] = input_data.creator
+ if input_data.mentioned:
+ params["mentioned"] = input_data.mentioned
+ if input_data.milestone:
+ params["milestone"] = input_data.milestone
+ if input_data.since:
+ params["since"] = input_data.since
+
+ data = await get_paginated(
+ api,
+ input_data.repo_url + "/issues",
+ limit=input_data.limit,
+ params=params,
+ # The issues endpoint also returns pull requests, marked by the
+ # presence of a "pull_request" key
+ keep=(
+ None
+ if input_data.include_pull_requests
+ else (lambda issue: "pull_request" not in issue)
+ ),
+ )
issues: list[GithubListIssuesBlock.Output.IssueItem] = [
{"title": issue["title"], "url": issue["html_url"]} for issue in data
]
@@ -567,10 +674,7 @@ class GithubListIssuesBlock(Block):
credentials: GithubCredentials,
**kwargs,
) -> BlockOutput:
- issues = await self.list_issues(
- credentials,
- input_data.repo_url,
- )
+ issues = await self.list_issues(credentials, input_data)
yield "issues", issues
for issue in issues:
yield "issue", issue
diff --git a/autogpt_platform/backend/backend/blocks/github/notifications.py b/autogpt_platform/backend/backend/blocks/github/notifications.py
new file mode 100644
index 0000000000..a008e73f5d
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/github/notifications.py
@@ -0,0 +1,518 @@
+from typing_extensions import TypedDict
+
+from backend.blocks._base import (
+ Block,
+ BlockCategory,
+ BlockOutput,
+ BlockSchemaInput,
+ BlockSchemaOutput,
+)
+from backend.data.model import SchemaField
+
+from ._api import GITHUB_API_URL, get_api, get_paginated
+from ._auth import (
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ GithubCredentials,
+ GithubCredentialsField,
+ GithubCredentialsInput,
+)
+from ._utils import normalize_repo_path
+
+GITHUB_WEB_URL = "https://github.com"
+
+# API path segments whose github.com equivalent is spelled differently
+_WEB_PATH_BY_API_PATH = {"pulls": "pull", "commits": "commit"}
+
+
+class NotificationItem(TypedDict):
+ thread_id: str
+ reason: str
+ unread: bool
+ updated_at: str
+ title: str
+ subject_type: str
+ subject_url: str
+ repository: str
+
+
+TEST_NOTIFICATION_ITEM: NotificationItem = {
+ "thread_id": "1337",
+ "reason": "review_requested",
+ "unread": True,
+ "updated_at": "2026-07-21T12:00:00Z",
+ "title": "Fix the flux capacitor",
+ "subject_type": "PullRequest",
+ "subject_url": "https://github.com/owner/repo/pull/1",
+ "repository": "owner/repo",
+}
+
+
+class GithubListNotificationsBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ include_read: bool = SchemaField(
+ description="Whether to include notifications that are already "
+ "marked as read",
+ default=False,
+ )
+ participating_only: bool = SchemaField(
+ description="Whether to only include notifications in which you are "
+ "directly participating or mentioned",
+ default=False,
+ )
+ limit: int = SchemaField(
+ description="Maximum number of notifications to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ repo: str = SchemaField(
+ description="Repository to list notifications for, "
+ "as '{owner}/{repo}' or a full repository URL. "
+ "Leave empty to list notifications for all repositories.",
+ placeholder="{owner}/{repo}",
+ default="",
+ advanced=True,
+ )
+ since: str = SchemaField(
+ description="Only show notifications updated after the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
+ before: str = SchemaField(
+ description="Only show notifications updated before the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ notification: NotificationItem = SchemaField(
+ title="Notification", description="Each notification thread"
+ )
+ notifications: list[NotificationItem] = SchemaField(
+ description="List of notification threads"
+ )
+ error: str = SchemaField(
+ description="Error message if listing notifications failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="15911223-52e9-47ec-ab95-0581f36c8092",
+ description="This block lists GitHub notifications for the authenticated "
+ "user, e.g. mentions, review requests, and updates on subscribed threads.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubListNotificationsBlock.Input,
+ output_schema=GithubListNotificationsBlock.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("notifications", [TEST_NOTIFICATION_ITEM]),
+ ("notification", TEST_NOTIFICATION_ITEM),
+ ],
+ test_mock={
+ "list_notifications": lambda *args, **kwargs: [TEST_NOTIFICATION_ITEM]
+ },
+ )
+
+ @staticmethod
+ async def list_notifications(
+ credentials: GithubCredentials, input_data: Input
+ ) -> list[NotificationItem]:
+ api = get_api(credentials, convert_urls=False)
+ url = _notifications_url(input_data.repo)
+ params: dict[str, str] = {}
+ if input_data.include_read:
+ params["all"] = "true"
+ if input_data.participating_only:
+ params["participating"] = "true"
+ if input_data.since:
+ params["since"] = input_data.since
+ if input_data.before:
+ params["before"] = input_data.before
+
+ threads = await get_paginated(
+ api,
+ url,
+ limit=input_data.limit,
+ params=params,
+ # GET /notifications caps per_page at 50;
+ # the repo-scoped endpoint allows the usual 100
+ max_page_size=100 if input_data.repo else 50,
+ )
+ return [_to_notification_item(thread) for thread in threads]
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ notifications = await self.list_notifications(credentials, input_data)
+ yield "notifications", notifications
+ for notification in notifications:
+ yield "notification", notification
+
+
+class GithubGetNotificationThreadBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ thread_id: str = SchemaField(
+ description="ID of the notification thread",
+ placeholder="1337",
+ )
+
+ class Output(BlockSchemaOutput):
+ notification: NotificationItem = SchemaField(
+ description="The notification thread"
+ )
+ title: str = SchemaField(description="Title of the notification subject")
+ reason: str = SchemaField(
+ description="Reason you received the notification (e.g. 'mention', "
+ "'review_requested', 'subscribed')"
+ )
+ unread: bool = SchemaField(description="Whether the notification is unread")
+ subject_type: str = SchemaField(
+ description="Type of the notification subject "
+ "(e.g. 'Issue', 'PullRequest', 'Release')"
+ )
+ subject_url: str = SchemaField(
+ description="URL of the notification subject on GitHub"
+ )
+ repository: str = SchemaField(
+ description="Full name of the repository (owner/repo)"
+ )
+ updated_at: str = SchemaField(
+ description="ISO 8601 timestamp of the last update to the thread"
+ )
+ error: str = SchemaField(
+ description="Error message if fetching the notification thread failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="454afb97-46c4-43ca-b54a-543d647a9113",
+ description="This block fetches a single GitHub notification thread.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubGetNotificationThreadBlock.Input,
+ output_schema=GithubGetNotificationThreadBlock.Output,
+ test_input={
+ "thread_id": "1337",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("notification", TEST_NOTIFICATION_ITEM),
+ ("title", TEST_NOTIFICATION_ITEM["title"]),
+ ("reason", TEST_NOTIFICATION_ITEM["reason"]),
+ ("unread", TEST_NOTIFICATION_ITEM["unread"]),
+ ("subject_type", TEST_NOTIFICATION_ITEM["subject_type"]),
+ ("subject_url", TEST_NOTIFICATION_ITEM["subject_url"]),
+ ("repository", TEST_NOTIFICATION_ITEM["repository"]),
+ ("updated_at", TEST_NOTIFICATION_ITEM["updated_at"]),
+ ],
+ test_mock={
+ "get_thread": lambda *args, **kwargs: TEST_NOTIFICATION_ITEM,
+ },
+ )
+
+ @staticmethod
+ async def get_thread(
+ credentials: GithubCredentials, thread_id: str
+ ) -> NotificationItem:
+ api = get_api(credentials, convert_urls=False)
+ response = await api.get(f"{GITHUB_API_URL}/notifications/threads/{thread_id}")
+ return _to_notification_item(response.json())
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ notification = await self.get_thread(credentials, input_data.thread_id)
+ yield "notification", notification
+ yield "title", notification["title"]
+ yield "reason", notification["reason"]
+ yield "unread", notification["unread"]
+ yield "subject_type", notification["subject_type"]
+ yield "subject_url", notification["subject_url"]
+ yield "repository", notification["repository"]
+ yield "updated_at", notification["updated_at"]
+
+
+class GithubMarkNotificationsAsReadBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ repo: str = SchemaField(
+ description="Repository to mark notifications as read for, "
+ "as '{owner}/{repo}' or a full repository URL. "
+ "Leave empty to mark notifications for all repositories.",
+ placeholder="{owner}/{repo}",
+ default="",
+ advanced=False,
+ )
+ last_read_at: str = SchemaField(
+ description="Only mark notifications updated before the given "
+ "ISO 8601 timestamp as read. Defaults to the current time.",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ success: bool = SchemaField(
+ description="Whether the notifications were marked as read"
+ )
+ error: str = SchemaField(
+ description="Error message if marking notifications as read failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="725d4f50-f40e-4dc9-9487-17bf16d34111",
+ description="This block marks all GitHub notifications as read, "
+ "optionally scoped to a single repository.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubMarkNotificationsAsReadBlock.Input,
+ output_schema=GithubMarkNotificationsAsReadBlock.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[("success", True)],
+ test_mock={"mark_all_as_read": lambda *args, **kwargs: True},
+ )
+
+ @staticmethod
+ async def mark_all_as_read(
+ credentials: GithubCredentials, repo: str, last_read_at: str
+ ) -> bool:
+ api = get_api(credentials, convert_urls=False)
+ url = _notifications_url(repo)
+ data: dict[str, str] = {}
+ if last_read_at:
+ data["last_read_at"] = last_read_at
+
+ await api.put(url, json=data)
+ return True
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ yield "success", await self.mark_all_as_read(
+ credentials, input_data.repo, input_data.last_read_at
+ )
+
+
+class GithubMarkNotificationThreadAsReadBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ thread_id: str = SchemaField(
+ description="ID of the notification thread",
+ placeholder="1337",
+ )
+
+ class Output(BlockSchemaOutput):
+ success: bool = SchemaField(
+ description="Whether the notification thread was marked as read"
+ )
+ error: str = SchemaField(
+ description="Error message if marking the thread as read failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="530d5158-34f7-4ea1-a91b-134f5eabc3b8",
+ description="This block marks a single GitHub notification thread as read.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubMarkNotificationThreadAsReadBlock.Input,
+ output_schema=GithubMarkNotificationThreadAsReadBlock.Output,
+ test_input={
+ "thread_id": "1337",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[("success", True)],
+ test_mock={"mark_thread_as_read": lambda *args, **kwargs: True},
+ )
+
+ @staticmethod
+ async def mark_thread_as_read(
+ credentials: GithubCredentials, thread_id: str
+ ) -> bool:
+ api = get_api(credentials, convert_urls=False)
+ await api.patch(f"{GITHUB_API_URL}/notifications/threads/{thread_id}")
+ return True
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ yield "success", await self.mark_thread_as_read(
+ credentials, input_data.thread_id
+ )
+
+
+class GithubMarkNotificationThreadAsDoneBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ thread_id: str = SchemaField(
+ description="ID of the notification thread",
+ placeholder="1337",
+ )
+
+ class Output(BlockSchemaOutput):
+ success: bool = SchemaField(
+ description="Whether the notification thread was marked as done"
+ )
+ error: str = SchemaField(
+ description="Error message if marking the thread as done failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="6f579efa-df74-4d0c-bda8-d63c8bc37416",
+ description="This block marks a GitHub notification thread as done, "
+ "removing it from the notification inbox.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubMarkNotificationThreadAsDoneBlock.Input,
+ output_schema=GithubMarkNotificationThreadAsDoneBlock.Output,
+ test_input={
+ "thread_id": "1337",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[("success", True)],
+ test_mock={"mark_thread_as_done": lambda *args, **kwargs: True},
+ )
+
+ @staticmethod
+ async def mark_thread_as_done(
+ credentials: GithubCredentials, thread_id: str
+ ) -> bool:
+ api = get_api(credentials, convert_urls=False)
+ await api.delete(f"{GITHUB_API_URL}/notifications/threads/{thread_id}")
+ return True
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ yield "success", await self.mark_thread_as_done(
+ credentials, input_data.thread_id
+ )
+
+
+class GithubUnsubscribeNotificationThreadBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("notifications")
+ thread_id: str = SchemaField(
+ description="ID of the notification thread",
+ placeholder="1337",
+ )
+
+ class Output(BlockSchemaOutput):
+ success: bool = SchemaField(
+ description="Whether you were unsubscribed from the notification thread"
+ )
+ error: str = SchemaField(
+ description="Error message if unsubscribing from the thread failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="0a57b1b4-87c1-4758-91fc-badedcf338dd",
+ description="This block unsubscribes you from a GitHub notification "
+ "thread, muting future notifications unless you are mentioned again.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubUnsubscribeNotificationThreadBlock.Input,
+ output_schema=GithubUnsubscribeNotificationThreadBlock.Output,
+ test_input={
+ "thread_id": "1337",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[("success", True)],
+ test_mock={"unsubscribe_thread": lambda *args, **kwargs: True},
+ )
+
+ @staticmethod
+ async def unsubscribe_thread(
+ credentials: GithubCredentials, thread_id: str
+ ) -> bool:
+ api = get_api(credentials, convert_urls=False)
+ await api.delete(
+ f"{GITHUB_API_URL}/notifications/threads/{thread_id}/subscription"
+ )
+ return True
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ yield "success", await self.unsubscribe_thread(
+ credentials, input_data.thread_id
+ )
+
+
+def _notifications_url(repo: str) -> str:
+ if not repo:
+ return f"{GITHUB_API_URL}/notifications"
+ return f"{GITHUB_API_URL}/repos/{normalize_repo_path(repo)}/notifications"
+
+
+def _to_notification_item(thread: dict) -> NotificationItem:
+ subject = thread.get("subject") or {}
+ return {
+ "thread_id": thread["id"],
+ "reason": thread["reason"],
+ "unread": thread["unread"],
+ "updated_at": thread["updated_at"],
+ "title": subject.get("title", ""),
+ "subject_type": subject.get("type", ""),
+ "subject_url": _subject_html_url(subject.get("url") or ""),
+ "repository": (thread.get("repository") or {}).get("full_name", ""),
+ }
+
+
+def _subject_html_url(api_url: str) -> str:
+ """
+ Best-effort conversion of a subject API URL to its github.com equivalent.
+ Anything that isn't a repo-scoped API URL is passed through unchanged.
+ """
+ prefix = f"{GITHUB_API_URL}/repos/"
+ if not api_url.startswith(prefix):
+ return api_url
+
+ parts = api_url[len(prefix) :].split("/")
+ if len(parts) > 2:
+ # Releases are addressed by tag on the web, and the subject URL only
+ # carries the numeric id, so drop it and link to the release index.
+ if parts[2] == "releases":
+ del parts[3:]
+ else:
+ parts[2] = _WEB_PATH_BY_API_PATH.get(parts[2], parts[2])
+ return "/".join([GITHUB_WEB_URL, *parts])
diff --git a/autogpt_platform/backend/backend/blocks/github/pull_requests.py b/autogpt_platform/backend/backend/blocks/github/pull_requests.py
index f98c34572c..6b83180a3e 100644
--- a/autogpt_platform/backend/backend/blocks/github/pull_requests.py
+++ b/autogpt_platform/backend/backend/blocks/github/pull_requests.py
@@ -12,7 +12,7 @@ from backend.blocks._base import (
)
from backend.data.model import SchemaField
-from ._api import get_api
+from ._api import get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -31,6 +31,38 @@ class GithubListPullRequestsBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
+ state: Literal["open", "closed", "all"] = SchemaField(
+ description="Only include pull requests in this state",
+ default="open",
+ )
+ base: str = SchemaField(
+ description="Only include pull requests targeting this base branch",
+ placeholder="main",
+ default="",
+ )
+ limit: int = SchemaField(
+ description="Maximum number of pull requests to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ head: str = SchemaField(
+ description="Only include pull requests from this head branch. "
+ "Format: 'user:branch' or 'org:branch'.",
+ placeholder="octocat:feature-branch",
+ default="",
+ advanced=True,
+ )
+ sort: Literal["created", "updated", "popularity", "long-running"] = SchemaField(
+ description="What to sort the pull requests by",
+ default="created",
+ advanced=True,
+ )
+ direction: Literal["asc", "desc"] = SchemaField(
+ description="Sort direction",
+ default="desc",
+ advanced=True,
+ )
class Output(BlockSchemaOutput):
class PRItem(TypedDict):
@@ -89,12 +121,25 @@ class GithubListPullRequestsBlock(Block):
@staticmethod
async def list_prs(
- credentials: GithubCredentials, repo_url: str
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.PRItem]:
api = get_api(credentials)
- pulls_url = repo_url + "/pulls"
- response = await api.get(pulls_url)
- data = response.json()
+ params = {
+ "state": input_data.state,
+ "sort": input_data.sort,
+ "direction": input_data.direction,
+ }
+ if input_data.base:
+ params["base"] = input_data.base
+ if input_data.head:
+ params["head"] = input_data.head
+
+ data = await get_paginated(
+ api,
+ input_data.repo_url + "/pulls",
+ limit=input_data.limit,
+ params=params,
+ )
pull_requests: list[GithubListPullRequestsBlock.Output.PRItem] = [
{"title": pr["title"], "url": pr["html_url"]} for pr in data
]
@@ -107,10 +152,7 @@ class GithubListPullRequestsBlock(Block):
credentials: GithubCredentials,
**kwargs,
) -> BlockOutput:
- pull_requests = await self.list_prs(
- credentials,
- input_data.repo_url,
- )
+ pull_requests = await self.list_prs(credentials, input_data)
yield "pull_requests", pull_requests
for pr in pull_requests:
yield "pull_request", pr
@@ -467,6 +509,11 @@ class GithubUnassignPRReviewerBlock(Block):
yield "error", str(e)
+# A PR accumulates one review event per comment round, so scan well past the
+# reviewer count to be sure the latest state of each reviewer is seen.
+MAX_REVIEWS_SCANNED = 500
+
+
class GithubListPRReviewersBlock(Block):
class Input(BlockSchemaInput):
credentials: GithubCredentialsInput = GithubCredentialsField("repo")
@@ -474,18 +521,28 @@ class GithubListPRReviewersBlock(Block):
description="URL of the GitHub pull request",
placeholder="https://github.com/owner/repo/pull/1",
)
+ include_past_reviewers: bool = SchemaField(
+ description="Also include users who have already submitted a review, "
+ "in addition to users whose review request is pending",
+ default=False,
+ )
class Output(BlockSchemaOutput):
class ReviewerItem(TypedDict):
username: str
url: str
+ review_requested: bool
+ has_reviewed: bool
+ review_state: str
reviewer: ReviewerItem = SchemaField(
title="Reviewer",
- description="Reviewers with their username and profile URL",
+ description="Reviewers with their username, profile URL, "
+ "and review status.",
)
reviewers: list[ReviewerItem] = SchemaField(
- description="List of reviewers with their username and profile URL"
+ description="List of reviewers with their username, profile URL, "
+ "and review status"
)
error: str = SchemaField(
description="Error message if listing reviewers failed"
@@ -494,7 +551,9 @@ class GithubListPRReviewersBlock(Block):
def __init__(self):
super().__init__(
id="2646956e-96d5-4754-a3df-034017e7ed96",
- description="This block lists all reviewers for a specified GitHub pull request.",
+ description="This block lists the requested reviewers for a specified "
+ "GitHub pull request, optionally including users who have already "
+ "submitted a review.",
categories={BlockCategory.DEVELOPER_TOOLS},
input_schema=GithubListPRReviewersBlock.Input,
output_schema=GithubListPRReviewersBlock.Output,
@@ -510,6 +569,9 @@ class GithubListPRReviewersBlock(Block):
{
"username": "reviewer1",
"url": "https://github.com/reviewer1",
+ "review_requested": True,
+ "has_reviewed": False,
+ "review_state": "",
}
],
),
@@ -518,6 +580,9 @@ class GithubListPRReviewersBlock(Block):
{
"username": "reviewer1",
"url": "https://github.com/reviewer1",
+ "review_requested": True,
+ "has_reviewed": False,
+ "review_state": "",
},
),
],
@@ -526,6 +591,9 @@ class GithubListPRReviewersBlock(Block):
{
"username": "reviewer1",
"url": "https://github.com/reviewer1",
+ "review_requested": True,
+ "has_reviewed": False,
+ "review_state": "",
}
]
},
@@ -533,16 +601,49 @@ class GithubListPRReviewersBlock(Block):
@staticmethod
async def list_reviewers(
- credentials: GithubCredentials, pr_url: str
+ credentials: GithubCredentials, pr_url: str, include_past_reviewers: bool
) -> list[Output.ReviewerItem]:
api = get_api(credentials)
reviewers_url = prepare_pr_api_url(pr_url=pr_url, path="requested_reviewers")
response = await api.get(reviewers_url)
data = response.json()
reviewers: list[GithubListPRReviewersBlock.Output.ReviewerItem] = [
- {"username": reviewer["login"], "url": reviewer["html_url"]}
+ {
+ "username": reviewer["login"],
+ "url": reviewer["html_url"],
+ "review_requested": True,
+ "has_reviewed": False,
+ "review_state": "",
+ }
for reviewer in data.get("users", [])
]
+ if not include_past_reviewers:
+ return reviewers
+
+ reviews_url = prepare_pr_api_url(pr_url=pr_url, path="reviews")
+ reviews = await get_paginated(api, reviews_url, limit=MAX_REVIEWS_SCANNED)
+ reviewers_by_username = {r["username"]: r for r in reviewers}
+ for review in reviews:
+ # PENDING reviews are drafts that haven't been submitted yet
+ if review["state"] == "PENDING":
+ continue
+ # Reviews by deleted accounts come back with a null user
+ if not (user := review.get("user")):
+ continue
+ if user["login"] not in reviewers_by_username:
+ reviewer: GithubListPRReviewersBlock.Output.ReviewerItem = {
+ "username": user["login"],
+ "url": user["html_url"],
+ "review_requested": False,
+ "has_reviewed": True,
+ "review_state": review["state"],
+ }
+ reviewers.append(reviewer)
+ reviewers_by_username[user["login"]] = reviewer
+ else:
+ reviewers_by_username[user["login"]].update(
+ has_reviewed=True, review_state=review["state"]
+ )
return reviewers
async def run(
@@ -555,6 +656,7 @@ class GithubListPRReviewersBlock(Block):
reviewers = await self.list_reviewers(
credentials,
input_data.pr_url,
+ input_data.include_past_reviewers,
)
yield "reviewers", reviewers
for reviewer in reviewers:
diff --git a/autogpt_platform/backend/backend/blocks/github/repo.py b/autogpt_platform/backend/backend/blocks/github/repo.py
index 3ac7891707..a7f930ba60 100644
--- a/autogpt_platform/backend/backend/blocks/github/repo.py
+++ b/autogpt_platform/backend/backend/blocks/github/repo.py
@@ -1,3 +1,6 @@
+from datetime import datetime, timezone
+from typing import Literal, Optional
+
from typing_extensions import TypedDict
from backend.blocks._base import (
@@ -8,8 +11,9 @@ from backend.blocks._base import (
BlockSchemaOutput,
)
from backend.data.model import SchemaField
+from backend.util.request import Requests
-from ._api import get_api
+from ._api import get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -27,6 +31,12 @@ class GithubListTagsBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
+ limit: int = SchemaField(
+ description="Maximum number of tags to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
class Output(BlockSchemaOutput):
class TagItem(TypedDict):
@@ -82,12 +92,11 @@ class GithubListTagsBlock(Block):
@staticmethod
async def list_tags(
- credentials: GithubCredentials, repo_url: str
+ credentials: GithubCredentials, repo_url: str, limit: int
) -> list[Output.TagItem]:
api = get_api(credentials)
tags_url = repo_url + "/tags"
- response = await api.get(tags_url)
- data = response.json()
+ data = await get_paginated(api, tags_url, limit=limit)
repo_path = github_repo_path(repo_url)
tags: list[GithubListTagsBlock.Output.TagItem] = [
{
@@ -108,6 +117,7 @@ class GithubListTagsBlock(Block):
tags = await self.list_tags(
credentials,
input_data.repo_url,
+ input_data.limit,
)
yield "tags", tags
for tag in tags:
@@ -122,7 +132,33 @@ class GithubListDiscussionsBlock(Block):
placeholder="https://github.com/owner/repo",
)
num_discussions: int = SchemaField(
- description="Number of discussions to fetch", default=5
+ title="Limit",
+ description="Maximum number of discussions to fetch",
+ default=5,
+ )
+ category: str = SchemaField(
+ description="Only include discussions in the category with this name",
+ default="",
+ )
+ answered: Literal["all", "answered", "unanswered"] = SchemaField(
+ description="Only include discussions that are (un)answered",
+ default="all",
+ advanced=True,
+ )
+ state: Literal["all", "open", "closed"] = SchemaField(
+ description="Only include discussions in this state",
+ default="all",
+ advanced=True,
+ )
+ order_by: Literal["created", "updated"] = SchemaField(
+ description="What to sort the discussions by",
+ default="updated",
+ advanced=True,
+ )
+ direction: Literal["asc", "desc"] = SchemaField(
+ description="Sort direction",
+ default="desc",
+ advanced=True,
)
class Output(BlockSchemaOutput):
@@ -183,35 +219,107 @@ class GithubListDiscussionsBlock(Block):
@staticmethod
async def list_discussions(
- credentials: GithubCredentials, repo_url: str, num_discussions: int
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.DiscussionItem]:
api = get_api(credentials)
# GitHub GraphQL API endpoint is different; we'll use api.post with custom URL
- repo_path = github_repo_path(repo_url)
+ repo_path = github_repo_path(input_data.repo_url)
owner, repo = repo_path.split("/")
query = """
- query($owner: String!, $repo: String!, $num: Int!) {
+ query(
+ $owner: String!, $repo: String!, $num: Int!, $after: String,
+ $categoryId: ID, $answered: Boolean,
+ $states: [DiscussionState!], $orderBy: DiscussionOrder
+ ) {
repository(owner: $owner, name: $repo) {
- discussions(first: $num) {
+ discussions(
+ first: $num, after: $after, categoryId: $categoryId,
+ answered: $answered, states: $states, orderBy: $orderBy
+ ) {
nodes {
title
url
}
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
+ }
+ }
+ }
+ """
+ limit = input_data.num_discussions
+ variables = {
+ "owner": owner,
+ "repo": repo,
+ "num": min(limit, 100),
+ "after": None,
+ "categoryId": (
+ await GithubListDiscussionsBlock._get_category_id(
+ api, owner, repo, input_data.category
+ )
+ if input_data.category
+ else None
+ ),
+ "answered": {"all": None, "answered": True, "unanswered": False}[
+ input_data.answered
+ ],
+ "states": (
+ [input_data.state.upper()] if input_data.state != "all" else None
+ ),
+ "orderBy": {
+ "field": {"created": "CREATED_AT", "updated": "UPDATED_AT"}[
+ input_data.order_by
+ ],
+ "direction": input_data.direction.upper(),
+ },
+ }
+
+ discussions: list[GithubListDiscussionsBlock.Output.DiscussionItem] = []
+ while len(discussions) < limit:
+ response = await api.post(
+ "https://api.github.com/graphql",
+ json={"query": query, "variables": variables},
+ )
+ data = response.json()["data"]["repository"]["discussions"]
+ discussions.extend(
+ {"title": discussion["title"], "url": discussion["url"]}
+ for discussion in data["nodes"]
+ )
+ if not data["pageInfo"]["hasNextPage"]:
+ break
+ variables["after"] = data["pageInfo"]["endCursor"]
+ return discussions[:limit]
+
+ @staticmethod
+ async def _get_category_id(
+ api: Requests, owner: str, repo: str, category_name: str
+ ) -> str:
+ query = """
+ query($owner: String!, $repo: String!) {
+ repository(owner: $owner, name: $repo) {
+ discussionCategories(first: 100) {
+ nodes {
+ id
+ name
+ }
}
}
}
"""
- variables = {"owner": owner, "repo": repo, "num": num_discussions}
response = await api.post(
"https://api.github.com/graphql",
- json={"query": query, "variables": variables},
+ json={"query": query, "variables": {"owner": owner, "repo": repo}},
)
- data = response.json()
- discussions: list[GithubListDiscussionsBlock.Output.DiscussionItem] = [
- {"title": discussion["title"], "url": discussion["url"]}
- for discussion in data["data"]["repository"]["discussions"]["nodes"]
+ categories = response.json()["data"]["repository"]["discussionCategories"][
+ "nodes"
]
- return discussions
+ for category in categories:
+ if category["name"].lower() == category_name.lower():
+ return category["id"]
+ raise ValueError(
+ f"Discussion category '{category_name}' does not exist in {owner}/{repo}"
+ )
async def run(
self,
@@ -220,11 +328,7 @@ class GithubListDiscussionsBlock(Block):
credentials: GithubCredentials,
**kwargs,
) -> BlockOutput:
- discussions = await self.list_discussions(
- credentials,
- input_data.repo_url,
- input_data.num_discussions,
- )
+ discussions = await self.list_discussions(credentials, input_data)
yield "discussions", discussions
for discussion in discussions:
yield "discussion", discussion
@@ -237,24 +341,54 @@ class GithubListReleasesBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
+ release_type: Literal["all", "stable", "prerelease", "draft"] = SchemaField(
+ description="Only include releases of this type",
+ default="all",
+ )
+ limit: int = SchemaField(
+ description="Maximum number of releases to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ published_after: str = SchemaField(
+ description="Only include releases published after the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
+ published_before: str = SchemaField(
+ description="Only include releases published before the given "
+ "ISO 8601 timestamp",
+ placeholder="2026-01-01T00:00:00Z",
+ default="",
+ advanced=True,
+ )
class Output(BlockSchemaOutput):
class ReleaseItem(TypedDict):
name: str
+ tag_name: str
url: str
+ published_at: str
+ prerelease: bool
+ draft: bool
release: ReleaseItem = SchemaField(
title="Release",
- description="Releases with their name and file tree browser URL",
+ description="Releases with their name, tag, URL, publish date, and type",
)
releases: list[ReleaseItem] = SchemaField(
- description="List of releases with their name and file tree browser URL"
+ description="List of releases with their name, tag, URL, publish date, "
+ "and type"
)
def __init__(self):
super().__init__(
id="3460367a-6ba7-4645-8ce6-47b05d040b92",
- description="This block lists all releases for a specified GitHub repository.",
+ description="This block lists releases for a specified GitHub repository, "
+ "optionally filtered by type and date range.",
categories={BlockCategory.DEVELOPER_TOOLS},
input_schema=GithubListReleasesBlock.Input,
output_schema=GithubListReleasesBlock.Output,
@@ -269,7 +403,11 @@ class GithubListReleasesBlock(Block):
[
{
"name": "v1.0.0",
+ "tag_name": "v1.0.0",
"url": "https://github.com/owner/repo/releases/tag/v1.0.0",
+ "published_at": "2026-01-01T00:00:00Z",
+ "prerelease": False,
+ "draft": False,
}
],
),
@@ -277,7 +415,11 @@ class GithubListReleasesBlock(Block):
"release",
{
"name": "v1.0.0",
+ "tag_name": "v1.0.0",
"url": "https://github.com/owner/repo/releases/tag/v1.0.0",
+ "published_at": "2026-01-01T00:00:00Z",
+ "prerelease": False,
+ "draft": False,
},
),
],
@@ -285,7 +427,11 @@ class GithubListReleasesBlock(Block):
"list_releases": lambda *args, **kwargs: [
{
"name": "v1.0.0",
+ "tag_name": "v1.0.0",
"url": "https://github.com/owner/repo/releases/tag/v1.0.0",
+ "published_at": "2026-01-01T00:00:00Z",
+ "prerelease": False,
+ "draft": False,
}
]
},
@@ -293,14 +439,58 @@ class GithubListReleasesBlock(Block):
@staticmethod
async def list_releases(
- credentials: GithubCredentials, repo_url: str
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.ReleaseItem]:
api = get_api(credentials)
- releases_url = repo_url + "/releases"
- response = await api.get(releases_url)
- data = response.json()
+ releases_url = input_data.repo_url + "/releases"
+
+ # The releases endpoint has no filter params, so we filter client-side
+ published_after = _parse_timestamp(input_data.published_after)
+ published_before = _parse_timestamp(input_data.published_before)
+
+ def keep(release: dict) -> bool:
+ if input_data.release_type == "stable" and (
+ release["prerelease"] or release["draft"]
+ ):
+ return False
+ if input_data.release_type == "prerelease" and not release["prerelease"]:
+ return False
+ if input_data.release_type == "draft" and not release["draft"]:
+ return False
+ if published_after or published_before:
+ # Drafts have no publish date; use their creation date instead
+ published = _parse_timestamp(
+ release.get("published_at") or release["created_at"]
+ )
+ if published is None:
+ return False
+ if published_after and published < published_after:
+ return False
+ if published_before and published > published_before:
+ return False
+ return True
+
+ is_filtered = (
+ input_data.release_type != "all"
+ or published_after is not None
+ or published_before is not None
+ )
+ data = await get_paginated(
+ api,
+ releases_url,
+ limit=input_data.limit,
+ keep=keep if is_filtered else None,
+ )
releases: list[GithubListReleasesBlock.Output.ReleaseItem] = [
- {"name": release["name"], "url": release["html_url"]} for release in data
+ {
+ "name": release["name"] or release["tag_name"],
+ "tag_name": release["tag_name"],
+ "url": release["html_url"],
+ "published_at": release.get("published_at") or "",
+ "prerelease": release["prerelease"],
+ "draft": release["draft"],
+ }
+ for release in data
]
return releases
@@ -311,10 +501,7 @@ class GithubListReleasesBlock(Block):
credentials: GithubCredentials,
**kwargs,
) -> BlockOutput:
- releases = await self.list_releases(
- credentials,
- input_data.repo_url,
- )
+ releases = await self.list_releases(credentials, input_data)
yield "releases", releases
for release in releases:
yield "release", release
@@ -430,6 +617,12 @@ class GithubListStargazersBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
+ limit: int = SchemaField(
+ description="Maximum number of stargazers to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
class Output(BlockSchemaOutput):
class StargazerItem(TypedDict):
@@ -489,12 +682,11 @@ class GithubListStargazersBlock(Block):
@staticmethod
async def list_stargazers(
- credentials: GithubCredentials, repo_url: str
+ credentials: GithubCredentials, repo_url: str, limit: int
) -> list[Output.StargazerItem]:
api = get_api(credentials)
stargazers_url = repo_url + "/stargazers"
- response = await api.get(stargazers_url)
- data = response.json()
+ data = await get_paginated(api, stargazers_url, limit=limit)
stargazers: list[GithubListStargazersBlock.Output.StargazerItem] = [
{
"username": stargazer["login"],
@@ -514,6 +706,7 @@ class GithubListStargazersBlock(Block):
stargazers = await self.list_stargazers(
credentials,
input_data.repo_url,
+ input_data.limit,
)
yield "stargazers", stargazers
for stargazer in stargazers:
@@ -745,3 +938,12 @@ class GithubStarRepositoryBlock(Block):
yield "status", status
except Exception as e:
yield "error", str(e)
+
+
+def _parse_timestamp(timestamp: str) -> Optional[datetime]:
+ if not timestamp:
+ return None
+ parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed
diff --git a/autogpt_platform/backend/backend/blocks/github/repo_branches.py b/autogpt_platform/backend/backend/blocks/github/repo_branches.py
index dfc677105c..1d5ac109d9 100644
--- a/autogpt_platform/backend/backend/blocks/github/repo_branches.py
+++ b/autogpt_platform/backend/backend/blocks/github/repo_branches.py
@@ -1,3 +1,4 @@
+from typing import Literal, Optional
from urllib.parse import quote
from typing_extensions import TypedDict
@@ -11,7 +12,7 @@ from backend.blocks._base import (
)
from backend.data.model import SchemaField
-from ._api import get_api
+from ._api import get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -29,16 +30,31 @@ class GithubListBranchesBlock(Block):
description="URL of the GitHub repository",
placeholder="https://github.com/owner/repo",
)
- per_page: int = SchemaField(
- description="Number of branches to return per page (max 100)",
- default=30,
+ limit: int = SchemaField(
+ description="Maximum number of branches to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
+ per_page: Optional[int] = SchemaField(
+ description="[Legacy] Number of branches to return per page (max 100). "
+ "If set (or `page` is set), `limit` is ignored.",
+ default=None,
ge=1,
le=100,
+ advanced=True,
)
- page: int = SchemaField(
- description="Page number for pagination",
- default=1,
+ page: Optional[int] = SchemaField(
+ description="[Legacy] Page number for pagination. "
+ "If set (or `per_page` is set), `limit` is ignored.",
+ default=None,
ge=1,
+ advanced=True,
+ )
+ protected: Literal["all", "protected", "unprotected"] = SchemaField(
+ description="Only include branches that are (un)protected",
+ default="all",
+ advanced=True,
)
class Output(BlockSchemaOutput):
@@ -64,8 +80,6 @@ class GithubListBranchesBlock(Block):
output_schema=GithubListBranchesBlock.Output,
test_input={
"repo_url": "https://github.com/owner/repo",
- "per_page": 30,
- "page": 1,
"credentials": TEST_CREDENTIALS_INPUT,
},
test_credentials=TEST_CREDENTIALS,
@@ -99,14 +113,24 @@ class GithubListBranchesBlock(Block):
@staticmethod
async def list_branches(
- credentials: GithubCredentials, repo_url: str, per_page: int, page: int
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.BranchItem]:
api = get_api(credentials)
+ repo_url = input_data.repo_url
branches_url = repo_url + "/branches"
- response = await api.get(
- branches_url, params={"per_page": str(per_page), "page": str(page)}
+ params: dict[str, str] = {}
+ if input_data.protected != "all":
+ params["protected"] = str(input_data.protected == "protected").lower()
+
+ # Legacy page-based fetching takes precedence over `limit` if used
+ if input_data.per_page is not None or input_data.page is not None:
+ limit = input_data.per_page or 30
+ start_page = input_data.page or 1
+ else:
+ limit, start_page = input_data.limit, 1
+ data = await get_paginated(
+ api, branches_url, limit=limit, params=params, start_page=start_page
)
- data = response.json()
repo_path = github_repo_path(repo_url)
branches: list[GithubListBranchesBlock.Output.BranchItem] = [
{
@@ -125,12 +149,7 @@ class GithubListBranchesBlock(Block):
**kwargs,
) -> BlockOutput:
try:
- branches = await self.list_branches(
- credentials,
- input_data.repo_url,
- input_data.per_page,
- input_data.page,
- )
+ branches = await self.list_branches(credentials, input_data)
yield "branches", branches
for branch in branches:
yield "branch", branch
diff --git a/autogpt_platform/backend/backend/blocks/github/reviews.py b/autogpt_platform/backend/backend/blocks/github/reviews.py
index 932362c09a..5270c77e7b 100644
--- a/autogpt_platform/backend/backend/blocks/github/reviews.py
+++ b/autogpt_platform/backend/backend/blocks/github/reviews.py
@@ -1,6 +1,6 @@
import logging
from enum import Enum
-from typing import Any, List, Optional
+from typing import Any, List, Literal, Optional
from typing_extensions import TypedDict
@@ -13,7 +13,7 @@ from backend.blocks._base import (
)
from backend.data.model import SchemaField
-from ._api import get_api
+from ._api import get_api, get_paginated
from ._auth import (
TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
@@ -213,6 +213,30 @@ class GithubListPRReviewsBlock(Block):
description="Pull request number",
placeholder="123",
)
+ reviewer: str = SchemaField(
+ description="Only include reviews by this user",
+ placeholder="octocat",
+ default="",
+ )
+ state: Literal[
+ "all", "approved", "changes_requested", "commented", "dismissed", "pending"
+ ] = SchemaField(
+ description="Only include reviews with this state. "
+ "Note: 'pending' reviews are your own unsubmitted draft reviews, "
+ "which are excluded by any other choice.",
+ default="all",
+ )
+ latest_only: bool = SchemaField(
+ description="Only include each reviewer's latest review, "
+ "reflecting their current stance",
+ default=False,
+ )
+ limit: int = SchemaField(
+ description="Maximum number of reviews to fetch",
+ default=100,
+ ge=1,
+ le=1000,
+ )
class Output(BlockSchemaOutput):
class ReviewItem(TypedDict):
@@ -282,15 +306,45 @@ class GithubListPRReviewsBlock(Block):
@staticmethod
async def list_reviews(
- credentials: GithubCredentials, repo: str, pr_number: int
+ credentials: GithubCredentials, input_data: Input
) -> list[Output.ReviewItem]:
api = get_api(credentials, convert_urls=False)
# GitHub API endpoint for listing reviews
- reviews_url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/reviews"
-
- response = await api.get(reviews_url)
- data = response.json()
+ reviews_url = (
+ f"https://api.github.com/repos/{input_data.repo}"
+ f"/pulls/{input_data.pr_number}/reviews"
+ )
+
+ # State filtering and per-reviewer deduplication can only be done after
+ # fetching, so in those cases the limit is applied at the end instead.
+ fetch_limit = (
+ input_data.limit
+ if input_data.state == "all" and not input_data.latest_only
+ else 1000
+ )
+ data = await get_paginated(
+ api,
+ reviews_url,
+ limit=fetch_limit,
+ keep=(
+ (lambda review: review["user"]["login"] == input_data.reviewer)
+ if input_data.reviewer
+ else None
+ ),
+ )
+
+ if input_data.latest_only:
+ latest_by_user: dict[str, dict] = {}
+ for review in data:
+ # A PENDING review is an unsubmitted draft, not a stance
+ if review["state"] == "PENDING":
+ continue
+ latest_by_user[review["user"]["login"]] = review
+ data = list(latest_by_user.values())
+
+ if input_data.state != "all":
+ data = [r for r in data if r["state"] == input_data.state.upper()]
reviews: list[GithubListPRReviewsBlock.Output.ReviewItem] = [
{
@@ -300,7 +354,7 @@ class GithubListPRReviewsBlock(Block):
"body": review.get("body", ""),
"html_url": review["html_url"],
}
- for review in data
+ for review in data[: input_data.limit]
]
return reviews
@@ -311,11 +365,7 @@ class GithubListPRReviewsBlock(Block):
credentials: GithubCredentials,
**kwargs,
) -> BlockOutput:
- reviews = await self.list_reviews(
- credentials,
- input_data.repo,
- input_data.pr_number,
- )
+ reviews = await self.list_reviews(credentials, input_data)
yield "reviews", reviews
for review in reviews:
yield "review", review
diff --git a/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py b/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py
index b8b97e5693..9ab7ab2eac 100644
--- a/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py
+++ b/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py
@@ -1,13 +1,60 @@
+import asyncio
+import copy
import inspect
+from datetime import datetime, timezone
+from unittest import mock
import pytest
+from backend.blocks.github import (
+ commits,
+ issues,
+ notifications,
+ pull_requests,
+ repo,
+ repo_branches,
+ reviews,
+ users,
+)
+from backend.blocks.github._api import (
+ convert_comment_url_to_api_endpoint,
+ get_paginated,
+)
from backend.blocks.github._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT
-from backend.blocks.github.commits import FileOperation, GithubMultiFileCommitBlock
+from backend.blocks.github._utils import normalize_repo_path
+from backend.blocks.github.commits import (
+ FileOperation,
+ GithubListCommitsBlock,
+ GithubMultiFileCommitBlock,
+)
+from backend.blocks.github.issues import GithubListCommentsBlock, GithubListIssuesBlock
+from backend.blocks.github.notifications import (
+ TEST_NOTIFICATION_ITEM,
+ GithubGetNotificationThreadBlock,
+ GithubListNotificationsBlock,
+ GithubMarkNotificationsAsReadBlock,
+ GithubMarkNotificationThreadAsDoneBlock,
+ GithubMarkNotificationThreadAsReadBlock,
+ GithubUnsubscribeNotificationThreadBlock,
+ _notifications_url,
+ _subject_html_url,
+ _to_notification_item,
+)
from backend.blocks.github.pull_requests import (
+ GithubListPRReviewersBlock,
+ GithubListPullRequestsBlock,
GithubMergePullRequestBlock,
prepare_pr_api_url,
)
+from backend.blocks.github.repo import (
+ GithubListDiscussionsBlock,
+ GithubListReleasesBlock,
+ GithubListStargazersBlock,
+ GithubListTagsBlock,
+)
+from backend.blocks.github.repo_branches import GithubListBranchesBlock
+from backend.blocks.github.reviews import GithubListPRReviewsBlock
+from backend.blocks.github.users import GithubGetUserInfoBlock
from backend.data.execution import ExecutionContext
from backend.util.exceptions import BlockExecutionError
@@ -127,3 +174,1174 @@ class TestFileOperation:
def test_invalid_value_raises_typo(self):
with pytest.raises(ValueError):
FileOperation("upser")
+
+
+# ── _subject_html_url tests ──
+# These helpers are mocked out in every block test, so they are covered here
+# directly against realistic GitHub API payloads.
+
+
+class TestSubjectHtmlUrl:
+ def test_issue_url(self):
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/repo/issues/42")
+ == "https://github.com/owner/repo/issues/42"
+ )
+
+ def test_pull_request_url_is_singularised(self):
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/repo/pulls/42")
+ == "https://github.com/owner/repo/pull/42"
+ )
+
+ def test_commit_url_is_singularised(self):
+ # /commits/{sha} resolves to the ref's history page, not the commit
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/repo/commits/abc123")
+ == "https://github.com/owner/repo/commit/abc123"
+ )
+
+ def test_release_id_falls_back_to_release_index(self):
+ # Releases resolve by tag on the web; the numeric id 404s
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/repo/releases/9876")
+ == "https://github.com/owner/repo/releases"
+ )
+
+ def test_repo_named_pulls_is_not_rewritten(self):
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/pulls/pulls/1")
+ == "https://github.com/owner/pulls/pull/1"
+ )
+
+ def test_empty_url(self):
+ assert _subject_html_url("") == ""
+
+ def test_non_repo_url_passes_through(self):
+ url = "https://api.github.com/user/12345"
+ assert _subject_html_url(url) == url
+
+
+# ── _to_notification_item tests ──
+
+RAW_NOTIFICATION = {
+ "id": "1337",
+ "unread": True,
+ "reason": "review_requested",
+ "updated_at": "2026-07-21T12:00:00Z",
+ "last_read_at": None,
+ "subject": {
+ "title": "Fix the flux capacitor",
+ "url": "https://api.github.com/repos/owner/repo/pulls/1",
+ "latest_comment_url": "https://api.github.com/repos/owner/repo/pulls/1",
+ "type": "PullRequest",
+ },
+ "repository": {
+ "id": 1296269,
+ "name": "repo",
+ "full_name": "owner/repo",
+ "private": False,
+ },
+ "url": "https://api.github.com/notifications/threads/1337",
+}
+
+
+class TestToNotificationItem:
+ def test_maps_a_realistic_payload(self):
+ assert _to_notification_item(RAW_NOTIFICATION) == TEST_NOTIFICATION_ITEM
+
+ def test_null_repository_degrades_to_empty_string(self):
+ item = _to_notification_item({**RAW_NOTIFICATION, "repository": None})
+ assert item["repository"] == ""
+ assert item["thread_id"] == "1337"
+
+ def test_missing_subject_degrades_to_empty_strings(self):
+ item = _to_notification_item({**RAW_NOTIFICATION, "subject": None})
+ assert item["title"] == ""
+ assert item["subject_type"] == ""
+ assert item["subject_url"] == ""
+
+
+# ── _notifications_url tests ──
+
+
+class TestNotificationsUrl:
+ def test_global_scope(self):
+ assert _notifications_url("") == "https://api.github.com/notifications"
+
+ def test_repo_scope(self):
+ assert (
+ _notifications_url("owner/repo")
+ == "https://api.github.com/repos/owner/repo/notifications"
+ )
+
+ def test_repo_url_is_accepted_too(self):
+ assert (
+ _notifications_url("https://github.com/owner/repo")
+ == "https://api.github.com/repos/owner/repo/notifications"
+ )
+
+ def test_malformed_repo_is_rejected(self):
+ with pytest.raises(ValueError):
+ _notifications_url("owner/repo/../../secrets")
+
+
+# ── normalize_repo_path tests ──
+# The `repo` input on the notification blocks accepts both the bare
+# {owner}/{repo} form and a full repo URL, so both are normalised here.
+
+
+class TestNormalizeRepoPath:
+ def test_bare_owner_repo(self):
+ assert normalize_repo_path("owner/repo") == "owner/repo"
+
+ def test_https_url(self):
+ assert normalize_repo_path("https://github.com/owner/repo") == "owner/repo"
+
+ def test_http_url(self):
+ assert normalize_repo_path("http://github.com/owner/repo") == "owner/repo"
+
+ def test_www_host(self):
+ assert normalize_repo_path("https://www.github.com/owner/repo") == "owner/repo"
+
+ def test_schemeless_url(self):
+ assert normalize_repo_path("github.com/owner/repo") == "owner/repo"
+
+ def test_trailing_slash(self):
+ assert normalize_repo_path("https://github.com/owner/repo/") == "owner/repo"
+
+ def test_git_suffix_is_dropped(self):
+ assert normalize_repo_path("https://github.com/owner/repo.git") == "owner/repo"
+
+ def test_surrounding_whitespace(self):
+ assert normalize_repo_path(" owner/repo ") == "owner/repo"
+
+ def test_dots_and_dashes_in_repo_name(self):
+ assert normalize_repo_path("my-org/my.repo_v2") == "my-org/my.repo_v2"
+
+ def test_deep_link_is_rejected(self):
+ with pytest.raises(ValueError, match="Invalid repository"):
+ normalize_repo_path("https://github.com/owner/repo/tree/main")
+
+ def test_traversal_is_rejected(self):
+ with pytest.raises(ValueError, match="Invalid repository"):
+ normalize_repo_path("owner/../../notifications")
+
+ def test_extra_path_segment_is_rejected(self):
+ with pytest.raises(ValueError, match="Invalid repository"):
+ normalize_repo_path("owner/repo/notifications")
+
+ def test_bare_owner_is_rejected(self):
+ with pytest.raises(ValueError, match="Invalid repository"):
+ normalize_repo_path("owner")
+
+ def test_empty_is_rejected(self):
+ with pytest.raises(ValueError, match="Invalid repository"):
+ normalize_repo_path("")
+
+ def test_non_github_host_is_rejected(self):
+ with pytest.raises(ValueError, match="Not a github.com repository URL"):
+ normalize_repo_path("https://evil.example.com/owner/repo")
+
+ def test_query_string_is_not_smuggled_into_the_path(self):
+ assert (
+ normalize_repo_path("https://github.com/owner/repo?tab=readme")
+ == "owner/repo"
+ )
+
+
+# ── Request-building tests ──
+# The blocks' static methods are mocked wholesale in block tests, so the
+# param/body construction inside them is exercised here instead.
+
+
+def _list_notifications_call(**input_kwargs) -> dict:
+ """Runs list_notifications with the network stubbed; returns the call args."""
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kwargs):
+ captured.update(url=url, **kwargs)
+ return []
+
+ input_data = GithubListNotificationsBlock.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, **input_kwargs}
+ )
+ with (
+ mock.patch.object(notifications, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(notifications, "get_paginated", fake_get_paginated),
+ ):
+ asyncio.run(
+ GithubListNotificationsBlock.list_notifications(
+ TEST_CREDENTIALS, input_data
+ )
+ )
+ return captured
+
+
+class TestListNotificationsRequest:
+ def test_defaults_send_no_filters(self):
+ call = _list_notifications_call()
+ assert call["url"] == "https://api.github.com/notifications"
+ assert call["params"] == {}
+
+ def test_global_endpoint_caps_page_size_at_50(self):
+ assert _list_notifications_call()["max_page_size"] == 50
+
+ def test_repo_endpoint_allows_the_usual_100(self):
+ call = _list_notifications_call(repo="owner/repo")
+ assert call["url"] == "https://api.github.com/repos/owner/repo/notifications"
+ assert call["max_page_size"] == 100
+
+ def test_flags_and_timestamps_become_params(self):
+ call = _list_notifications_call(
+ include_read=True,
+ participating_only=True,
+ since="2026-01-01T00:00:00Z",
+ before="2026-02-01T00:00:00Z",
+ )
+ assert call["params"] == {
+ "all": "true",
+ "participating": "true",
+ "since": "2026-01-01T00:00:00Z",
+ "before": "2026-02-01T00:00:00Z",
+ }
+
+ def test_limit_is_forwarded(self):
+ assert _list_notifications_call(limit=7)["limit"] == 7
+
+
+class _FakeApi:
+ """Captures the request a block builds, and replays canned responses."""
+
+ def __init__(self, responses: dict[str, object] | None = None):
+ self.responses = responses or {}
+ self.calls: list[tuple[str, str, dict]] = []
+
+ async def get(self, url, **kwargs):
+ self.calls.append(("get", url, kwargs))
+ return mock.Mock(json=lambda: self.responses.get(url, {}))
+
+ async def put(self, url, **kwargs):
+ self.calls.append(("put", url, kwargs))
+ return mock.Mock(json=dict)
+
+ async def patch(self, url, **kwargs):
+ self.calls.append(("patch", url, kwargs))
+ return mock.Mock(json=dict)
+
+ async def delete(self, url, **kwargs):
+ self.calls.append(("delete", url, kwargs))
+ return mock.Mock(json=dict)
+
+
+class TestMarkAllAsReadRequest:
+ def _run(self, repo: str, last_read_at: str) -> tuple[str, str, dict]:
+ api = _FakeApi()
+ with mock.patch.object(notifications, "get_api", lambda *a, **kw: api):
+ asyncio.run(
+ GithubMarkNotificationsAsReadBlock.mark_all_as_read(
+ TEST_CREDENTIALS, repo, last_read_at
+ )
+ )
+ return api.calls[0]
+
+ def test_global_scope_with_empty_body(self):
+ method, url, kwargs = self._run("", "")
+ assert (method, url) == ("put", "https://api.github.com/notifications")
+ assert kwargs["json"] == {}
+
+ def test_repo_scope_with_last_read_at(self):
+ method, url, kwargs = self._run("owner/repo", "2026-01-01T00:00:00Z")
+ assert url == "https://api.github.com/repos/owner/repo/notifications"
+ assert kwargs["json"] == {"last_read_at": "2026-01-01T00:00:00Z"}
+
+
+# ── list_reviewers merge/dedup tests ──
+
+PR_URL = "https://github.com/owner/repo/pull/1"
+REQUESTED_REVIEWERS_URL = "https://github.com/owner/repo/pulls/1/requested_reviewers"
+
+
+def _list_reviewers(
+ reviews: list[dict], include_past: bool = True
+) -> list[GithubListPRReviewersBlock.Output.ReviewerItem]:
+ api = _FakeApi(
+ {
+ REQUESTED_REVIEWERS_URL: {
+ "users": [
+ {
+ "login": "pending_alice",
+ "html_url": "https://github.com/pending_alice",
+ }
+ ]
+ }
+ }
+ )
+
+ async def fake_get_paginated(_api, _url, **kwargs):
+ return reviews
+
+ with (
+ mock.patch.object(pull_requests, "get_api", lambda *a, **kw: api),
+ mock.patch.object(pull_requests, "get_paginated", fake_get_paginated),
+ ):
+ return asyncio.run(
+ GithubListPRReviewersBlock.list_reviewers(
+ TEST_CREDENTIALS, PR_URL, include_past
+ )
+ )
+
+
+def _review(login: str | None, state: str) -> dict:
+ user = (
+ {"login": login, "html_url": f"https://github.com/{login}"} if login else None
+ )
+ return {"user": user, "state": state}
+
+
+class TestListReviewers:
+ def test_past_reviewers_are_skipped_when_not_requested(self):
+ assert _list_reviewers([_review("bob", "APPROVED")], include_past=False) == [
+ {
+ "username": "pending_alice",
+ "url": "https://github.com/pending_alice",
+ "review_requested": True,
+ "has_reviewed": False,
+ "review_state": "",
+ }
+ ]
+
+ def test_past_reviewer_is_appended(self):
+ result = _list_reviewers([_review("bob", "APPROVED")])
+ assert result[1] == {
+ "username": "bob",
+ "url": "https://github.com/bob",
+ "review_requested": False,
+ "has_reviewed": True,
+ "review_state": "APPROVED",
+ }
+
+ def test_requested_reviewer_who_reviewed_is_updated_not_duplicated(self):
+ result = _list_reviewers([_review("pending_alice", "CHANGES_REQUESTED")])
+ assert len(result) == 1
+ assert result[0]["review_requested"] is True
+ assert result[0]["has_reviewed"] is True
+ assert result[0]["review_state"] == "CHANGES_REQUESTED"
+
+ def test_latest_review_state_wins(self):
+ result = _list_reviewers(
+ [_review("bob", "CHANGES_REQUESTED"), _review("bob", "APPROVED")]
+ )
+ assert len(result) == 2
+ assert result[1]["review_state"] == "APPROVED"
+
+ def test_pending_reviews_are_ignored(self):
+ assert len(_list_reviewers([_review("bob", "PENDING")])) == 1
+
+ def test_deleted_accounts_are_ignored(self):
+ assert len(_list_reviewers([_review(None, "APPROVED")])) == 1
+
+
+# ── get_paginated tests ──
+# Every list block delegates its fetching here, and every block test mocks the
+# list method wholesale, so the pagination logic is exercised directly.
+
+
+class _PagedApi:
+ """Serves canned pages and records the query params of each request."""
+
+ def __init__(self, pages: list[list[dict]]):
+ self.pages = pages
+ self.requests: list[dict] = []
+
+ async def get(self, url, **kwargs):
+ params = kwargs.get("params") or {}
+ self.requests.append({"url": url, **params})
+ index = int(params["page"]) - 1
+ page = self.pages[index] if index < len(self.pages) else []
+ return mock.Mock(json=lambda: page)
+
+
+def _paginate(pages: list[list[dict]], **kwargs) -> tuple[list[dict], _PagedApi]:
+ api = _PagedApi(pages)
+ items = asyncio.run(get_paginated(api, LIST_URL, **kwargs)) # type: ignore[arg-type]
+ return items, api
+
+
+LIST_URL = "https://api.github.com/repos/owner/repo/items"
+
+
+class TestGetPaginated:
+ def test_short_page_ends_the_fetch(self):
+ items, api = _paginate([[{"n": 1}, {"n": 2}]], limit=10)
+ assert items == [{"n": 1}, {"n": 2}]
+ assert len(api.requests) == 1
+
+ def test_empty_first_page_returns_nothing(self):
+ items, api = _paginate([[]], limit=10)
+ assert items == []
+ assert len(api.requests) == 1
+
+ def test_full_pages_are_followed_and_truncated_to_limit(self):
+ pages = [[{"n": 1}, {"n": 2}, {"n": 3}], [{"n": 4}, {"n": 5}, {"n": 6}]]
+ items, api = _paginate(pages, limit=4, max_page_size=3)
+ assert [i["n"] for i in items] == [1, 2, 3, 4]
+ assert [r["page"] for r in api.requests] == ["1", "2"]
+
+ def test_page_size_is_capped_by_limit_when_unfiltered(self):
+ _, api = _paginate([[]], limit=5)
+ assert api.requests[0]["per_page"] == "5"
+
+ def test_page_size_ignores_limit_when_filtering(self):
+ # A keep filter can reject anything, so pages must be fetched in full
+ _, api = _paginate([[]], limit=5, keep=lambda item: True)
+ assert api.requests[0]["per_page"] == "100"
+
+ def test_filtered_out_items_do_not_count_towards_the_limit(self):
+ pages = [
+ [{"n": 1, "ok": True}, {"n": 2, "ok": False}],
+ [{"n": 3, "ok": True}, {"n": 4, "ok": True}],
+ ]
+ items, api = _paginate(
+ pages, limit=2, max_page_size=2, keep=lambda item: item["ok"]
+ )
+ assert [i["n"] for i in items] == [1, 3]
+ assert len(api.requests) == 2
+
+ def test_start_page_is_honoured(self):
+ _, api = _paginate([[], [], []], limit=10, start_page=3)
+ assert api.requests[0]["page"] == "3"
+
+ def test_extra_params_are_forwarded(self):
+ _, api = _paginate([[]], limit=1, params={"state": "open"})
+ assert api.requests[0]["state"] == "open"
+
+
+# ── convert_comment_url_to_api_endpoint tests ──
+
+
+class TestConvertCommentUrl:
+ def test_api_url_passes_through(self):
+ url = "https://api.github.com/repos/owner/repo/issues/comments/1"
+ assert convert_comment_url_to_api_endpoint(url) == url
+
+ def test_issue_comment_anchor(self):
+ assert (
+ convert_comment_url_to_api_endpoint(
+ "https://github.com/owner/repo/issues/1#issuecomment-99"
+ )
+ == "https://api.github.com/repos/owner/repo/issues/comments/99"
+ )
+
+ def test_pr_review_comment_anchor(self):
+ assert (
+ convert_comment_url_to_api_endpoint(
+ "https://github.com/owner/repo/pull/1#discussion_r77"
+ )
+ == "https://api.github.com/repos/owner/repo/pulls/comments/77"
+ )
+
+ def test_url_without_anchor_falls_back_to_plain_conversion(self):
+ assert (
+ convert_comment_url_to_api_endpoint(
+ "https://github.com/owner/repo/issues/1"
+ )
+ == "https://api.github.com/repos/owner/repo/issues/1"
+ )
+
+ def test_repo_root_url(self):
+ assert (
+ convert_comment_url_to_api_endpoint("https://github.com/owner/repo")
+ == "https://api.github.com/repos/owner/repo"
+ )
+
+ def test_url_without_a_repo_is_rejected(self):
+ with pytest.raises(ValueError):
+ convert_comment_url_to_api_endpoint("https://github.com/owner")
+
+
+def test_subject_html_url_of_a_repo_root_is_not_rewritten():
+ assert (
+ _subject_html_url("https://api.github.com/repos/owner/repo")
+ == "https://github.com/owner/repo"
+ )
+
+
+# ── Notification thread request tests ──
+
+THREAD_URL = "https://api.github.com/notifications/threads/1337"
+
+
+def _thread_call(method, *args):
+ api = _FakeApi({THREAD_URL: RAW_NOTIFICATION})
+ with mock.patch.object(notifications, "get_api", lambda *a, **kw: api):
+ result = asyncio.run(method(TEST_CREDENTIALS, *args))
+ return result, api.calls[0]
+
+
+class TestNotificationThreadRequests:
+ def test_get_thread_maps_the_payload(self):
+ result, (method, url, _) = _thread_call(
+ GithubGetNotificationThreadBlock.get_thread, "1337"
+ )
+ assert (method, url) == ("get", THREAD_URL)
+ assert result == TEST_NOTIFICATION_ITEM
+
+ def test_mark_thread_as_read_patches_the_thread(self):
+ result, (method, url, _) = _thread_call(
+ GithubMarkNotificationThreadAsReadBlock.mark_thread_as_read, "1337"
+ )
+ assert (result, method, url) == (True, "patch", THREAD_URL)
+
+ def test_mark_thread_as_done_deletes_the_thread(self):
+ result, (method, url, _) = _thread_call(
+ GithubMarkNotificationThreadAsDoneBlock.mark_thread_as_done, "1337"
+ )
+ assert (result, method, url) == (True, "delete", THREAD_URL)
+
+ def test_unsubscribe_deletes_the_subscription(self):
+ result, (method, url, _) = _thread_call(
+ GithubUnsubscribeNotificationThreadBlock.unsubscribe_thread, "1337"
+ )
+ assert (result, method, url) == (True, "delete", f"{THREAD_URL}/subscription")
+
+
+# ── List-block request-building tests ──
+# Same rationale as the notification request tests above: the params these
+# blocks build never reach get_paginated in a block test, because the whole
+# list method is mocked out.
+
+REPO_URL = "https://github.com/owner/repo"
+
+_LIST_METHOD = {
+ GithubListCommitsBlock: "list_commits",
+ GithubListBranchesBlock: "list_branches",
+ GithubListIssuesBlock: "list_issues",
+ GithubListPullRequestsBlock: "list_prs",
+ GithubListReleasesBlock: "list_releases",
+}
+
+
+def _capture_paginated(module, block, input_kwargs, page: list[dict] | None = None):
+ """Runs a block's list method with the network stubbed; returns (result, call)."""
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kwargs):
+ captured.update(url=url, **kwargs)
+ items = page or []
+ keep = kwargs.get("keep")
+ return [i for i in items if keep is None or keep(i)]
+
+ method = getattr(block, _LIST_METHOD[block])
+ input_data = block.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, **input_kwargs}
+ )
+ with (
+ mock.patch.object(module, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(module, "get_paginated", fake_get_paginated),
+ ):
+ result = asyncio.run(method(TEST_CREDENTIALS, input_data))
+ return result, captured
+
+
+class TestListCommitsRequest:
+ def _call(self, **kwargs):
+ return _capture_paginated(
+ commits,
+ GithubListCommitsBlock,
+ {"repo_url": REPO_URL, **kwargs},
+ )[1]
+
+ def test_branch_becomes_the_sha_param(self):
+ call = self._call(branch="dev")
+ assert call["url"] == f"{REPO_URL}/commits"
+ assert call["params"] == {"sha": "dev"}
+
+ def test_optional_filters_become_params(self):
+ call = self._call(
+ path="src/main.py",
+ author="alice",
+ committer="bob",
+ since="2026-01-01T00:00:00Z",
+ until="2026-02-01T00:00:00Z",
+ )
+ assert call["params"] == {
+ "sha": "main",
+ "path": "src/main.py",
+ "author": "alice",
+ "committer": "bob",
+ "since": "2026-01-01T00:00:00Z",
+ "until": "2026-02-01T00:00:00Z",
+ }
+
+ def test_limit_is_used_by_default(self):
+ call = self._call(limit=7)
+ assert (call["limit"], call["start_page"]) == (7, 1)
+
+ def test_legacy_paging_overrides_limit(self):
+ call = self._call(limit=7, per_page=25, page=3)
+ assert (call["limit"], call["start_page"]) == (25, 3)
+
+ def test_legacy_page_alone_defaults_the_page_size(self):
+ call = self._call(limit=7, page=2)
+ assert (call["limit"], call["start_page"]) == (30, 2)
+
+ def test_commit_items_are_mapped(self):
+ raw = {
+ "sha": "abc123",
+ "commit": {
+ "message": "Initial commit",
+ "author": {"name": "octocat", "date": "2026-01-01T00:00:00Z"},
+ },
+ }
+ result, _ = _capture_paginated(
+ commits,
+ GithubListCommitsBlock,
+ {"repo_url": REPO_URL},
+ page=[raw],
+ )
+ assert result[0]["url"] == f"{REPO_URL}/commit/abc123"
+ assert result[0]["author"] == "octocat"
+
+ def test_missing_commit_author_degrades(self):
+ raw = {"sha": "abc123", "commit": {"message": "m", "author": None}}
+ result, _ = _capture_paginated(
+ commits,
+ GithubListCommitsBlock,
+ {"repo_url": REPO_URL},
+ page=[raw],
+ )
+ assert (result[0]["author"], result[0]["date"]) == ("Unknown", "")
+
+
+class TestListBranchesRequest:
+ def _call(self, **kwargs):
+ return _capture_paginated(
+ repo_branches,
+ GithubListBranchesBlock,
+ {"repo_url": REPO_URL, **kwargs},
+ )[1]
+
+ def test_default_sends_no_protected_filter(self):
+ call = self._call()
+ assert call["url"] == f"{REPO_URL}/branches"
+ assert call["params"] == {}
+
+ def test_protected_filter(self):
+ assert self._call(protected="protected")["params"] == {"protected": "true"}
+
+ def test_unprotected_filter(self):
+ assert self._call(protected="unprotected")["params"] == {"protected": "false"}
+
+ def test_legacy_paging_overrides_limit(self):
+ call = self._call(limit=7, per_page=10)
+ assert (call["limit"], call["start_page"]) == (10, 1)
+
+ def test_branch_items_are_mapped(self):
+ result, _ = _capture_paginated(
+ repo_branches,
+ GithubListBranchesBlock,
+ {"repo_url": REPO_URL},
+ page=[{"name": "main"}],
+ )
+ assert result == [{"name": "main", "url": f"{REPO_URL}/tree/main"}]
+
+
+class TestListIssuesRequest:
+ def _call(self, **kwargs):
+ return _capture_paginated(
+ issues,
+ GithubListIssuesBlock,
+ {"repo_url": REPO_URL, **kwargs},
+ )[1]
+
+ def test_defaults(self):
+ call = self._call()
+ assert call["url"] == f"{REPO_URL}/issues"
+ assert call["params"] == {
+ "state": "open",
+ "sort": "created",
+ "direction": "desc",
+ }
+
+ def test_labels_are_joined(self):
+ assert self._call(labels=["bug", "p0"])["params"]["labels"] == "bug,p0"
+
+ def test_optional_filters_become_params(self):
+ params = self._call(
+ assignee="alice",
+ creator="bob",
+ mentioned="carol",
+ milestone="4",
+ since="2026-01-01T00:00:00Z",
+ )["params"]
+ assert params["assignee"] == "alice"
+ assert params["creator"] == "bob"
+ assert params["mentioned"] == "carol"
+ assert params["milestone"] == "4"
+ assert params["since"] == "2026-01-01T00:00:00Z"
+
+ def test_pull_requests_are_filtered_out_by_default(self):
+ page = [
+ {"title": "issue", "html_url": "https://github.com/owner/repo/issues/1"},
+ {
+ "title": "pr",
+ "html_url": "https://github.com/owner/repo/pull/2",
+ "pull_request": {},
+ },
+ ]
+ result, _ = _capture_paginated(
+ issues,
+ GithubListIssuesBlock,
+ {"repo_url": REPO_URL},
+ page=page,
+ )
+ assert [i["title"] for i in result] == ["issue"]
+
+ def test_pull_requests_are_kept_when_requested(self):
+ call = self._call(include_pull_requests=True)
+ assert call["keep"] is None
+
+
+class TestListCommentsRequest:
+ def _call(self, issue_url: str, limit: int = 100, since: str = ""):
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kwargs):
+ captured.update(url=url, **kwargs)
+ return []
+
+ with (
+ mock.patch.object(issues, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(issues, "get_paginated", fake_get_paginated),
+ ):
+ asyncio.run(
+ GithubListCommentsBlock.list_comments(
+ TEST_CREDENTIALS, issue_url, limit, since
+ )
+ )
+ return captured
+
+ def test_issue_url_becomes_the_comments_endpoint(self):
+ call = self._call("https://github.com/owner/repo/issues/1")
+ assert (
+ call["url"] == "https://api.github.com/repos/owner/repo/issues/1/comments"
+ )
+ assert call["params"] is None
+
+ def test_pr_url_uses_the_same_issues_endpoint(self):
+ call = self._call("https://github.com/owner/repo/pull/42")
+ assert (
+ call["url"] == "https://api.github.com/repos/owner/repo/issues/42/comments"
+ )
+
+ def test_since_is_forwarded(self):
+ call = self._call(
+ "https://github.com/owner/repo/issues/1", since="2026-01-01T00:00:00Z"
+ )
+ assert call["params"] == {"since": "2026-01-01T00:00:00Z"}
+
+
+class TestListPullRequestsRequest:
+ def _call(self, **kwargs):
+ return _capture_paginated(
+ pull_requests,
+ GithubListPullRequestsBlock,
+ {"repo_url": REPO_URL, **kwargs},
+ )[1]
+
+ def test_defaults(self):
+ call = self._call()
+ assert call["url"] == f"{REPO_URL}/pulls"
+ assert call["params"] == {
+ "state": "open",
+ "sort": "created",
+ "direction": "desc",
+ }
+
+ def test_base_and_head_become_params(self):
+ params = self._call(base="dev", head="octocat:feature")["params"]
+ assert (params["base"], params["head"]) == ("dev", "octocat:feature")
+
+ def test_limit_is_forwarded(self):
+ assert self._call(limit=9)["limit"] == 9
+
+
+# ── list_reviews filtering tests ──
+
+
+def _list_reviews(reviews_page: list[dict], **kwargs):
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kw):
+ captured.update(url=url, **kw)
+ keep = kw.get("keep")
+ return [r for r in reviews_page if keep is None or keep(r)]
+
+ input_data = GithubListPRReviewsBlock.Input.model_validate(
+ {
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "repo": "owner/repo",
+ "pr_number": 1,
+ **kwargs,
+ }
+ )
+ with (
+ mock.patch.object(reviews, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(reviews, "get_paginated", fake_get_paginated),
+ ):
+ result = asyncio.run(
+ GithubListPRReviewsBlock.list_reviews(TEST_CREDENTIALS, input_data)
+ )
+ return result, captured
+
+
+def _pr_review(login: str, state: str, id: int = 1) -> dict:
+ return {
+ "id": id,
+ "user": {"login": login},
+ "state": state,
+ "body": "",
+ "html_url": f"https://github.com/owner/repo/pull/1#pullrequestreview-{id}",
+ }
+
+
+class TestListReviews:
+ def test_endpoint_is_built_from_repo_and_pr_number(self):
+ _, call = _list_reviews([])
+ assert call["url"] == "https://api.github.com/repos/owner/repo/pulls/1/reviews"
+
+ def test_unfiltered_fetch_uses_the_limit(self):
+ _, call = _list_reviews([], limit=12)
+ assert call["limit"] == 12
+ assert call["keep"] is None
+
+ def test_post_fetch_filtering_raises_the_fetch_limit(self):
+ # State/latest_only filtering happens after fetching, so a small fetch
+ # limit would silently drop matches that sit further down the list.
+ _, call = _list_reviews([], limit=12, latest_only=True)
+ assert call["limit"] == 1000
+
+ def test_reviewer_filter_is_applied_while_fetching(self):
+ result, _ = _list_reviews(
+ [_pr_review("alice", "APPROVED", 1), _pr_review("bob", "APPROVED", 2)],
+ reviewer="alice",
+ )
+ assert [r["user"] for r in result] == ["alice"]
+
+ def test_latest_only_keeps_the_last_review_per_user(self):
+ result, _ = _list_reviews(
+ [
+ _pr_review("alice", "CHANGES_REQUESTED", 1),
+ _pr_review("alice", "APPROVED", 2),
+ ],
+ latest_only=True,
+ )
+ assert [(r["id"], r["state"]) for r in result] == [(2, "APPROVED")]
+
+ def test_latest_only_ignores_pending_drafts(self):
+ result, _ = _list_reviews(
+ [_pr_review("alice", "APPROVED", 1), _pr_review("alice", "PENDING", 2)],
+ latest_only=True,
+ )
+ assert [r["id"] for r in result] == [1]
+
+ def test_state_filter_is_case_insensitive_against_the_api(self):
+ result, _ = _list_reviews(
+ [
+ _pr_review("alice", "APPROVED", 1),
+ _pr_review("bob", "CHANGES_REQUESTED", 2),
+ ],
+ state="changes_requested",
+ )
+ assert [r["id"] for r in result] == [2]
+
+ def test_limit_is_applied_after_filtering(self):
+ result, _ = _list_reviews(
+ [_pr_review("a", "APPROVED", 1), _pr_review("b", "APPROVED", 2)],
+ state="approved",
+ limit=1,
+ )
+ assert len(result) == 1
+
+
+# ── list_releases filtering tests ──
+
+
+def _release(
+ tag: str,
+ *,
+ prerelease: bool = False,
+ draft: bool = False,
+ published_at: str | None = "2026-01-01T00:00:00Z",
+ created_at: str = "2026-01-01T00:00:00Z",
+) -> dict:
+ return {
+ "name": None,
+ "tag_name": tag,
+ "html_url": f"https://github.com/owner/repo/releases/tag/{tag}",
+ "published_at": published_at,
+ "created_at": created_at,
+ "prerelease": prerelease,
+ "draft": draft,
+ }
+
+
+def _list_releases(page: list[dict], **kwargs):
+ return _capture_paginated(
+ repo,
+ GithubListReleasesBlock,
+ {"repo_url": REPO_URL, **kwargs},
+ page=page,
+ )
+
+
+class TestListReleases:
+ def test_no_filter_means_no_keep_predicate(self):
+ _, call = _list_releases(
+ [],
+ )
+ assert call["url"] == f"{REPO_URL}/releases"
+ assert call["keep"] is None
+
+ def test_stable_excludes_prereleases_and_drafts(self):
+ result, _ = _list_releases(
+ [
+ _release("v1"),
+ _release("v2-rc", prerelease=True),
+ _release("v3", draft=True),
+ ],
+ release_type="stable",
+ )
+ assert [r["tag_name"] for r in result] == ["v1"]
+
+ def test_prerelease_filter(self):
+ result, _ = _list_releases(
+ [_release("v1"), _release("v2-rc", prerelease=True)],
+ release_type="prerelease",
+ )
+ assert [r["tag_name"] for r in result] == ["v2-rc"]
+
+ def test_draft_filter_uses_created_at_for_the_date(self):
+ result, _ = _list_releases(
+ [
+ _release(
+ "v9",
+ draft=True,
+ published_at=None,
+ created_at="2026-06-01T00:00:00Z",
+ ),
+ _release("v1", published_at="2026-06-01T00:00:00Z"),
+ ],
+ release_type="draft",
+ published_after="2026-05-01T00:00:00Z",
+ )
+ assert [r["tag_name"] for r in result] == ["v9"]
+
+ def test_published_after_and_before_bracket_the_range(self):
+ result, _ = _list_releases(
+ [
+ _release("old", published_at="2025-01-01T00:00:00Z"),
+ _release("hit", published_at="2026-06-01T00:00:00Z"),
+ _release("new", published_at="2027-01-01T00:00:00Z"),
+ ],
+ published_after="2026-01-01T00:00:00Z",
+ published_before="2026-12-31T00:00:00Z",
+ )
+ assert [r["tag_name"] for r in result] == ["hit"]
+
+ def test_undated_release_is_dropped_when_a_date_filter_is_set(self):
+ result, _ = _list_releases(
+ [_release("v1", published_at=None, created_at="")],
+ published_after="2026-01-01T00:00:00Z",
+ )
+ assert result == []
+
+ def test_name_falls_back_to_the_tag(self):
+ result, _ = _list_releases([_release("v1")])
+ assert result[0]["name"] == "v1"
+
+
+class TestParseTimestamp:
+ def test_empty_string_is_none(self):
+ assert repo._parse_timestamp("") is None
+
+ def test_zulu_suffix_is_understood(self):
+ assert repo._parse_timestamp("2026-01-01T00:00:00Z") == datetime(
+ 2026, 1, 1, tzinfo=timezone.utc
+ )
+
+ def test_naive_timestamp_is_assumed_utc(self):
+ assert repo._parse_timestamp("2026-01-01T00:00:00") == datetime(
+ 2026, 1, 1, tzinfo=timezone.utc
+ )
+
+
+# ── list_tags / list_stargazers tests ──
+
+
+class TestSimpleRepoLists:
+ def test_tags_are_mapped_to_tree_urls(self):
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kwargs):
+ captured.update(url=url, **kwargs)
+ return [{"name": "v1.0.0"}]
+
+ with (
+ mock.patch.object(repo, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(repo, "get_paginated", fake_get_paginated),
+ ):
+ result = asyncio.run(
+ GithubListTagsBlock.list_tags(TEST_CREDENTIALS, REPO_URL, 5)
+ )
+ assert captured["url"] == f"{REPO_URL}/tags"
+ assert result == [{"name": "v1.0.0", "url": f"{REPO_URL}/tree/v1.0.0"}]
+
+ def test_stargazers_are_mapped(self):
+ captured: dict = {}
+
+ async def fake_get_paginated(api, url, **kwargs):
+ captured.update(url=url, **kwargs)
+ return [{"login": "octocat", "html_url": "https://github.com/octocat"}]
+
+ with (
+ mock.patch.object(repo, "get_api", lambda *a, **kw: object()),
+ mock.patch.object(repo, "get_paginated", fake_get_paginated),
+ ):
+ result = asyncio.run(
+ GithubListStargazersBlock.list_stargazers(TEST_CREDENTIALS, REPO_URL, 5)
+ )
+ assert captured["url"] == f"{REPO_URL}/stargazers"
+ assert result == [{"username": "octocat", "url": "https://github.com/octocat"}]
+
+
+# ── list_discussions (GraphQL) tests ──
+
+GRAPHQL_URL = "https://api.github.com/graphql"
+
+
+class _GraphqlApi:
+ """Replays a queue of GraphQL responses and snapshots each request."""
+
+ def __init__(self, responses: list[dict]):
+ self.responses = list(responses)
+ self.requests: list[dict] = []
+
+ async def post(self, url, **kwargs):
+ self.requests.append(copy.deepcopy(kwargs["json"]))
+ payload = self.responses.pop(0)
+ return mock.Mock(json=lambda: payload)
+
+
+def _discussions_page(nodes: list[dict], has_next: bool = False, cursor=None) -> dict:
+ return {
+ "data": {
+ "repository": {
+ "discussions": {
+ "nodes": nodes,
+ "pageInfo": {"hasNextPage": has_next, "endCursor": cursor},
+ }
+ }
+ }
+ }
+
+
+def _list_discussions(responses: list[dict], **kwargs):
+ api = _GraphqlApi(responses)
+ input_data = GithubListDiscussionsBlock.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, "repo_url": REPO_URL, **kwargs}
+ )
+ with mock.patch.object(repo, "get_api", lambda *a, **kw: api):
+ result = asyncio.run(
+ GithubListDiscussionsBlock.list_discussions(TEST_CREDENTIALS, input_data)
+ )
+ return result, api.requests
+
+
+def _discussion(title: str) -> dict:
+ return {"title": title, "url": f"https://github.com/owner/repo/discussions/{title}"}
+
+
+class TestListDiscussions:
+ def test_defaults_send_no_filters(self):
+ _, requests = _list_discussions([_discussions_page([])])
+ variables = requests[0]["variables"]
+ assert variables["owner"] == "owner"
+ assert variables["repo"] == "repo"
+ assert variables["categoryId"] is None
+ assert variables["answered"] is None
+ assert variables["states"] is None
+ assert variables["orderBy"] == {"field": "UPDATED_AT", "direction": "DESC"}
+
+ def test_page_size_is_capped_at_100(self):
+ _, requests = _list_discussions([_discussions_page([])], num_discussions=250)
+ assert requests[0]["variables"]["num"] == 100
+
+ def test_filters_are_translated_to_graphql_arguments(self):
+ _, requests = _list_discussions(
+ [_discussions_page([])],
+ answered="unanswered",
+ state="closed",
+ order_by="created",
+ direction="asc",
+ )
+ variables = requests[0]["variables"]
+ assert variables["answered"] is False
+ assert variables["states"] == ["CLOSED"]
+ assert variables["orderBy"] == {"field": "CREATED_AT", "direction": "ASC"}
+
+ def test_pagination_follows_the_cursor_and_truncates(self):
+ result, requests = _list_discussions(
+ [
+ _discussions_page(
+ [_discussion("a"), _discussion("b")], has_next=True, cursor="CUR"
+ ),
+ _discussions_page([_discussion("c"), _discussion("d")]),
+ ],
+ num_discussions=3,
+ )
+ assert [d["title"] for d in result] == ["a", "b", "c"]
+ assert requests[0]["variables"]["after"] is None
+ assert requests[1]["variables"]["after"] == "CUR"
+
+ def test_category_name_is_resolved_to_an_id(self):
+ categories = {
+ "data": {
+ "repository": {
+ "discussionCategories": {"nodes": [{"id": "DIC_1", "name": "Q&A"}]}
+ }
+ }
+ }
+ _, requests = _list_discussions(
+ [categories, _discussions_page([])], category="q&a"
+ )
+ assert requests[1]["variables"]["categoryId"] == "DIC_1"
+
+ def test_unknown_category_raises(self):
+ categories = {
+ "data": {
+ "repository": {
+ "discussionCategories": {"nodes": [{"id": "DIC_1", "name": "Q&A"}]}
+ }
+ }
+ }
+ with pytest.raises(ValueError, match="does not exist"):
+ _list_discussions([categories], category="Ideas")
+
+
+# ── get_user tests ──
+
+
+class TestGetUser:
+ def _call(self, username: str) -> str:
+ api = _FakeApi()
+ with mock.patch.object(users, "get_api", lambda *a, **kw: api):
+ asyncio.run(GithubGetUserInfoBlock.get_user(TEST_CREDENTIALS, username))
+ return api.calls[0][1]
+
+ def test_named_user(self):
+ assert self._call("octocat") == "https://api.github.com/users/octocat"
+
+ def test_empty_username_means_the_authenticated_user(self):
+ assert self._call("") == "https://api.github.com/user"
diff --git a/autogpt_platform/backend/backend/blocks/github/users.py b/autogpt_platform/backend/backend/blocks/github/users.py
new file mode 100644
index 0000000000..9741cde359
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/github/users.py
@@ -0,0 +1,97 @@
+from backend.blocks._base import (
+ Block,
+ BlockCategory,
+ BlockOutput,
+ BlockSchemaInput,
+ BlockSchemaOutput,
+)
+from backend.data.model import SchemaField
+
+from ._api import GITHUB_API_URL, get_api
+from ._auth import (
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ GithubCredentials,
+ GithubCredentialsField,
+ GithubCredentialsInput,
+)
+
+TEST_USER_PAYLOAD = {
+ "login": "octocat",
+ "name": "The Octocat",
+ "html_url": "https://github.com/octocat",
+ "avatar_url": "https://avatars.githubusercontent.com/u/583231",
+}
+
+
+class GithubGetUserInfoBlock(Block):
+ class Input(BlockSchemaInput):
+ credentials: GithubCredentialsInput = GithubCredentialsField("read:user")
+ username: str = SchemaField(
+ description="Username of the GitHub user to look up. "
+ "Leave empty to get the authenticated user (yourself).",
+ placeholder="octocat",
+ default="",
+ advanced=False,
+ )
+
+ class Output(BlockSchemaOutput):
+ username: str = SchemaField(description="Login (username) of the user")
+ name: str = SchemaField(description="Display name of the user")
+ profile_url: str = SchemaField(description="URL of the user's GitHub profile")
+ avatar_url: str = SchemaField(description="URL of the user's avatar image")
+ user: dict = SchemaField(
+ description="The full user object from the API. For the authenticated "
+ "user (i.e. when no username is given) this also includes private "
+ "account details such as plan, email and private repository counts."
+ )
+ error: str = SchemaField(
+ description="Error message if fetching the user info failed"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="046050c6-96cd-44fa-b73f-af5d790a43b6",
+ description="This block fetches information about a GitHub user, "
+ "or about the authenticated user (yourself) if no username is given.",
+ categories={BlockCategory.DEVELOPER_TOOLS},
+ input_schema=GithubGetUserInfoBlock.Input,
+ output_schema=GithubGetUserInfoBlock.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("username", "octocat"),
+ ("name", "The Octocat"),
+ ("profile_url", "https://github.com/octocat"),
+ ("avatar_url", "https://avatars.githubusercontent.com/u/583231"),
+ ("user", TEST_USER_PAYLOAD),
+ ],
+ test_mock={"get_user": lambda *args, **kwargs: TEST_USER_PAYLOAD},
+ )
+
+ @staticmethod
+ async def get_user(credentials: GithubCredentials, username: str) -> dict:
+ api = get_api(credentials, convert_urls=False)
+ url = (
+ f"{GITHUB_API_URL}/users/{username}"
+ if username
+ else f"{GITHUB_API_URL}/user"
+ )
+ response = await api.get(url)
+ return response.json()
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: GithubCredentials,
+ **kwargs,
+ ) -> BlockOutput:
+ user = await self.get_user(credentials, input_data.username)
+ yield "username", user["login"]
+ yield "name", user.get("name") or ""
+ yield "profile_url", user["html_url"]
+ yield "avatar_url", user["avatar_url"]
+ yield "user", user
diff --git a/docs/integrations/README.md b/docs/integrations/README.md
index 5dcae068c3..e97262cfd2 100644
--- a/docs/integrations/README.md
+++ b/docs/integrations/README.md
@@ -519,24 +519,30 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Github Discussion Trigger](block-integrations/github/triggers.md#github-discussion-trigger) | This block triggers on GitHub Discussions events |
| [Github Fork Repository](block-integrations/github/repo.md#github-fork-repository) | This block forks a GitHub repository to your account or an organization |
| [Github Get CI Results](block-integrations/github/ci.md#github-get-ci-results) | This block gets CI results for a commit or PR, with optional search for specific errors/warnings in logs |
+| [Github Get Notification Thread](block-integrations/github/notifications.md#github-get-notification-thread) | This block fetches a single GitHub notification thread |
| [Github Get PR Review Comments](block-integrations/github/reviews.md#github-get-pr-review-comments) | This block gets all review comments from a GitHub pull request or from a specific review |
| [Github Get Repository Info](block-integrations/github/repo.md#github-get-repository-info) | This block retrieves metadata about a GitHub repository |
| [Github Get Repository Tree](block-integrations/github/repo_files.md#github-get-repository-tree) | This block lists the entire file tree of a GitHub repository recursively |
+| [Github Get User Info](block-integrations/github/users.md#github-get-user-info) | This block fetches information about a GitHub user, or about the authenticated user (yourself) if no username is given |
| [Github Issues Trigger](block-integrations/github/triggers.md#github-issues-trigger) | This block triggers on GitHub issues events |
| [Github List Branches](block-integrations/github/repo_branches.md#github-list-branches) | This block lists all branches for a specified GitHub repository |
| [Github List Comments](block-integrations/github/issues.md#github-list-comments) | A block that retrieves all comments from a GitHub issue or pull request, including comment metadata and content |
| [Github List Commits](block-integrations/github/commits.md#github-list-commits) | This block lists commits on a branch in a GitHub repository |
| [Github List Discussions](block-integrations/github/repo.md#github-list-discussions) | This block lists recent discussions for a specified GitHub repository |
| [Github List Issues](block-integrations/github/issues.md#github-list-issues) | A block that retrieves a list of issues from a GitHub repository with their titles and URLs |
-| [Github List PR Reviewers](block-integrations/github/pull_requests.md#github-list-pr-reviewers) | This block lists all reviewers for a specified GitHub pull request |
+| [Github List Notifications](block-integrations/github/notifications.md#github-list-notifications) | This block lists GitHub notifications for the authenticated user, e |
+| [Github List PR Reviewers](block-integrations/github/pull_requests.md#github-list-pr-reviewers) | This block lists the requested reviewers for a specified GitHub pull request, optionally including users who have already submitted a review |
| [Github List PR Reviews](block-integrations/github/reviews.md#github-list-pr-reviews) | This block lists all reviews for a specified GitHub pull request |
| [Github List Pull Requests](block-integrations/github/pull_requests.md#github-list-pull-requests) | This block lists all pull requests for a specified GitHub repository |
-| [Github List Releases](block-integrations/github/repo.md#github-list-releases) | This block lists all releases for a specified GitHub repository |
+| [Github List Releases](block-integrations/github/repo.md#github-list-releases) | This block lists releases for a specified GitHub repository, optionally filtered by type and date range |
| [Github List Stargazers](block-integrations/github/repo.md#github-list-stargazers) | This block lists all users who have starred a specified GitHub repository |
| [Github List Tags](block-integrations/github/repo.md#github-list-tags) | This block lists all tags for a specified GitHub repository |
| [Github Make Branch](block-integrations/github/repo_branches.md#github-make-branch) | This block creates a new branch from a specified source branch |
| [Github Make Issue](block-integrations/github/issues.md#github-make-issue) | A block that creates new issues on GitHub repositories with a title and body content |
| [Github Make Pull Request](block-integrations/github/pull_requests.md#github-make-pull-request) | This block creates a new pull request on a specified GitHub repository |
+| [Github Mark Notification Thread As Done](block-integrations/github/notifications.md#github-mark-notification-thread-as-done) | This block marks a GitHub notification thread as done, removing it from the notification inbox |
+| [Github Mark Notification Thread As Read](block-integrations/github/notifications.md#github-mark-notification-thread-as-read) | This block marks a single GitHub notification thread as read |
+| [Github Mark Notifications As Read](block-integrations/github/notifications.md#github-mark-notifications-as-read) | This block marks all GitHub notifications as read, optionally scoped to a single repository |
| [Github Merge Pull Request](block-integrations/github/pull_requests.md#github-merge-pull-request) | This block merges a pull request using merge, squash, or rebase |
| [Github Multi File Commit](block-integrations/github/commits.md#github-multi-file-commit) | This block creates a single commit with multiple file upsert/delete operations using the Git Trees API |
| [Github Pull Request Trigger](block-integrations/github/triggers.md#github-pull-request-trigger) | This block triggers on pull request events and outputs the event type and payload |
@@ -553,6 +559,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Github Submit Pending Review](block-integrations/github/reviews.md#github-submit-pending-review) | This block submits a pending (draft) review on a GitHub pull request |
| [Github Unassign Issue](block-integrations/github/issues.md#github-unassign-issue) | A block that removes a user's assignment from a GitHub issue |
| [Github Unassign PR Reviewer](block-integrations/github/pull_requests.md#github-unassign-pr-reviewer) | This block unassigns a reviewer from a specified GitHub pull request |
+| [Github Unsubscribe Notification Thread](block-integrations/github/notifications.md#github-unsubscribe-notification-thread) | This block unsubscribes you from a GitHub notification thread, muting future notifications unless you are mentioned again |
| [Github Update Check Run](block-integrations/github/checks.md#github-update-check-run) | Updates an existing check run in a GitHub repository |
| [Github Update Comment](block-integrations/github/issues.md#github-update-comment) | A block that updates an existing comment on a GitHub issue or pull request |
| [Github Update File](block-integrations/github/repo_files.md#github-update-file) | This block updates an existing file in a GitHub repository |
diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.md
index 8307702c4f..2d6f777a90 100644
--- a/docs/integrations/SUMMARY.md
+++ b/docs/integrations/SUMMARY.md
@@ -80,6 +80,7 @@
* [GitHub CI](block-integrations/github/ci.md)
* [GitHub Commits](block-integrations/github/commits.md)
* [GitHub Issues](block-integrations/github/issues.md)
+* [GitHub Notifications](block-integrations/github/notifications.md)
* [GitHub Pull Requests](block-integrations/github/pull_requests.md)
* [GitHub Repo](block-integrations/github/repo.md)
* [GitHub Repo Branches](block-integrations/github/repo_branches.md)
@@ -87,6 +88,7 @@
* [GitHub Reviews](block-integrations/github/reviews.md)
* [GitHub Statuses](block-integrations/github/statuses.md)
* [GitHub Triggers](block-integrations/github/triggers.md)
+* [GitHub Users](block-integrations/github/users.md)
* [Google Calendar](block-integrations/google/calendar.md)
* [Google Docs](block-integrations/google/docs.md)
* [Google Gmail](block-integrations/google/gmail.md)
diff --git a/docs/integrations/block-integrations/github/commits.md b/docs/integrations/block-integrations/github/commits.md
index e2eb44ad52..2ae0fb5834 100644
--- a/docs/integrations/block-integrations/github/commits.md
+++ b/docs/integrations/block-integrations/github/commits.md
@@ -21,8 +21,14 @@ Each commit entry includes the SHA, commit message, author name, date, and a URL
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
| branch | Branch name to list commits from | str | No |
-| per_page | Number of commits to return (max 100) | int | No |
-| page | Page number for pagination | int | No |
+| limit | Maximum number of commits to fetch | int | No |
+| per_page | [Legacy] Number of commits to return per page (max 100). If set (or `page` is set), `limit` is ignored. | int | No |
+| page | [Legacy] Page number for pagination. If set (or `per_page` is set), `limit` is ignored. | int | No |
+| path | Only include commits that touch this file or directory path | str | No |
+| author | Only include commits authored by this user (GitHub username or email address) | str | No |
+| committer | Only include commits committed by this user (GitHub username or email address) | str | No |
+| since | Only include commits after the given ISO 8601 timestamp | str | No |
+| until | Only include commits before the given ISO 8601 timestamp | str | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/issues.md b/docs/integrations/block-integrations/github/issues.md
index 300eda5c5e..40fd7678a2 100644
--- a/docs/integrations/block-integrations/github/issues.md
+++ b/docs/integrations/block-integrations/github/issues.md
@@ -114,6 +114,8 @@ Each comment includes the comment ID, body text, author username, and a direct U
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| issue_url | URL of the GitHub issue or pull request | str | Yes |
+| limit | Maximum number of comments to fetch | int | No |
+| since | Only include comments updated after the given ISO 8601 timestamp | str | No |
### Outputs
@@ -149,6 +151,17 @@ The block takes the GitHub credentials and repository URL as inputs. It then sen
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
+| state | Only include issues in this state | "open" \| "closed" \| "all" | No |
+| include_pull_requests | Whether to also include pull requests in the results. The GitHub API considers every pull request an issue. | bool | No |
+| labels | Only include issues that have all of these labels | List[str] | No |
+| limit | Maximum number of issues to fetch | int | No |
+| assignee | Only include issues assigned to this user. Use 'none' for unassigned issues, or '*' for issues with any assignee. | str | No |
+| creator | Only include issues created by this user | str | No |
+| mentioned | Only include issues in which this user is mentioned | str | No |
+| milestone | Only include issues in this milestone, by milestone number. Use 'none' for issues without a milestone, or '*' for issues with any milestone. | str | No |
+| sort | What to sort the issues by | "created" \| "updated" \| "comments" | No |
+| direction | Sort direction | "asc" \| "desc" | No |
+| since | Only include issues updated after the given ISO 8601 timestamp | str | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/notifications.md b/docs/integrations/block-integrations/github/notifications.md
new file mode 100644
index 0000000000..22e05217f4
--- /dev/null
+++ b/docs/integrations/block-integrations/github/notifications.md
@@ -0,0 +1,198 @@
+# GitHub Notifications
+<!-- MANUAL: file_description -->
+Blocks for reading and clearing the GitHub notification inbox — the same feed as the bell icon on github.com — so an agent can triage what it is being asked to look at and then clear those threads behind itself.
+<!-- END MANUAL -->
+
+## Github Get Notification Thread
+
+### What it is
+This block fetches a single GitHub notification thread.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Fetches one thread from `/notifications/threads/{thread_id}` and normalises it into the same `NotificationItem` shape the list block emits, so both can feed the same downstream nodes. The subject URL GitHub returns is an API URL, and the block rewrites it per path segment into its github.com equivalent: `/pulls/{n}` becomes `/pull/{n}`, `/commits/{sha}` becomes `/commit/{sha}`, and a release — which the API addresses by numeric id but the web addresses by tag — degrades to the repository's releases index. Anything that is not a repo-scoped API URL is passed through untouched. Note that a thread id is the notification's own id, not the issue or pull request number.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| thread_id | ID of the notification thread | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if fetching the notification thread failed | str |
+| notification | The notification thread | NotificationItem |
+| title | Title of the notification subject | str |
+| reason | Reason you received the notification (e.g. 'mention', 'review_requested', 'subscribed') | str |
+| unread | Whether the notification is unread | bool |
+| subject_type | Type of the notification subject (e.g. 'Issue', 'PullRequest', 'Release') | str |
+| subject_url | URL of the notification subject on GitHub | str |
+| repository | Full name of the repository (owner/repo) | str |
+| updated_at | ISO 8601 timestamp of the last update to the thread | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+A triage agent walks an inbox listing and re-fetches each thread before acting on it. A notification may have been read, resolved or closed elsewhere since the listing was taken, and acting on stale state means replying to something a colleague already handled.
+<!-- END MANUAL -->
+
+---
+
+## Github List Notifications
+
+### What it is
+This block lists GitHub notifications for the authenticated user, e.g. mentions, review requests, and updates on subscribed threads.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Reads the notification inbox, either globally or scoped to a single repository, and follows pagination until `limit` items are collected rather than returning only the first page. The two endpoints differ in page size — the global `/notifications` caps a page at 50 while the repo-scoped one allows the usual 100 — and the block uses whichever applies. `repo` accepts either `{owner}/{repo}` or a full repository URL. By default only unread threads come back; `include_read` sends `all=true`, and `participating_only` narrows to threads where you are directly involved rather than merely watching. `since` and `before` bound the results by last-update time. Each item is flattened to a `NotificationItem` whose `subject_url` is a browsable github.com link, not the API URL.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| include_read | Whether to include notifications that are already marked as read | bool | No |
+| participating_only | Whether to only include notifications in which you are directly participating or mentioned | bool | No |
+| limit | Maximum number of notifications to fetch | int | No |
+| repo | Repository to list notifications for, as '{owner}/{repo}' or a full repository URL. Leave empty to list notifications for all repositories. | str | No |
+| since | Only show notifications updated after the given ISO 8601 timestamp | str | No |
+| before | Only show notifications updated before the given ISO 8601 timestamp | str | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if listing notifications failed | str |
+| notification | Each notification thread | Notification |
+| notifications | List of notification threads | List[NotificationItem] |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+A morning triage agent lists notifications with `participating_only` enabled, groups them by `reason` — `review_requested`, `mention`, `assign` — and posts one ranked digest to Slack, so a maintainer sees what actually needs them instead of scrolling the bell menu.
+<!-- END MANUAL -->
+
+---
+
+## Github Mark Notification Thread As Done
+
+### What it is
+This block marks a GitHub notification thread as done, removing it from the notification inbox.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Sends `DELETE` to `/notifications/threads/{thread_id}`. Despite the verb, nothing is deleted: GitHub's "done" state removes the thread from your inbox and marks it read, while the underlying issue, pull request or discussion is untouched, and new activity on that subject can surface it again. This is distinct from unsubscribing, which stops future notifications for the subject entirely.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| thread_id | ID of the notification thread | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if marking the thread as done failed | str |
+| success | Whether the notification thread was marked as done | bool |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Once a triage agent has summarised and filed a batch of notifications, it marks each one done so the next run starts from a clean inbox instead of re-reporting the same threads.
+<!-- END MANUAL -->
+
+---
+
+## Github Mark Notification Thread As Read
+
+### What it is
+This block marks a single GitHub notification thread as read.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Sends `PATCH` to `/notifications/threads/{thread_id}`. The thread keeps its place in the inbox but loses its unread flag, so a later listing without `include_read` skips it. Use this rather than marking the thread done when it should stay visible.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| thread_id | ID of the notification thread | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if marking the thread as read failed | str |
+| success | Whether the notification thread was marked as read | bool |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+An agent that auto-answers a known subset of mentions marks only those threads read, leaving everything it could not handle unread and still in the inbox for a human.
+<!-- END MANUAL -->
+
+---
+
+## Github Mark Notifications As Read
+
+### What it is
+This block marks all GitHub notifications as read, optionally scoped to a single repository.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Sends `PUT` to the notifications endpoint, either globally or for one repository; `repo` accepts `{owner}/{repo}` or a full repository URL, and leaving it empty clears the whole inbox. `last_read_at` restricts the sweep to threads updated before that timestamp and defaults to now, which is what makes this safe to run against a busy inbox: anything arriving while the request is in flight keeps its unread state rather than being silently cleared.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| repo | Repository to mark notifications as read for, as '{owner}/{repo}' or a full repository URL. Leave empty to mark notifications for all repositories. | str | No |
+| last_read_at | Only mark notifications updated before the given ISO 8601 timestamp as read. Defaults to the current time. | str | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if marking notifications as read failed | str |
+| success | Whether the notifications were marked as read | bool |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+A weekly hygiene agent passes the start of the week as `last_read_at`, clearing a backlog of stale notifications in one call while leaving the last few days' worth untouched.
+<!-- END MANUAL -->
+
+---
+
+## Github Unsubscribe Notification Thread
+
+### What it is
+This block unsubscribes you from a GitHub notification thread, muting future notifications unless you are mentioned again.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Sends `DELETE` to `/notifications/threads/{thread_id}/subscription`, a different endpoint from the one that marks a thread done. This ends your subscription to the subject, so further activity on that issue or pull request produces no new notifications at all. The effect persists until you subscribe again or someone mentions you directly.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| thread_id | ID of the notification thread | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if unsubscribing from the thread failed | str |
+| success | Whether you were unsubscribed from the notification thread | bool |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+A long-running, high-traffic issue that an agent was added to but has no stake in gets unsubscribed after a single triage pass, so its every comment stops re-entering the inbox.
+<!-- END MANUAL -->
+
+---
diff --git a/docs/integrations/block-integrations/github/pull_requests.md b/docs/integrations/block-integrations/github/pull_requests.md
index 7aa7d3cb5e..218671141b 100644
--- a/docs/integrations/block-integrations/github/pull_requests.md
+++ b/docs/integrations/block-integrations/github/pull_requests.md
@@ -43,7 +43,7 @@ The reviewer must have access to the repository. Organization members can typica
## Github List PR Reviewers
### What it is
-This block lists all reviewers for a specified GitHub pull request.
+This block lists the requested reviewers for a specified GitHub pull request, optionally including users who have already submitted a review.
### How it works
<!-- MANUAL: how_it_works -->
@@ -57,14 +57,15 @@ This includes both pending review requests and users who have already submitted
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| pr_url | URL of the GitHub pull request | str | Yes |
+| include_past_reviewers | Also include users who have already submitted a review, in addition to users whose review request is pending | bool | No |
### Outputs
| Output | Description | Type |
|--------|-------------|------|
| error | Error message if listing reviewers failed | str |
-| reviewer | Reviewers with their username and profile URL | Reviewer |
-| reviewers | List of reviewers with their username and profile URL | List[ReviewerItem] |
+| reviewer | Reviewers with their username, profile URL, and review status. | Reviewer |
+| reviewers | List of reviewers with their username, profile URL, and review status | List[ReviewerItem] |
### Possible use case
<!-- MANUAL: use_case -->
@@ -94,6 +95,12 @@ The block returns open pull requests by default, allowing you to monitor pending
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
+| state | Only include pull requests in this state | "open" \| "closed" \| "all" | No |
+| base | Only include pull requests targeting this base branch | str | No |
+| limit | Maximum number of pull requests to fetch | int | No |
+| head | Only include pull requests from this head branch. Format: 'user:branch' or 'org:branch'. | str | No |
+| sort | What to sort the pull requests by | "created" \| "updated" \| "popularity" \| "long-running" | No |
+| direction | Sort direction | "asc" \| "desc" | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/repo.md b/docs/integrations/block-integrations/github/repo.md
index 9fa26c6c8b..3fa8862712 100644
--- a/docs/integrations/block-integrations/github/repo.md
+++ b/docs/integrations/block-integrations/github/repo.md
@@ -145,7 +145,12 @@ You can limit the number of discussions retrieved with the num_discussions param
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
-| num_discussions | Number of discussions to fetch | int | No |
+| num_discussions | Maximum number of discussions to fetch | int | No |
+| category | Only include discussions in the category with this name | str | No |
+| answered | Only include discussions that are (un)answered | "all" \| "answered" \| "unanswered" | No |
+| state | Only include discussions in this state | "all" \| "open" \| "closed" | No |
+| order_by | What to sort the discussions by | "created" \| "updated" | No |
+| direction | Sort direction | "asc" \| "desc" | No |
### Outputs
@@ -169,7 +174,7 @@ You can limit the number of discussions retrieved with the num_discussions param
## Github List Releases
### What it is
-This block lists all releases for a specified GitHub repository.
+This block lists releases for a specified GitHub repository, optionally filtered by type and date range.
### How it works
<!-- MANUAL: how_it_works -->
@@ -183,14 +188,18 @@ The block returns release information including names and URLs, outputting both
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
+| release_type | Only include releases of this type | "all" \| "stable" \| "prerelease" \| "draft" | No |
+| limit | Maximum number of releases to fetch | int | No |
+| published_after | Only include releases published after the given ISO 8601 timestamp | str | No |
+| published_before | Only include releases published before the given ISO 8601 timestamp | str | No |
### Outputs
| Output | Description | Type |
|--------|-------------|------|
| error | Error message if the operation failed | str |
-| release | Releases with their name and file tree browser URL | Release |
-| releases | List of releases with their name and file tree browser URL | List[ReleaseItem] |
+| release | Releases with their name, tag, URL, publish date, and type | Release |
+| releases | List of releases with their name, tag, URL, publish date, and type | List[ReleaseItem] |
### Possible use case
<!-- MANUAL: use_case -->
@@ -220,6 +229,7 @@ Each stargazer entry includes their username and a link to their GitHub profile.
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
+| limit | Maximum number of stargazers to fetch | int | No |
### Outputs
@@ -257,6 +267,7 @@ Each tag includes its name and a URL to browse the repository files at that tag.
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
+| limit | Maximum number of tags to fetch | int | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/repo_branches.md b/docs/integrations/block-integrations/github/repo_branches.md
index ad895aefde..300c06790d 100644
--- a/docs/integrations/block-integrations/github/repo_branches.md
+++ b/docs/integrations/block-integrations/github/repo_branches.md
@@ -101,8 +101,10 @@ Each branch entry includes its name and a URL to browse the repository file tree
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| repo_url | URL of the GitHub repository | str | Yes |
-| per_page | Number of branches to return per page (max 100) | int | No |
-| page | Page number for pagination | int | No |
+| limit | Maximum number of branches to fetch | int | No |
+| per_page | [Legacy] Number of branches to return per page (max 100). If set (or `page` is set), `limit` is ignored. | int | No |
+| page | [Legacy] Page number for pagination. If set (or `per_page` is set), `limit` is ignored. | int | No |
+| protected | Only include branches that are (un)protected | "all" \| "protected" \| "unprotected" | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/reviews.md b/docs/integrations/block-integrations/github/reviews.md
index fac3818b6c..7b351de7ac 100644
--- a/docs/integrations/block-integrations/github/reviews.md
+++ b/docs/integrations/block-integrations/github/reviews.md
@@ -145,6 +145,10 @@ Use this to check approval status, see who has reviewed, or analyze the review h
|-------|-------------|------|----------|
| repo | GitHub repository | str | Yes |
| pr_number | Pull request number | int | Yes |
+| reviewer | Only include reviews by this user | str | No |
+| state | Only include reviews with this state. Note: 'pending' reviews are your own unsubmitted draft reviews, which are excluded by any other choice. | "all" \| "approved" \| "changes_requested" \| "commented" \| "dismissed" \| "pending" | No |
+| latest_only | Only include each reviewer's latest review, reflecting their current stance | bool | No |
+| limit | Maximum number of reviews to fetch | int | No |
### Outputs
diff --git a/docs/integrations/block-integrations/github/users.md b/docs/integrations/block-integrations/github/users.md
new file mode 100644
index 0000000000..d19add82a9
--- /dev/null
+++ b/docs/integrations/block-integrations/github/users.md
@@ -0,0 +1,38 @@
+# GitHub Users
+<!-- MANUAL: file_description -->
+A block for looking up a GitHub user's public profile, or the profile of the account the supplied credentials belong to.
+<!-- END MANUAL -->
+
+## Github Get User Info
+
+### What it is
+This block fetches information about a GitHub user, or about the authenticated user (yourself) if no username is given.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls `/users/{username}` when a username is given, and the authenticated-user endpoint `/user` when it is left empty — which is how one block answers both "who is this person" and "who am I". The commonly used fields are pulled out as discrete outputs, and the untouched response is emitted as `user` as well, because GitHub returns roughly forty fields and which ones matter depends on the caller. The two endpoints do not return the same object: for the authenticated user the payload additionally carries private account details such as plan, email and private repository counts, so route `user` with that in mind.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| username | Username of the GitHub user to look up. Leave empty to get the authenticated user (yourself). | str | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if fetching the user info failed | str |
+| username | Login (username) of the user | str |
+| name | Display name of the user | str |
+| profile_url | URL of the user's GitHub profile | str |
+| avatar_url | URL of the user's avatar image | str |
+| user | The full user object from the API. For the authenticated user (i.e. when no username is given) this also includes private account details such as plan, email and private repository counts. | Dict[str, Any] |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+A graph resolves the operating account once at the start of a run — no username, so it hits `/user` — and reuses the returned login to filter issues, pull requests and review requests to that person's own, instead of hardcoding a username into every downstream block.
+<!-- END MANUAL -->
+
+---