Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(tasks): show github pr in tasks (#3517)
Will Hutchinson7d6b870324ec
diff --git a/js/app/packages/block-md/component/InlineTaskGithubPullRequests.tsx b/js/app/packages/block-md/component/InlineTaskGithubPullRequests.tsxnew file mode 100644index 0000000000..ae563e7fe7--- /dev/null+++ b/js/app/packages/block-md/component/InlineTaskGithubPullRequests.tsx@@ -0,0 +1,45 @@+import { useBlockAliasedName, useBlockId } from '@core/block';+import { useDocumentGithubPullRequestsQuery } from '@queries/storage/github-pull-requests';+import type { GithubPullRequest } from '@service-storage/generated/schemas';+import { Layer } from '@ui';+import { cn } from '@ui/utils/classname';+import { createMemo, For, type JSX, Show } from 'solid-js';++const GITHUB_PULL_REQUEST_LINK_CLASS = cn(+ 'inline-flex items-center gap-1.5 min-w-0 ring ring-edge-muted',+ 'px-2 py-1 leading-tight text-left rounded-full',+ 'bg-surface text-ink-muted hover:bg-hover hover:text-ink',+ 'focus-visible:bg-active focus-visible:ring-accent/10'+);++export function InlineTaskGithubPullRequests(): JSX.Element {+ const blockId = useBlockId();+ const isTask = useBlockAliasedName() === 'task';+ const query = useDocumentGithubPullRequestsQuery(blockId, isTask);++ const pullRequests = createMemo((): GithubPullRequest[] => {+ if (!isTask || query.isLoading || query.isError) return [];+ return query.data?.pullRequests ?? [];+ });++ return (+ <Show when={pullRequests().length > 0}>+ <div class="flex flex-row flex-wrap items-center gap-2 text-sm mb-6">+ <For each={pullRequests()}>+ {(pullRequest) => (+ <Layer depth={2}>+ <a+ class={GITHUB_PULL_REQUEST_LINK_CLASS}+ href={pullRequest.url}+ target="_blank"+ rel="noopener noreferrer"+ >+ <span class="truncate">{pullRequest.displayName}</span>+ </a>+ </Layer>+ )}+ </For>+ </div>+ </Show>+ );+}diff --git a/js/app/packages/block-md/component/Notebook.tsx b/js/app/packages/block-md/component/Notebook.tsxindex b25316ce12..cea15c6af1 100644--- a/js/app/packages/block-md/component/Notebook.tsx+++ b/js/app/packages/block-md/component/Notebook.tsx@@ -31,6 +31,7 @@ import {Show,untrack,} from 'solid-js';+import { InlineTaskGithubPullRequests } from './InlineTaskGithubPullRequests';import { InlineTaskProperties } from './InlineTaskProperties';import { InstructionsEditor } from './InstructionsEditor';import { MarkdownEditor } from './MarkdownEditor';@@ -266,6 +267,7 @@ export function Notebook() {<TitleEditor autoFocusOnMount={!navigatedFromJK()} /><div class="spacer h-3" /><InlineTaskProperties />+ <InlineTaskGithubPullRequests /><ParamsProvider><MarkdownEditor autoFocusOnMount={!navigatedFromJK()} /><Show when={ENABLE_RAIL_CHAT_TASK_COMMENTS && isTask}>diff --git a/js/app/packages/queries/storage/github-pull-requests.ts b/js/app/packages/queries/storage/github-pull-requests.tsnew file mode 100644index 0000000000..cf8ccc04ea--- /dev/null+++ b/js/app/packages/queries/storage/github-pull-requests.ts@@ -0,0 +1,59 @@+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { GithubPullRequestsResponse } from '@service-storage/generated/schemas';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { documentGithubPullRequestsKeys } from './keys';++const DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME = 60 * 1000;++type DocumentIdInput =+ | string+ | null+ | undefined+ | Accessor<string | null | undefined>;+type EnabledInput = boolean | Accessor<boolean>;++function readDocumentId(+ documentId: DocumentIdInput+): string | null | undefined {+ return typeof documentId === 'function' ? documentId() : documentId;+}++function readEnabled(enabled: EnabledInput | undefined): boolean {+ if (enabled === undefined) return true;+ return typeof enabled === 'function' ? enabled() : enabled;+}++async function fetchDocumentGithubPullRequests(+ documentId: string+): Promise<GithubPullRequestsResponse> {+ return await throwOnErr(() =>+ storageServiceClient.getDocumentGithubPullRequests({ documentId })+ );+}++export function useDocumentGithubPullRequestsQuery(+ documentId: DocumentIdInput,+ enabled?: EnabledInput+) {+ return useQuery(() => {+ const currentDocumentId = readDocumentId(documentId);++ return {+ queryKey: currentDocumentId+ ? documentGithubPullRequestsKeys.list(currentDocumentId).queryKey+ : documentGithubPullRequestsKeys.list._def,+ queryFn: () => {+ if (!currentDocumentId) {+ throw new Error(+ 'Document ID is required to fetch GitHub pull requests'+ );+ }+ return fetchDocumentGithubPullRequests(currentDocumentId);+ },+ staleTime: DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME,+ enabled: !!currentDocumentId && readEnabled(enabled),+ };+ });+}diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.tsindex 2b45525a90..e1d3181f34 100644--- a/js/app/packages/queries/storage/keys.ts+++ b/js/app/packages/queries/storage/keys.ts@@ -31,6 +31,15 @@ export const binaryDocumentKeys = createQueryKeys('binaryDocument', {}),});+export const documentGithubPullRequestsKeys = createQueryKeys(+ 'documentGithubPullRequests',+ {+ list: (documentId: string) => ({+ queryKey: [documentId],+ }),+ }+);+// Scoped under `entity` so `invalidateQueries({ queryKey: ['entity'] })`// (fired from the move/rename mutations) refreshes every key below.export const entityKeys = createQueryKeys('entity', {@@ -50,9 +59,10 @@ export const instructionsMdKeys = createQueryKeys('instructionsMd', {});/**- * @deprecated Use `projectsKeys` or `deletedKeys` directly+ * @deprecated Use the specific key exports directly.*/export const storageKeys = {projects: projectsKeys,deleted: deletedKeys,+ documentGithubPullRequests: documentGithubPullRequestsKeys,};diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 52e60321b4..7d03d43976 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -29,6 +29,7 @@ import { err, ok, type Result } from 'neverthrow';import type {AccessLevel,CallRecordPreview,+ GithubPullRequestsResponse,PostSoupAstRequest,PostSoupRequest,SoupPage,@@ -620,6 +621,19 @@ export const storageServiceClient = {}));},+ async getDocumentGithubPullRequests({+ documentId,+ }: {+ documentId: string;+ }): Promise<+ Result<GithubPullRequestsResponse, ResultError<FetchWithTokenErrorCode>[]>+ > {+ return await dssFetch<GithubPullRequestsResponse>(+ `/documents/${documentId}/github_prs`,+ { method: 'GET' }+ );+ },+async exportDocument({ documentId }) {return (await dssFetch<ExportDocumentResponse>(diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.tsnew file mode 100644index 0000000000..3cf1483726--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display-ready data for a GitHub pull request associated with a task.+ */+export interface GithubPullRequest {+ /** A compact label suitable for display in the UI. */+ displayName: string;+ /** The stored GitHub association key, in `owner/repo/pull/number` format. */+ githubKey: string;+ /**+ * The GitHub pull request number.+ * @minimum 0+ */+ number: number;+ /** The GitHub repository owner or organization. */+ owner: string;+ /** The GitHub repository name. */+ repo: string;+ /** The public GitHub URL for the pull request. */+ url: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestsResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestsResponse.tsnew file mode 100644index 0000000000..dbe69392be--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestsResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPullRequest } from './githubPullRequest';++/**+ * Response containing all GitHub pull requests associated with a task.+ */+export interface GithubPullRequestsResponse {+ /** Parsed pull requests, in repository query order. */+ pullRequests: GithubPullRequest[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 6a53d33351..c9410499e0 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -437,6 +437,8 @@ export * from './getProjectsResponse';export * from './getRecentActivityHandlerParams';export * from './getUserDocumentsHandlerParams';export * from './getUserHistoryResponse';+export * from './githubPullRequest';+export * from './githubPullRequestsResponse';export * from './hashMap';export * from './hashMapOneOf';export * from './hashMapOneOfAllOf';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex f83285c337..819a6c8b4b 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -3617,6 +3617,55 @@ export const exportDocumentResponse = zod.object({.describe('The presigned url to download the raw content of the document'),});+/**+ * Returns GitHub pull requests associated with a task document.+Returns 400 if the document is not a task.+ * @summary Handler for `GET /documents/{document_id}/github_prs`.+ */+export const getDocumentGithubPullRequestsParams = zod.object({+ document_id: zod.string().describe('Document ID'),+});++export const getDocumentGithubPullRequestsResponsePullRequestsItemNumberMin = 0;++export const getDocumentGithubPullRequestsResponse = zod+ .object({+ pullRequests: zod+ .array(+ zod+ .object({+ displayName: zod+ .string()+ .describe('A compact label suitable for display in the UI.'),+ githubKey: zod+ .string()+ .describe(+ 'The stored GitHub association key, in `owner\/repo\/pull\/number` format.'+ ),+ number: zod+ .number()+ .min(+ getDocumentGithubPullRequestsResponsePullRequestsItemNumberMin+ )+ .describe('The GitHub pull request number.'),+ owner: zod+ .string()+ .describe('The GitHub repository owner or organization.'),+ repo: zod.string().describe('The GitHub repository name.'),+ url: zod+ .string()+ .describe('The public GitHub URL for the pull request.'),+ })+ .describe(+ 'Display-ready data for a GitHub pull request associated with a task.'+ )+ )+ .describe('Parsed pull requests, in repository query order.'),+ })+ .describe(+ 'Response containing all GitHub pull requests associated with a task.'+ );+/*** @summary Gets the presigned url(s) for the document. aka location*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 6ef8c52c4b..d076785733 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -3146,6 +3146,77 @@}}},+ "/documents/{document_id}/github_prs": {+ "get": {+ "tags": ["document"],+ "summary": "Handler for `GET /documents/{document_id}/github_prs`.",+ "description": "Returns GitHub pull requests associated with a task document.\nReturns 400 if the document is not a task.",+ "operationId": "get_document_github_pull_requests",+ "parameters": [+ {+ "name": "document_id",+ "in": "path",+ "description": "Document ID",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GithubPullRequestsResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/documents/{document_id}/location": {"get": {"tags": ["document"],@@ -10221,6 +10292,60 @@}}},+ "GithubPullRequest": {+ "type": "object",+ "description": "Display-ready data for a GitHub pull request associated with a task.",+ "required": [+ "githubKey",+ "owner",+ "repo",+ "number",+ "url",+ "displayName"+ ],+ "properties": {+ "displayName": {+ "type": "string",+ "description": "A compact label suitable for display in the UI."+ },+ "githubKey": {+ "type": "string",+ "description": "The stored GitHub association key, in `owner/repo/pull/number` format."+ },+ "number": {+ "type": "integer",+ "format": "int64",+ "description": "The GitHub pull request number.",+ "minimum": 0+ },+ "owner": {+ "type": "string",+ "description": "The GitHub repository owner or organization."+ },+ "repo": {+ "type": "string",+ "description": "The GitHub repository name."+ },+ "url": {+ "type": "string",+ "description": "The public GitHub URL for the pull request."+ }+ }+ },+ "GithubPullRequestsResponse": {+ "type": "object",+ "description": "Response containing all GitHub pull requests associated with a task.",+ "required": ["pullRequests"],+ "properties": {+ "pullRequests": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/GithubPullRequest"+ },+ "description": "Parsed pull requests, in repository query order."+ }+ }+ },"HashMap": {"type": "object","additionalProperties": {diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.tsindex e3e420e47c..bac403a36d 100644--- a/js/app/packages/service-clients/service-storage/service.ts+++ b/js/app/packages/service-clients/service-storage/service.ts@@ -401,6 +401,14 @@ export const StorageService = new Svc('Document++ Storage Service API')result: schemas.getDocumentVersionResponse.shape.data.shape,throws: withFetchErrors(),})+ .fn('getDocumentGithubPullRequests', {+ description: 'Get GitHub pull requests associated with a task document',+ args: {+ documentId: schemas.getDocumentGithubPullRequestsParams.shape.document_id,+ },+ result: schemas.getDocumentGithubPullRequestsResponse.shape,+ throws: withFetchErrors(),+ }).fn('createDocument', {description: schemas.createDocumentResponse.description!,args: schemas.createDocumentBody.shape,diff --git a/rust/cloud-storage/.sqlx/query-28df117b319120af2c7f9b3dbfdd45539b62c00cb222b029e501cd7a40e83ccd.json b/rust/cloud-storage/.sqlx/query-28df117b319120af2c7f9b3dbfdd45539b62c00cb222b029e501cd7a40e83ccd.jsonnew file mode 100644index 0000000000..50a96efdf5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-28df117b319120af2c7f9b3dbfdd45539b62c00cb222b029e501cd7a40e83ccd.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT github_key\n FROM github_pr_tasks\n WHERE task_id = $1\n ORDER BY created_at ASC, github_key ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "github_key",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "28df117b319120af2c7f9b3dbfdd45539b62c00cb222b029e501cd7a40e83ccd"+}diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 4020e44b4c..a46d315c5d 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -158,6 +158,7 @@ use utoipa::OpenApi;documents::location::get_location_handler,documents_hex::inbound::axum_router::get_location::get_location_v3_handler,documents_hex::inbound::axum_router::get_branch_name::get_branch_name_handler,+ documents_hex::inbound::axum_router::get_github_pull_requests::get_github_pull_requests_handler,documents_hex::inbound::axum_router::get_short_id::get_short_id_handler,documents::simple_save::handler,documents::initialize_user_documents::handler,@@ -434,6 +435,8 @@ use utoipa::OpenApi;ExcludeDefaultViewRequest,BranchNameResponse,ShortIdResponse,+ documents_hex::domain::models::GithubPullRequest,+ documents_hex::domain::models::GithubPullRequestsResponse,// Sync servicesync_service_hex::domain::models::BulkWakeupRequest,diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rsindex 3c29fd4ed3..49546c77e9 100644--- a/rust/cloud-storage/documents/src/domain/models.rs+++ b/rust/cloud-storage/documents/src/domain/models.rs@@ -103,6 +103,86 @@ pub struct TaskBranchName {pub branch_name: String,}+/// Display-ready data for a GitHub pull request associated with a task.+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct GithubPullRequest {+ /// The stored GitHub association key, in `owner/repo/pull/number` format.+ pub github_key: String,+ /// The GitHub repository owner or organization.+ pub owner: String,+ /// The GitHub repository name.+ pub repo: String,+ /// The GitHub pull request number.+ pub number: u64,+ /// The public GitHub URL for the pull request.+ pub url: String,+ /// A compact label suitable for display in the UI.+ pub display_name: String,+}++impl GithubPullRequest {+ /// Parse a stored GitHub PR key in `owner/repo/pull/number` format.+ pub fn from_github_key(github_key: &str) -> Option<Self> {+ let mut parts = github_key.split('/');+ let (Some(owner), Some(repo), Some("pull"), Some(number), None) = (+ parts.next(),+ parts.next(),+ parts.next(),+ parts.next(),+ parts.next(),+ ) else {+ return None;+ };++ if owner.is_empty() || repo.is_empty() {+ return None;+ }++ let number = number.parse::<u64>().ok()?;+ let url = format!("https://github.com/{owner}/{repo}/pull/{number}");+ let display_name = format!("{owner}/{repo}#{number}");++ Some(Self {+ github_key: github_key.to_string(),+ owner: owner.to_string(),+ repo: repo.to_string(),+ number,+ url,+ display_name,+ })+ }+}++/// Response containing all GitHub pull requests associated with a task.+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct GithubPullRequestsResponse {+ /// Parsed pull requests, in repository query order.+ pub pull_requests: Vec<GithubPullRequest>,+}++impl GithubPullRequestsResponse {+ /// Build a response from stored GitHub PR keys, skipping malformed rows.+ pub fn from_github_keys(github_keys: Vec<String>) -> Self {+ let mut pull_requests = Vec::new();++ for github_key in github_keys {+ match GithubPullRequest::from_github_key(&github_key) {+ Some(pull_request) => pull_requests.push(pull_request),+ None => tracing::warn!(+ github_key = %github_key,+ "skipping malformed GitHub pull request key"+ ),+ }+ }++ Self { pull_requests }+ }+}+/// Request body for copying a document.#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/documents/src/domain/ports/mod.rs b/rust/cloud-storage/documents/src/domain/ports/mod.rsindex 3cc3f34a1c..7da1f56069 100644--- a/rust/cloud-storage/documents/src/domain/ports/mod.rs+++ b/rust/cloud-storage/documents/src/domain/ports/mod.rs@@ -26,7 +26,7 @@ use model_entity::Entity;use super::models::{BranchNameContext, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- LocationQueryParams, TaskBranchName, TeamTaskMetadata,+ GithubPullRequestsResponse, LocationQueryParams, TaskBranchName, TeamTaskMetadata,};/// Repository for accessing document data from the database.@@ -179,6 +179,12 @@ pub trait DocumentRepo: Send + Sync + 'static {user_id: &str,) -> impl Future<Output = Result<BranchNameContext, Self::Err>> + Send;+ /// Get stored GitHub PR keys associated with a task short id.+ fn get_task_github_pull_request_keys(+ &self,+ task_short_id: &str,+ ) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;+/// Share a document with the given team.fn share_with_team(&self,@@ -357,6 +363,13 @@ pub trait DocumentService: Send + Sync + 'static {document_name: String,) -> impl Future<Output = Result<TaskBranchName, DocumentError>> + Send;+ /// Get GitHub pull requests associated with a task document.+ fn get_task_github_pull_requests(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ document_context: &DocumentBasic,+ ) -> impl Future<Output = Result<GithubPullRequestsResponse, DocumentError>> + Send;+/// Edit a document's metadata and share permissions.////// Validates permissions, updates the document, sends invalidation event,diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex e1ebd96d10..2a6fb5057d 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -39,7 +39,8 @@ use super::content::{DocumentContent, DocumentContentLocation, DocumentContentStuse super::models::{CloudFrontConfig, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- FileTypeUpdate, LocationQueryParams, TaskBranchName, TeamTaskMetadata,+ FileTypeUpdate, GithubPullRequestsResponse, LocationQueryParams, TaskBranchName,+ TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -723,6 +724,29 @@ impl<})}+ #[tracing::instrument(err, skip(self, document_context))]+ async fn get_task_github_pull_requests(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ document_context: &DocumentBasic,+ ) -> Result<GithubPullRequestsResponse, DocumentError> {+ if document_context.sub_type != Some(DocumentSubType::Task) {+ return Err(DocumentError::BadRequest(+ "document is not a task".to_string(),+ ));+ }++ let document_id = &entity_access_receipt.entity().entity_id;+ let short_id = short_id_for_entity_id(document_id)?;+ let github_keys = self+ .repo+ .get_task_github_pull_request_keys(&short_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))?;++ Ok(GithubPullRequestsResponse::from_github_keys(github_keys))+ }+#[tracing::instrument(err, skip(self, document_context))]async fn get_document_content(&self,diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rsindex 4dded6aa1b..f2e8b69046 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs@@ -5,6 +5,7 @@//! - `GET /{document_id}` — get document metadata//! - `GET /{document_id}/location_v3` — get document content location (presigned URL)//! - `GET /{document_id}/branch_name` — get short ID + task-aware git branch name (when the document is a task)+//! - `GET /{document_id}/github_prs` — get GitHub pull requests associated with a task document//! - `GET /{document_id}/short_id` — get document short ID//! - `POST /create_markdown` — create and initialize a markdown document//! - `DELETE /{document_id}` — soft-delete a document@@ -21,6 +22,7 @@ pub mod delete_document;pub mod edit_document;pub mod get_branch_name;pub mod get_document;+pub mod get_github_pull_requests;pub mod get_location;pub mod get_short_id;@@ -45,8 +47,8 @@ use self::{copy_document::copy_document_handler, create_document::create_document_handler,create_task::create_task_handler, delete_document::delete_document_handler,edit_document::edit_document_handler, get_branch_name::get_branch_name_handler,- get_document::get_document_handler, get_location::get_location_v3_handler,- get_short_id::get_short_id_handler,+ get_document::get_document_handler, get_github_pull_requests::get_github_pull_requests_handler,+ get_location::get_location_v3_handler, get_short_id::get_short_id_handler,};use crate::domain::models::DocumentError;@@ -149,6 +151,10 @@ where"/{document_id}/branch_name",axum::routing::get(get_branch_name_handler::<T, Svc>),)+ .route(+ "/{document_id}/github_prs",+ axum::routing::get(get_github_pull_requests_handler::<T, Svc>),+ ).route("/{document_id}/short_id",axum::routing::get(get_short_id_handler::<T, Svc>),diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rsnew file mode 100644index 0000000000..4ea6bc9e5f--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs@@ -0,0 +1,81 @@+//! Handler for `GET /documents/{document_id}/github_prs`.++use axum::{+ Extension, Json,+ extract::{Path, State},+};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::DocumentAccessExtractor;+use model::document::DocumentBasic;+use models_permissions::share_permission::access_level::ViewAccessLevel;++use super::{DocumentRouterState, Params};+use crate::domain::models::{DocumentError, GithubPullRequestsResponse};+use crate::domain::ports::DocumentService;++/// Handler for `GET /documents/{document_id}/github_prs`.+///+/// Returns GitHub pull requests associated with a task document.+/// Returns 400 if the document is not a task.+#[utoipa::path(+ tag = "document",+ get,+ path = "/documents/{document_id}/github_prs",+ operation_id = "get_document_github_pull_requests",+ params(+ ("document_id" = String, Path, description = "Document ID")+ ),+ responses(+ (status = 200, body = GithubPullRequestsResponse),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 404, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, access, document_context), err)]+pub async fn get_github_pull_requests_handler<T: DocumentService, Svc: EntityAccessService>(+ access: DocumentAccessExtractor<ViewAccessLevel, Svc>,+ State(state): State<DocumentRouterState<T, Svc>>,+ Extension(document_context): Extension<DocumentBasic>,+ Path(Params { document_id }): Path<Params>,+) -> Result<Json<GithubPullRequestsResponse>, DocumentError> {+ let response = state+ .service+ .get_task_github_pull_requests(access.entity_access_receipt, &document_context)+ .await?;++ Ok(Json(response))+}++#[cfg(test)]+mod tests {+ use serde_json::Value;+ use utoipa::OpenApi;++ #[derive(OpenApi)]+ #[openapi(+ paths(super::get_github_pull_requests_handler),+ components(schemas(+ crate::domain::models::GithubPullRequest,+ crate::domain::models::GithubPullRequestsResponse,+ ))+ )]+ struct ApiDoc;++ #[test]+ fn get_github_pull_requests_openapi_documents_expected_responses() {+ let openapi = serde_json::to_value(ApiDoc::openapi()).expect("OpenAPI should serialize");+ let responses = openapi+ .pointer("/paths/~1documents~1{document_id}~1github_prs/get/responses")+ .and_then(Value::as_object)+ .expect("GitHub PR endpoint should be documented");++ for status in ["200", "400", "401", "404", "500"] {+ assert!(+ responses.contains_key(status),+ "expected {status} response to be documented"+ );+ }+ }+}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rsindex aba76ceb21..504de7771c 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs@@ -743,6 +743,24 @@ impl DocumentRepo for PgDocumentRepo {})}+ #[tracing::instrument(err, skip(self))]+ async fn get_task_github_pull_request_keys(+ &self,+ task_short_id: &str,+ ) -> Result<Vec<String>, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT github_key+ FROM github_pr_tasks+ WHERE task_id = $1+ ORDER BY created_at ASC, github_key ASC+ "#,+ task_short_id,+ )+ .fetch_all(&self.pool)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn share_with_team(&self,diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rsindex 4ffd1cec8f..8f05e12491 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs@@ -10,6 +10,7 @@ use sqlx::{Pool, Postgres, Row};use crate::domain::models::{CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs, FileTypeUpdate,+ GithubPullRequest, GithubPullRequestsResponse,};use crate::domain::ports::DocumentRepo;use crate::outbound::pg_document_repo::PgDocumentRepo;@@ -71,6 +72,32 @@ async fn team_task_numbers(pool: &Pool<Postgres>, team_id: uuid::Uuid) -> Vec<i3.collect()}+fn short_id_for_document_id(document_id: &str) -> String {+ let uuid = macro_uuid::string_to_uuid(document_id).unwrap();+ macro_uuid::ShortUuidConverter::default().from_uuid(&uuid)+}++async fn insert_github_pr_task(+ pool: &Pool<Postgres>,+ github_key: &str,+ task_short_id: &str,+ created_at: chrono::DateTime<chrono::Utc>,+) {+ sqlx::query(+ r#"+ INSERT INTO github_pr_tasks (id, github_key, task_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $4)+ "#,+ )+ .bind(uuid::Uuid::new_v4())+ .bind(github_key)+ .bind(task_short_id)+ .bind(created_at)+ .execute(pool)+ .await+ .unwrap();+}+async fn insert_second_team(pool: &Pool<Postgres>) {sqlx::query(r#"@@ -913,6 +940,90 @@ async fn test_get_branch_name_context_falls_back_for_unknown_user(pool: Pool<Posassert_eq!(context.team_task_id, None);}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ let other_task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ let task_short_id = short_id_for_document_id(&task.document_id);+ let other_task_short_id = short_id_for_document_id(&other_task.document_id);+ let created_at = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")+ .unwrap()+ .with_timezone(&chrono::Utc);++ insert_github_pr_task(&pool, "not-a-github-pr-key", &task_short_id, created_at).await;+ insert_github_pr_task(+ &pool,+ "macro/macro/pull/10",+ &task_short_id,+ created_at + chrono::Duration::seconds(1),+ )+ .await;+ insert_github_pr_task(+ &pool,+ "macro/api/pull/5",+ &task_short_id,+ created_at + chrono::Duration::seconds(1),+ )+ .await;+ insert_github_pr_task(+ &pool,+ "macro/macro/pull/20",+ &task_short_id,+ created_at + chrono::Duration::seconds(2),+ )+ .await;+ insert_github_pr_task(&pool, "other/repo/pull/1", &other_task_short_id, created_at).await;++ let github_keys = repo+ .get_task_github_pull_request_keys(&task_short_id)+ .await+ .unwrap();+ assert_eq!(+ github_keys,+ vec![+ "not-a-github-pr-key".to_string(),+ "macro/api/pull/5".to_string(),+ "macro/macro/pull/10".to_string(),+ "macro/macro/pull/20".to_string(),+ ]+ );++ let response = GithubPullRequestsResponse::from_github_keys(github_keys);+ assert_eq!(+ response.pull_requests,+ vec![+ GithubPullRequest {+ github_key: "macro/api/pull/5".to_string(),+ owner: "macro".to_string(),+ repo: "api".to_string(),+ number: 5,+ url: "https://github.com/macro/api/pull/5".to_string(),+ display_name: "macro/api#5".to_string(),+ },+ GithubPullRequest {+ github_key: "macro/macro/pull/10".to_string(),+ owner: "macro".to_string(),+ repo: "macro".to_string(),+ number: 10,+ url: "https://github.com/macro/macro/pull/10".to_string(),+ display_name: "macro/macro#10".to_string(),+ },+ GithubPullRequest {+ github_key: "macro/macro/pull/20".to_string(),+ owner: "macro".to_string(),+ repo: "macro".to_string(),+ number: 20,+ url: "https://github.com/macro/macro/pull/20".to_string(),+ display_name: "macro/macro#20".to_string(),+ },+ ]+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 894b97316f..d72e8d4a2b 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -127,6 +127,13 @@ impl DocumentService for StubDocumentService {) -> Result<documents::domain::models::TaskBranchName, DocumentError> {unimplemented!()}+ async fn get_task_github_pull_requests(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _document_context: &DocumentBasic,+ ) -> Result<documents::domain::models::GithubPullRequestsResponse, DocumentError> {+ unimplemented!()+ }async fn get_project_children(&self,_project_id: &str,