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(github): use foreign entities for task github pr (#3873)
Will Hutchinson778d99de0bcf
diff --git a/js/app/packages/queries/storage/github-pull-requests.test.ts b/js/app/packages/queries/storage/github-pull-requests.test.tsindex 818fd50340..4900c2e79f 100644--- a/js/app/packages/queries/storage/github-pull-requests.test.ts+++ b/js/app/packages/queries/storage/github-pull-requests.test.ts@@ -34,10 +34,47 @@ const rawPullRequest: GithubPullRequest = {const rawResponse = { pullRequests: [rawPullRequest] };+const storageMetadataPullRequest: GithubPullRequest = {+ ...rawPullRequest,+ additions: 12,+ checks: [+ {+ conclusion: 'success',+ id: 1001,+ name: 'build',+ status: 'completed',+ },+ ],+ comments: [+ {+ body: 'Stored review comment',+ id: 2001,+ source: 'review_comment',+ },+ ],+ deletions: 3,+ foreignEntityId: 'foreign-entity-1',+ name: 'Stored GitHub metadata',+ status: 'open',+};+function createError(code: string): ResultError<string> {return { code, message: code };}+function createShallowAuthPullRequest(+ pullRequest: GithubPullRequest+): EnrichedGithubPullRequest {+ return {+ displayName: pullRequest.displayName,+ githubKey: pullRequest.githubKey,+ number: pullRequest.number,+ owner: pullRequest.owner,+ repo: pullRequest.repo,+ url: pullRequest.url,+ };+}+beforeEach(() => {mocks.enrichGithubPullRequests.mockReset();mocks.getDocumentGithubPullRequests.mockReset();@@ -94,4 +131,62 @@ describe('fetchDocumentGithubPullRequests', () => {expect(response).toEqual({ pullRequests: [enrichedPullRequest] });});++ it('preserves storage metadata when auth enrichment succeeds with a shallow PR', async () => {+ const shallowAuthPullRequest = createShallowAuthPullRequest(rawPullRequest);+ mocks.getDocumentGithubPullRequests.mockResolvedValue(+ resultOk({ pullRequests: [storageMetadataPullRequest] })+ );+ mocks.enrichGithubPullRequests.mockResolvedValue(+ resultOk({ pullRequests: [shallowAuthPullRequest] })+ );++ const response = await fetchDocumentGithubPullRequests('document-1');++ expect(response).toEqual({+ pullRequests: [storageMetadataPullRequest],+ });+ });++ it('uses auth enrichment metadata when present while preserving the foreign entity id', async () => {+ const enrichedPullRequest: EnrichedGithubPullRequest = {+ ...rawPullRequest,+ additions: 20,+ checks: [+ {+ conclusion: 'failure',+ id: 1002,+ name: 'build',+ status: 'completed',+ },+ ],+ comments: [+ {+ body: 'Fresh review comment',+ id: 2002,+ source: 'review_comment',+ },+ ],+ deletions: 5,+ name: 'Fresh GitHub metadata',+ status: 'closed',+ };+ mocks.getDocumentGithubPullRequests.mockResolvedValue(+ resultOk({ pullRequests: [storageMetadataPullRequest] })+ );+ mocks.enrichGithubPullRequests.mockResolvedValue(+ resultOk({ pullRequests: [enrichedPullRequest] })+ );++ const response = await fetchDocumentGithubPullRequests('document-1');++ expect(response).toEqual({+ pullRequests: [+ {+ ...enrichedPullRequest,+ foreignEntityId: storageMetadataPullRequest.foreignEntityId,+ },+ ],+ });+ });});diff --git a/js/app/packages/queries/storage/github-pull-requests.ts b/js/app/packages/queries/storage/github-pull-requests.tsindex 547b9f2afb..3f1a00418d 100644--- a/js/app/packages/queries/storage/github-pull-requests.ts+++ b/js/app/packages/queries/storage/github-pull-requests.ts@@ -46,24 +46,34 @@ function toGithubPullRequestRef(}function toStorageGithubPullRequest(- pullRequest: EnrichedGithubPullRequest+ pullRequest: EnrichedGithubPullRequest,+ fallbackPullRequest: GithubPullRequest | undefined): GithubPullRequest {return {- additions: pullRequest.additions,- checks: pullRequest.checks,- comments: pullRequest.comments,- deletions: pullRequest.deletions,+ additions: pullRequest.additions ?? fallbackPullRequest?.additions,+ checks: pullRequest.checks ?? fallbackPullRequest?.checks,+ comments: pullRequest.comments ?? fallbackPullRequest?.comments,+ deletions: pullRequest.deletions ?? fallbackPullRequest?.deletions,displayName: pullRequest.displayName,+ foreignEntityId: fallbackPullRequest?.foreignEntityId,githubKey: pullRequest.githubKey,- name: pullRequest.name,+ name: pullRequest.name ?? fallbackPullRequest?.name,number: pullRequest.number,owner: pullRequest.owner,repo: pullRequest.repo,- status: pullRequest.status,+ status: pullRequest.status ?? fallbackPullRequest?.status,url: pullRequest.url,};}+function createPullRequestFallbacksByKey(+ pullRequests: GithubPullRequest[]+): Map<string, GithubPullRequest> {+ return new Map(+ pullRequests.map((pullRequest) => [pullRequest.githubKey, pullRequest])+ );+}+export async function fetchDocumentGithubPullRequests(documentId: string): Promise<GithubPullRequestsResponse> {@@ -83,9 +93,18 @@ export async function fetchDocumentGithubPullRequests(return rawResponse;}+ const fallbackPullRequestsByKey = createPullRequestFallbacksByKey(+ rawResponse.pullRequests+ );+return {pullRequests: enrichedResponse.value.pullRequests.map(- toStorageGithubPullRequest+ (pullRequest, index) =>+ toStorageGithubPullRequest(+ pullRequest,+ fallbackPullRequestsByKey.get(pullRequest.githubKey) ??+ rawResponse.pullRequests[index]+ )),};}diff --git a/js/bun.lock b/js/bun.lockindex c1b5aff31b..772e2c16ae 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -830,7 +830,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2550,7 +2550,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex 1527c0e9bb..bc40ce8b62 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -41,8 +41,8 @@ use super::content::{DocumentContent, DocumentContentLocation, DocumentContentStuse super::models::{CloudFrontConfig, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- FileTypeUpdate, GithubPullRequestsResponse, LocationQueryParams, TaskBranchName,- TeamTaskMetadata,+ FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse, LocationQueryParams,+ TaskBranchName, TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -131,21 +131,52 @@ fn foreign_entity_matches_source_id(foreign_entity: &ForeignEntity, source_id: &&& foreign_entity.stored_for_auth_entity == source_id.auth_entity}-fn first_visible_foreign_entity_id(- foreign_entities: &[ForeignEntity],+fn first_visible_foreign_entity<'a>(+ foreign_entities: &'a [ForeignEntity],source_ids: Option<&[SourceId]>,-) -> Option<uuid::Uuid> {- foreign_entities- .iter()- .find(|foreign_entity| {- foreign_entity.foreign_entity_source == GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE- && source_ids.is_none_or(|source_ids| {- source_ids.iter().any(|source_id| {- foreign_entity_matches_source_id(foreign_entity, source_id)- })- })- })- .map(|foreign_entity| foreign_entity.id)+) -> Option<&'a ForeignEntity> {+ foreign_entities.iter().find(|foreign_entity| {+ foreign_entity.foreign_entity_source == GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE+ && source_ids.is_none_or(|source_ids| {+ source_ids+ .iter()+ .any(|source_id| foreign_entity_matches_source_id(foreign_entity, source_id))+ })+ })+}++fn hydrate_github_pull_request_from_foreign_entity(+ pull_request: &mut GithubPullRequest,+ foreign_entity: &ForeignEntity,+) {+ let Ok(mut hydrated_pull_request) = serde_json::from_value::<GithubPullRequest>(+ foreign_entity.metadata.clone(),+ )+ .inspect_err(|error| {+ tracing::warn!(+ error = ?error,+ foreign_entity_id = %foreign_entity.id,+ fallback_github_key = %pull_request.github_key,+ "failed to parse GitHub pull request foreign entity metadata"+ );+ }) else {+ pull_request.foreign_entity_id = Some(foreign_entity.id);+ return;+ };++ if hydrated_pull_request.github_key != pull_request.github_key {+ tracing::warn!(+ foreign_entity_id = %foreign_entity.id,+ metadata_github_key = %hydrated_pull_request.github_key,+ fallback_github_key = %pull_request.github_key,+ "ignoring mismatched GitHub pull request foreign entity metadata"+ );+ pull_request.foreign_entity_id = Some(foreign_entity.id);+ return;+ }++ hydrated_pull_request.foreign_entity_id = Some(foreign_entity.id);+ *pull_request = hydrated_pull_request;}impl<@@ -817,8 +848,11 @@ impl<.await.map_err(|error| DocumentError::Internal(error.into()))?;- pull_request.foreign_entity_id =- first_visible_foreign_entity_id(&foreign_entities, source_ids.as_deref());+ if let Some(foreign_entity) =+ first_visible_foreign_entity(&foreign_entities, source_ids.as_deref())+ {+ hydrate_github_pull_request_from_foreign_entity(pull_request, foreign_entity);+ }}Ok(response)diff --git a/rust/cloud-storage/documents/src/domain/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rsindex 53d9c019f9..06df40f49f 100644--- a/rust/cloud-storage/documents/src/domain/service/tests.rs+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs@@ -347,6 +347,25 @@ fn make_foreign_entity(}}+fn make_foreign_entity_with_metadata(+ id: uuid::Uuid,+ foreign_entity_id: &str,+ foreign_entity_source: &str,+ stored_for_id: &str,+ stored_for_auth_entity: &str,+ metadata: serde_json::Value,+) -> ForeignEntity {+ let mut foreign_entity = make_foreign_entity(+ id,+ foreign_entity_id,+ foreign_entity_source,+ stored_for_id,+ stored_for_auth_entity,+ );+ foreign_entity.metadata = metadata;+ foreign_entity+}+fn expect_authenticated_team_lookup(repo: &mut MockDocumentRepo, team_ids: Vec<uuid::Uuid>) {repo.expect_get_team_ids_for_user().withf(|user_id| user_id == "macro|[email protected]")@@ -374,6 +393,23 @@ fn assert_pull_request_ref();}+fn assert_no_enriched_pull_request_metadata(pull_request: &GithubPullRequest) {+ assert!(pull_request.name.is_none());+ assert!(pull_request.status.is_none());+ assert!(pull_request.additions.is_none());+ assert!(pull_request.deletions.is_none());+ assert!(pull_request.comments.is_none());+ assert!(pull_request.checks.is_none());++ let pull_request_json = serde_json::to_value(pull_request).unwrap();+ assert!(pull_request_json.get("name").is_none());+ assert!(pull_request_json.get("status").is_none());+ assert!(pull_request_json.get("additions").is_none());+ assert!(pull_request_json.get("deletions").is_none());+ assert!(pull_request_json.get("comments").is_none());+ assert!(pull_request_json.get("checks").is_none());+}+fn assert_raw_pull_request(pull_request: &GithubPullRequest,github_key: &str,@@ -383,17 +419,30 @@ fn assert_raw_pull_request() {assert_pull_request_ref(pull_request, github_key, owner, repo, number);assert!(pull_request.foreign_entity_id.is_none());- assert!(pull_request.name.is_none());- assert!(pull_request.status.is_none());- assert!(pull_request.additions.is_none());- assert!(pull_request.deletions.is_none());- assert!(pull_request.comments.is_none());- assert!(pull_request.checks.is_none());+ assert_no_enriched_pull_request_metadata(pull_request);let pull_request_json = serde_json::to_value(pull_request).unwrap();assert!(pull_request_json.get("foreignEntityId").is_none());- assert!(pull_request_json.get("comments").is_none());- assert!(pull_request_json.get("checks").is_none());+}++fn assert_shallow_pull_request_with_foreign_entity_id(+ pull_request: &GithubPullRequest,+ github_key: &str,+ owner: &str,+ repo: &str,+ number: u64,+ foreign_entity_id: uuid::Uuid,+) {+ assert_pull_request_ref(pull_request, github_key, owner, repo, number);+ assert_eq!(pull_request.foreign_entity_id, Some(foreign_entity_id));+ assert_no_enriched_pull_request_metadata(pull_request);++ let pull_request_json = serde_json::to_value(pull_request).unwrap();+ let expected_foreign_entity_id = serde_json::json!(foreign_entity_id.to_string());+ assert_eq!(+ pull_request_json.get("foreignEntityId"),+ Some(&expected_foreign_entity_id)+ );}#[tokio::test]@@ -536,6 +585,173 @@ async fn test_get_task_github_pull_requests_adds_user_foreign_entity_id() {);}+#[tokio::test]+async fn test_get_task_github_pull_requests_hydrates_visible_foreign_entity_metadata() {+ let document_id = "00000000-0000-0000-0000-000000000008";+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();+ let foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000501");+ let mut repo = make_mock_repo();++ repo.expect_get_task_github_pull_request_keys()+ .withf(move |task_short_id| task_short_id == expected_short_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(vec![+ "macro/repo/pull/14".to_string(),+ ])))+ });+ expect_authenticated_team_lookup(&mut repo, Vec::new());++ let metadata = serde_json::json!({+ "githubKey": "macro/repo/pull/14",+ "owner": "macro",+ "repo": "repo",+ "number": 14,+ "url": "https://github.com/macro/repo/pull/14",+ "displayName": "macro/repo#14",+ "name": "Hydrate GitHub pull request metadata",+ "status": "open",+ "additions": 120,+ "deletions": 34,+ "comments": [+ {+ "id": 9001,+ "body": "Looks ready to merge.",+ "authorLogin": "alice",+ "authorAssociation": "MEMBER",+ "url": "https://github.com/macro/repo/pull/14#issuecomment-9001",+ "createdAt": "2026-06-09T12:00:00Z",+ "updatedAt": "2026-06-09T12:05:00Z",+ "source": "issue_comment"+ }+ ],+ "checks": [+ {+ "id": 7001,+ "name": "ci/test",+ "status": "completed",+ "conclusion": "success",+ "url": "https://github.com/macro/repo/actions/runs/7001",+ "startedAt": "2026-06-09T11:00:00Z",+ "completedAt": "2026-06-09T11:03:00Z"+ }+ ]+ });++ let service = make_test_service_with_foreign_entities(+ repo,+ vec![make_foreign_entity_with_metadata(+ foreign_entity_id,+ "macro/repo/pull/14",+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,+ "macro|[email protected]",+ "user",+ metadata.clone(),+ )],+ );++ let response = service+ .get_task_github_pull_requests(+ authenticated_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(response.pull_requests.len(), 1);+ let mut expected_pull_request = metadata;+ expected_pull_request.as_object_mut().unwrap().insert(+ "foreignEntityId".to_string(),+ serde_json::json!(foreign_entity_id.to_string()),+ );+ assert_eq!(+ serde_json::to_value(&response.pull_requests[0]).unwrap(),+ expected_pull_request+ );+}++#[tokio::test]+async fn test_get_task_github_pull_requests_falls_back_when_foreign_entity_metadata_is_malformed() {+ let document_id = "00000000-0000-0000-0000-000000000009";+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();+ let malformed_foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000601");+ let mismatched_foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000602");+ let mut repo = make_mock_repo();++ repo.expect_get_task_github_pull_request_keys()+ .withf(move |task_short_id| task_short_id == expected_short_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(vec![+ "macro/repo/pull/15".to_string(),+ "macro/repo/pull/16".to_string(),+ ])))+ });+ expect_authenticated_team_lookup(&mut repo, Vec::new());++ let service = make_test_service_with_foreign_entities(+ repo,+ vec![+ make_foreign_entity_with_metadata(+ malformed_foreign_entity_id,+ "macro/repo/pull/15",+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,+ "macro|[email protected]",+ "user",+ serde_json::json!({+ "githubKey": "macro/repo/pull/15",+ "owner": "macro"+ }),+ ),+ make_foreign_entity_with_metadata(+ mismatched_foreign_entity_id,+ "macro/repo/pull/16",+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,+ "macro|[email protected]",+ "user",+ serde_json::json!({+ "githubKey": "macro/repo/pull/999",+ "owner": "macro",+ "repo": "repo",+ "number": 999,+ "url": "https://github.com/macro/repo/pull/999",+ "displayName": "macro/repo#999",+ "name": "Wrong pull request metadata",+ "status": "merged",+ "additions": 999,+ "deletions": 999,+ "comments": [],+ "checks": []+ }),+ ),+ ],+ );++ let response = service+ .get_task_github_pull_requests(+ authenticated_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(response.pull_requests.len(), 2);+ assert_shallow_pull_request_with_foreign_entity_id(+ &response.pull_requests[0],+ "macro/repo/pull/15",+ "macro",+ "repo",+ 15,+ malformed_foreign_entity_id,+ );+ assert_shallow_pull_request_with_foreign_entity_id(+ &response.pull_requests[1],+ "macro/repo/pull/16",+ "macro",+ "repo",+ 16,+ mismatched_foreign_entity_id,+ );+}+#[tokio::test]async fn test_get_task_github_pull_requests_adds_team_foreign_entity_id() {let document_id = "00000000-0000-0000-0000-000000000003";@@ -655,12 +871,47 @@ async fn test_get_task_github_pull_requests_ignores_unrelated_stored_source() {let service = make_test_service_with_foreign_entities(repo,- vec![make_foreign_entity(+ vec![make_foreign_entity_with_metadata(unrelated_foreign_entity_id,"macro/repo/pull/11",GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,"macro|[email protected]","user",+ serde_json::json!({+ "githubKey": "macro/repo/pull/11",+ "owner": "macro",+ "repo": "repo",+ "number": 11,+ "url": "https://github.com/macro/repo/pull/11",+ "displayName": "macro/repo#11",+ "name": "Invisible pull request metadata",+ "status": "open",+ "additions": 55,+ "deletions": 13,+ "comments": [+ {+ "id": 3001,+ "body": "This comment should not be visible.",+ "authorLogin": "mallory",+ "authorAssociation": "CONTRIBUTOR",+ "url": "https://github.com/macro/repo/pull/11#issuecomment-3001",+ "createdAt": "2026-06-09T10:00:00Z",+ "updatedAt": "2026-06-09T10:01:00Z",+ "source": "issue_comment"+ }+ ],+ "checks": [+ {+ "id": 3002,+ "name": "ci/private",+ "status": "completed",+ "conclusion": "failure",+ "url": "https://github.com/macro/repo/actions/runs/3002",+ "startedAt": "2026-06-09T09:00:00Z",+ "completedAt": "2026-06-09T09:04:00Z"+ }+ ]+ }),)],);