@openchamber/web 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/dist/assets/{AboutDialog-MZbHWRua.js → AboutDialog-Ctk2zvrv.js} +1 -1
  2. package/dist/assets/{ArchiveView-CkeSWPcI.js → ArchiveView-sbNreasJ.js} +1 -1
  3. package/dist/assets/{CommandPalette-CtKzNzwW.js → CommandPalette-BICwnwAZ.js} +2 -2
  4. package/dist/assets/{DiffView-DaXjHTAq.js → DiffView-B5yeuxv8.js} +1 -1
  5. package/dist/assets/{FilesView-DMNYEydF.js → FilesView-ni2zfAwL.js} +7 -7
  6. package/dist/assets/{GitView-HXttTpUw.js → GitView-C0QgeC9O.js} +3 -3
  7. package/dist/assets/{GuestSurfacePane-KzguENQG.js → GuestSurfacePane-D1gLktSj.js} +1 -1
  8. package/dist/assets/{HelpDialog-9YZGhBgT.js → HelpDialog-CxC6qTaS.js} +1 -1
  9. package/dist/assets/{InProgressOperationBanner-DzGIwGH2.js → InProgressOperationBanner-JFV70YFh.js} +1 -1
  10. package/dist/assets/{JsonTreeView-D9rP8jM8.js → JsonTreeView-RsbV4Usa.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-CZK5DoOX.js +1 -0
  12. package/dist/assets/{MemoryDebugPanel-Ct0h3RWh.js → MemoryDebugPanel-caUWOKiz.js} +1 -1
  13. package/dist/assets/{OnboardingScreen-B5Zzb1Mp.js → OnboardingScreen-BDT-J2JP.js} +1 -1
  14. package/dist/assets/{OpenCodeStatusDialog-CXBWWRh8.js → OpenCodeStatusDialog-Cxa2yqOB.js} +1 -1
  15. package/dist/assets/{PatchDiff-DhDAQ5em.js → PatchDiff-C1pnbAsJ.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-DPa08AmN.js → PierreDiffViewer-D0zX2Msu.js} +1 -1
  17. package/dist/assets/PlanView-BxRCMuGe.js +5 -0
  18. package/dist/assets/{ProjectActionsDialog-DATu0aBc.js → ProjectActionsDialog-D660By4K.js} +1 -1
  19. package/dist/assets/{RunOverview-D6xy_vME.js → RunOverview-C1uTMnQS.js} +2 -2
  20. package/dist/assets/{ScheduledTasksDialog-BWXVnfrf.js → ScheduledTasksDialog-S-gAgo7Z.js} +5 -5
  21. package/dist/assets/SettingsView-CVpfbdob.js +30 -0
  22. package/dist/assets/{SettingsWindow-Cx6TrtY0.js → SettingsWindow-Dd1hHvgh.js} +1 -1
  23. package/dist/assets/SourceBoardView-DbGWAxtS.js +1 -0
  24. package/dist/assets/SpaceAccessDialog-muTSsEJ9.js +1 -0
  25. package/dist/assets/{SpaceApplyDialog-BtuwtlaG.js → SpaceApplyDialog-Dsf6MNGm.js} +1 -1
  26. package/dist/assets/{SpaceRow-MXqvd-dr.js → SpaceRow-7Z6ebRtm.js} +1 -1
  27. package/dist/assets/{SpaceSetupOutput-Uo5LS7Jy.js → SpaceSetupOutput-BytPfCOC.js} +1 -1
  28. package/dist/assets/{SpacesView-DvoOh4sM.js → SpacesView-CYCrlp0D.js} +1 -1
  29. package/dist/assets/{SubmoduleDiffSummary-CyMwDeoP.js → SubmoduleDiffSummary-VrNUbIqF.js} +1 -1
  30. package/dist/assets/{ToolOutputDialog-BaUZIVzc.js → ToolOutputDialog-DHORjBND.js} +7 -7
  31. package/dist/assets/{ToolPartDiffPreview-DmMwdcF4.js → ToolPartDiffPreview-BLAXe7C5.js} +1 -1
  32. package/dist/assets/{UsageStatsView-D7WrDBTC.js → UsageStatsView-BxtYEAa0.js} +1 -1
  33. package/dist/assets/{Virtualizer-CnU8pYMb.js → Virtualizer-Bl4Cf-H-.js} +1 -1
  34. package/dist/assets/{WalkthroughView-r0Ho9F4Z.js → WalkthroughView-B2BJJ4u5.js} +2 -2
  35. package/dist/assets/{WorktreesView-C-t7uxq1.js → WorktreesView-Dv0AO9dF.js} +1 -1
  36. package/dist/assets/{appThemeRegistry-BUY7Ge9i.js → appThemeRegistry-xm_W0svA.js} +1 -1
  37. package/dist/assets/{ar-HauNhDvN.js → ar-Cj8UF12m.js} +4 -4
  38. package/dist/assets/{computeVirtualFileMetrics-CUof18z3.js → computeVirtualFileMetrics-Cx05cmWI.js} +2 -2
  39. package/dist/assets/{de-fEoJ_Yyp.js → de-fSQ1ho01.js} +4 -4
  40. package/dist/assets/{decorate-BkTSGAlD.js → decorate-jpF7GA6t.js} +2 -2
  41. package/dist/assets/{es-CKNTBsZW.js → es-DrdzhSlK.js} +5 -5
  42. package/dist/assets/{fileContentPoller-BJWgy1fX.js → fileContentPoller-C0f20jNG.js} +3 -3
  43. package/dist/assets/{flexokiTheme-BArobfXV.js → flexokiTheme-DKNCYSqL.js} +1 -1
  44. package/dist/assets/{fr-C23655Pi.js → fr-Cmz6Da4q.js} +4 -4
  45. package/dist/assets/{he-CphXS_Fv.js → he-COJRUNy4.js} +4 -4
  46. package/dist/assets/{index-B27cSA9V.js → index-C8Mw8uvl.js} +1 -1
  47. package/dist/assets/{initializeSharedPreferences-CucsmDMw.js → initializeSharedPreferences-U9-v9mfq.js} +1 -1
  48. package/dist/assets/{isDiffPlainText-DSCjvV0m.js → isDiffPlainText-DW43IghW.js} +1 -1
  49. package/dist/assets/{isFilePlainText-C7g4UPox.js → isFilePlainText-Duq5CiuG.js} +1 -1
  50. package/dist/assets/{ja-BmsU2iQe.js → ja-Ce0NvDHZ.js} +4 -4
  51. package/dist/assets/katex-BZNCT55U.css +1 -0
  52. package/dist/assets/katex.min-EZjpSwGK.js +65 -0
  53. package/dist/assets/{ko-CxISpkje.js → ko-BGFcCLLq.js} +4 -4
  54. package/dist/assets/main-BUetg9hg.js +1048 -0
  55. package/dist/assets/{main-CGPiw9fS.js → main-Be_jmIlF.js} +2 -2
  56. package/dist/assets/markdownCore-BkTeS4gA.js +10 -0
  57. package/dist/assets/{miniChat-DVEKVYKe.js → miniChat-g1RgiLLS.js} +2 -2
  58. package/dist/assets/{mobile-Q_FVBe4I.js → mobile-DBli3U-T.js} +2 -2
  59. package/dist/assets/{moveWorkspacePath-CyZJ-2aD.js → moveWorkspacePath-CnYc96Xo.js} +1 -1
  60. package/dist/assets/{nl-jnTBQ_gU.js → nl-Cu1nxo5t.js} +4 -4
  61. package/dist/assets/{parseDiffFromFile-OHXXXyzL.js → parseDiffFromFile-DEjkjYod.js} +3 -3
  62. package/dist/assets/{patchFileDiff-BZrb6h2u.js → patchFileDiff-D__42sau.js} +5 -5
  63. package/dist/assets/{pierreDiffTint-DHf2xvyt.js → pierreDiffTint-3oatL635.js} +4 -4
  64. package/dist/assets/pl-4LdEMgWI.js +20 -0
  65. package/dist/assets/{pt-BR-BfpsFrHv.js → pt-BR-2UbEBNgC.js} +5 -5
  66. package/dist/assets/{relocateRestoredSession-DInneXVI.js → relocateRestoredSession-pkxyd_lV.js} +1 -1
  67. package/dist/assets/renderElectronMiniChatApp-D0tKJFBB.js +2 -0
  68. package/dist/assets/renderMobileApp-D6bOYHuP.js +25 -0
  69. package/dist/assets/{restartOpenCode-DwBaMPJK.js → restartOpenCode-FYqjpaWc.js} +1 -1
  70. package/dist/assets/runtimeEndpointReset-6CNNzem4.js +74 -0
  71. package/dist/assets/{scheduledTasksApi-ClJplEhR.js → scheduledTasksApi-BbnQ4W-W.js} +1 -1
  72. package/dist/assets/{selectionMarkdown-BuveYuup.js → selectionMarkdown-D8QAxC44.js} +1 -1
  73. package/dist/assets/sessionOwnership-BBuf0UCB.js +1 -0
  74. package/dist/assets/{shikiHighlight-DJAESrna.js → shikiHighlight-CweIj1cL.js} +1 -1
  75. package/dist/assets/{space-apply-DWFLwXbI.js → space-apply-CEi013sa.js} +1 -1
  76. package/dist/assets/{space-close-BYDbwdWc.js → space-close-BuStkLrZ.js} +1 -1
  77. package/dist/assets/{spaceNetwork-DHrhfbKM.js → spaceNetwork-tH2d5Mgs.js} +1 -1
  78. package/dist/assets/{textMateThemeFromAppTheme-DcAZmUlv.js → textMateThemeFromAppTheme-DLJBL6al.js} +1 -1
  79. package/dist/assets/tr-Bg0Qt-mG.js +11 -0
  80. package/dist/assets/{uk-C82aEtvs.js → uk-vcnOugr0.js} +5 -5
  81. package/dist/assets/useAppFontEffects-Cs6k0JKv.js +773 -0
  82. package/dist/assets/{useCallableModelProviders-BU_455MN.js → useCallableModelProviders-BsGEzsl2.js} +1 -1
  83. package/dist/assets/{useInlineCommentController-AuUrVz9U.js → useInlineCommentController-CVYaPzfO.js} +2 -2
  84. package/dist/assets/{useRootScrollLock-Cpk7NmBa.js → useRootScrollLock-Dov-44ov.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-language-data-BYGweLoh.js → vendor-codemirror-language-data-DBekkZIx.js} +2 -2
  86. package/dist/assets/vendor-tanstack-react-virtual-Dozz-7fb.js +1 -0
  87. package/dist/assets/vendor-tanstack-virtual-core-DKBj55Em.js +1 -0
  88. package/dist/assets/{vendor-yaml-3778uTud.js → vendor-yaml-CE-D_49-.js} +1 -1
  89. package/dist/assets/{zh-CN-DEq7j9I5.js → zh-CN-C3UhwFsk.js} +5 -5
  90. package/dist/assets/{zh-TW-DgCN99T-.js → zh-TW-D0CmmMvp.js} +5 -5
  91. package/dist/index.html +3 -3
  92. package/dist/mini-chat.html +3 -3
  93. package/dist/mobile.html +3 -3
  94. package/package.json +5 -5
  95. package/server/index.js +13 -1
  96. package/server/lib/agent-memory/actions.js +22 -9
  97. package/server/lib/agent-memory/actions.test.js +57 -0
  98. package/server/lib/agent-memory/runtime.js +8 -5
  99. package/server/lib/agent-tool/DOCUMENTATION.md +17 -1
  100. package/server/lib/agent-tool/runtime.js +41 -7
  101. package/server/lib/agent-tool/runtime.test.js +11 -0
  102. package/server/lib/git/DOCUMENTATION.md +17 -5
  103. package/server/lib/git/lfs-discovery.js +7 -4
  104. package/server/lib/git/lfs-discovery.test.js +60 -0
  105. package/server/lib/git/network-operations.js +9 -3
  106. package/server/lib/git/network-operations.test.js +31 -2
  107. package/server/lib/git/service.js +72 -12
  108. package/server/lib/git/service.test.js +65 -0
  109. package/server/lib/github/DOCUMENTATION.md +1 -0
  110. package/server/lib/github/reference-search.js +49 -18
  111. package/server/lib/github/reference-search.test.js +28 -6
  112. package/server/lib/github/routes.js +87 -1
  113. package/server/lib/github/routes.mutations.test.js +38 -0
  114. package/server/lib/github/routes.test.js +1 -0
  115. package/server/lib/gitlab/DOCUMENTATION.md +4 -0
  116. package/server/lib/gitlab/client.js +23 -0
  117. package/server/lib/gitlab/client.test.js +28 -1
  118. package/server/lib/gitlab/mappers.js +9 -0
  119. package/server/lib/gitlab/resources.js +153 -4
  120. package/server/lib/gitlab/resources.test.js +107 -0
  121. package/server/lib/gitlab/routes.js +120 -1
  122. package/server/lib/gitlab/routes.test.js +59 -0
  123. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  124. package/server/lib/markdown-image-grants/routes.js +14 -2
  125. package/server/lib/markdown-image-grants/routes.test.js +23 -0
  126. package/server/lib/notifications/APNS.md +24 -23
  127. package/server/lib/notifications/DOCUMENTATION.md +2 -2
  128. package/server/lib/notifications/apns-runtime.js +8 -5
  129. package/server/lib/notifications/apns-runtime.test.js +26 -0
  130. package/server/lib/notifications/message.js +5 -3
  131. package/server/lib/notifications/message.test.js +9 -0
  132. package/server/lib/notifications/runtime.js +44 -9
  133. package/server/lib/notifications/trigger-runtime.test.js +84 -0
  134. package/server/lib/openchamber-control/DOCUMENTATION.md +6 -1
  135. package/server/lib/openchamber-control/actions.js +18 -2
  136. package/server/lib/openchamber-control/project-knowledge.js +17 -3
  137. package/server/lib/openchamber-control/project-knowledge.test.js +14 -0
  138. package/server/lib/openchamber-control/render-page.js +58 -0
  139. package/server/lib/openchamber-control/service.js +9 -0
  140. package/server/lib/openchamber-control/service.test.js +43 -0
  141. package/server/lib/openchamber-sessions/routes.js +1 -0
  142. package/server/lib/openchamber-sessions/worktree-move.js +26 -10
  143. package/server/lib/openchamber-sessions/worktree-move.test.js +36 -0
  144. package/server/lib/opencode/DOCUMENTATION.md +1 -1
  145. package/server/lib/opencode/managed-config-file.js +3 -2
  146. package/server/lib/opencode/managed-config-file.test.js +20 -6
  147. package/server/lib/opencode/settings-helpers.js +3 -0
  148. package/server/lib/opencode/settings-helpers.test.js +1 -1
  149. package/server/lib/opencode/settings-registry.json +3 -0
  150. package/server/lib/opencode/settings-runtime.js +1 -0
  151. package/server/lib/project-context/DOCUMENTATION.md +25 -1
  152. package/server/lib/project-context/plan-progress.js +69 -0
  153. package/server/lib/project-context/plan-progress.test.js +58 -0
  154. package/server/lib/project-context/routes.http.test.js +22 -0
  155. package/server/lib/project-context/routes.js +20 -0
  156. package/server/lib/project-context/runtime.js +132 -18
  157. package/server/lib/project-context/runtime.test.js +58 -0
  158. package/server/lib/provider-read-cache/index.js +7 -1
  159. package/server/lib/provider-read-cache/index.test.js +12 -0
  160. package/server/lib/relay/DOCUMENTATION.md +17 -1
  161. package/server/lib/session-knowledge/DOCUMENTATION.md +17 -0
  162. package/server/lib/session-knowledge/runtime.js +29 -6
  163. package/server/lib/session-knowledge/runtime.test.js +26 -1
  164. package/server/lib/source-control/audit-storage.js +1 -0
  165. package/server/lib/source-control/mutation-storage.js +3 -0
  166. package/server/lib/spaces/DOCUMENTATION.md +14 -9
  167. package/server/lib/spaces/code-out.js +13 -4
  168. package/server/lib/spaces/code-out.test.js +5 -3
  169. package/server/lib/spaces/dispatcher.js +12 -5
  170. package/server/lib/spaces/dispatcher.test.js +19 -1
  171. package/server/lib/spaces/gatekeeper-channel.js +8 -7
  172. package/server/lib/spaces/gatekeeper-channel.test.js +10 -0
  173. package/server/lib/spaces/gatekeeper-program.cjs +38 -3
  174. package/server/lib/spaces/gatekeeper-program.test.js +20 -0
  175. package/server/lib/spaces/hardening.js +14 -1
  176. package/server/lib/spaces/hardening.test.js +5 -0
  177. package/server/lib/spaces/host-providers.js +165 -0
  178. package/server/lib/spaces/host-providers.test.js +100 -0
  179. package/server/lib/spaces/host.js +16 -4
  180. package/server/lib/spaces/journey.js +87 -17
  181. package/server/lib/spaces/journey.test.js +90 -2
  182. package/server/lib/spaces/layout.js +15 -5
  183. package/server/lib/spaces/places/docker-live-support.js +2 -0
  184. package/server/lib/spaces/places/docker.test.js +2 -0
  185. package/server/lib/spaces/places/fake-docker.js +3 -0
  186. package/server/lib/spaces/places/grants.docker.live.test.js +71 -7
  187. package/server/lib/spaces/routes.js +9 -0
  188. package/server/lib/spaces/routes.test.js +4 -2
  189. package/server/lib/spaces/space-opencode.js +31 -14
  190. package/server/lib/spaces/space-opencode.test.js +15 -2
  191. package/server/lib/spaces/space-records.js +8 -0
  192. package/server/lib/spaces/space-records.test.js +7 -3
  193. package/server/lib/spaces/websocket.test.js +13 -1
  194. package/server/lib/ui-auth/ui-auth.js +28 -3
  195. package/server/lib/ui-auth/ui-auth.test.js +31 -0
  196. package/dist/assets/MarkdownRendererImpl-B2LsA09C.js +0 -1
  197. package/dist/assets/PlanView-Dt5EN_JK.js +0 -5
  198. package/dist/assets/SettingsView-BolP_tuu.js +0 -30
  199. package/dist/assets/SourceBoardView-yca1qvgB.js +0 -1
  200. package/dist/assets/SpaceAccessDialog-CZ-u75py.js +0 -1
  201. package/dist/assets/katex-rNcbfUj4.css +0 -1
  202. package/dist/assets/katex.min-DQ8qF6NR.js +0 -65
  203. package/dist/assets/main-CVHM3_8W.js +0 -1048
  204. package/dist/assets/markdownCore-D5ZOJXeO.js +0 -9
  205. package/dist/assets/pl-Bj-Hy0X5.js +0 -20
  206. package/dist/assets/renderElectronMiniChatApp-B_5BeSF6.js +0 -2
  207. package/dist/assets/renderMobileApp-DGEXUTk-.js +0 -25
  208. package/dist/assets/runtimeEndpointReset-CIpvn8QG.js +0 -59
  209. package/dist/assets/sessionOwnership-BZoGed9N.js +0 -1
  210. package/dist/assets/tr-qMRMBQ8r.js +0 -11
  211. package/dist/assets/useAppFontEffects-Bih1DxXi.js +0 -745
  212. package/dist/assets/vendor-tanstack-react-virtual-CvuLsk7D.js +0 -1
  213. package/dist/assets/vendor-tanstack-virtual-core-DPaNcJcT.js +0 -1
@@ -464,6 +464,11 @@ export function registerGitHubRoutes(app, options = {}) {
464
464
  return value;
465
465
  };
466
466
  const ISSUE_KINDS = new Set(['issue-comment', 'issue-state', 'issue-labels']);
467
+ // A review thread's GraphQL node id, such as `PRRT_kwDOA...`.
468
+ const reviewThreadId = (value) => {
469
+ if (!isProviderString(value) || !/^[A-Za-z0-9_=-]{1,200}$/.test(value)) throw canonicalMutationError('threadId is invalid');
470
+ return value;
471
+ };
467
472
  // Labels or reviewers as one whole set, so a repeat asks for the same result.
468
473
  const nameList = (value, name, limit) => {
469
474
  if (!Array.isArray(value) || value.length > limit
@@ -553,7 +558,12 @@ export function registerGitHubRoutes(app, options = {}) {
553
558
  const reconcileExistingMutation = async (octokit, kind, target, operation) => {
554
559
  // A comment or a review leaves nothing that tells a lost write from one
555
560
  // never sent short of guessing from its text, so the outcome stays unknown.
556
- if (kind === 'comment' || kind === 'review' || kind === 'issue-comment') return { state: 'outcome-unknown' };
561
+ if (kind === 'comment' || kind === 'review' || kind === 'issue-comment' || kind === 'thread-reply') return { state: 'outcome-unknown' };
562
+ if (kind === 'thread-resolve') {
563
+ // Someone may have flipped it since: only the asked state is certain.
564
+ const thread = await readReviewThread(octokit, operation.threadId, target.project, target.number);
565
+ return thread.isResolved === operation.resolved ? { state: 'succeeded', result: {} } : { state: 'outcome-unknown' };
566
+ }
557
567
  if (kind === 'labels' || kind === 'issue-labels') {
558
568
  const current = await octokit.rest.issues.listLabelsOnIssue({
559
569
  owner: target.project.owner, repo: target.project.name, issue_number: target.number, per_page: 100,
@@ -630,6 +640,61 @@ export function registerGitHubRoutes(app, options = {}) {
630
640
  }
631
641
  return {};
632
642
  };
643
+ // A GraphQL write GitHub refused answers with errors, not a status: that is
644
+ // a definite refusal with GitHub's own reason.
645
+ const graphqlRejection = (error) => {
646
+ const message = Array.isArray(error?.errors) ? error.errors.find((entry) => isProviderString(entry?.message))?.message : undefined;
647
+ return message ? canonicalMutationError(message, 'SOURCE_CONTROL_MUTATION_REJECTED', 422) : providerRejection(error);
648
+ };
649
+ const REVIEW_THREAD_QUERY = `query($id: ID!) {
650
+ node(id: $id) {
651
+ __typename
652
+ ... on PullRequestReviewThread { isResolved pullRequest { number repository { name owner { login } } } }
653
+ }
654
+ }`;
655
+ /** The review thread `threadId` names, and only one on the target pull request: an id from elsewhere is refused. */
656
+ const readReviewThread = async (octokit, threadId, project, number) => {
657
+ let data;
658
+ try {
659
+ data = await octokit.graphql(REVIEW_THREAD_QUERY, { id: threadId });
660
+ } catch (error) {
661
+ if (!Array.isArray(error?.errors)) throw error;
662
+ data = error.data;
663
+ }
664
+ const node = data?.node;
665
+ const repository = node?.pullRequest?.repository;
666
+ if (node?.__typename !== 'PullRequestReviewThread' || node.pullRequest.number !== number
667
+ || !isProviderString(repository?.owner?.login) || !isProviderString(repository?.name)
668
+ || repository.owner.login.toLowerCase() !== project.owner.toLowerCase()
669
+ || repository.name.toLowerCase() !== project.name.toLowerCase()) {
670
+ throw canonicalMutationError('Review thread is not on this pull request', 'SOURCE_CONTROL_MUTATION_TARGET_INVALID', 409);
671
+ }
672
+ return node;
673
+ };
674
+ const replyToReviewThread = async (octokit, threadId, body) => {
675
+ let data;
676
+ try {
677
+ data = await octokit.graphql(
678
+ 'mutation($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
679
+ { threadId, body },
680
+ );
681
+ } catch (error) {
682
+ throw graphqlRejection(error);
683
+ }
684
+ if (!isProviderString(data?.addPullRequestReviewThreadReply?.comment?.id)) throw invalidProviderPayload('GitHub returned an invalid reply');
685
+ return {};
686
+ };
687
+ const setReviewThreadResolved = async (octokit, threadId, resolved) => {
688
+ const field = resolved ? 'resolveReviewThread' : 'unresolveReviewThread';
689
+ let data;
690
+ try {
691
+ data = await octokit.graphql(`mutation($threadId: ID!) { ${field}(input: { threadId: $threadId }) { thread { isResolved } } }`, { threadId });
692
+ } catch (error) {
693
+ throw graphqlRejection(error);
694
+ }
695
+ if (data?.[field]?.thread?.isResolved !== resolved) throw invalidProviderPayload('GitHub returned an invalid thread state');
696
+ return {};
697
+ };
633
698
  const setLabels = async (octokit, project, number, labels) => {
634
699
  let response;
635
700
  try {
@@ -764,6 +829,17 @@ export function registerGitHubRoutes(app, options = {}) {
764
829
  const body = commentText(req.body?.body, true);
765
830
  return { body, digest: (target) => digestMutationInput({ kind, actor, credential, target, body }) };
766
831
  }
832
+ if (kind === 'thread-reply') {
833
+ const threadId = reviewThreadId(req.body?.threadId);
834
+ const body = commentText(req.body?.body, true);
835
+ return { threadId, body, digest: (target) => digestMutationInput({ kind, actor, credential, target, threadId, body }) };
836
+ }
837
+ if (kind === 'thread-resolve') {
838
+ const threadId = reviewThreadId(req.body?.threadId);
839
+ const resolved = req.body?.resolved;
840
+ if (resolved !== true && resolved !== false) throw canonicalMutationError('resolved is invalid');
841
+ return { threadId, resolved, digest: (target) => digestMutationInput({ kind, actor, credential, target, threadId, resolved }) };
842
+ }
767
843
  if (kind === 'review') {
768
844
  const verdict = req.body?.verdict;
769
845
  if (verdict !== 'approve' && verdict !== 'request-changes') throw canonicalMutationError('review verdict is invalid');
@@ -1020,6 +1096,12 @@ export function registerGitHubRoutes(app, options = {}) {
1020
1096
  } else if (kind === 'comment') {
1021
1097
  perform = () => postComment(octokit, expectedProject, target.number, operation.body);
1022
1098
  reconcile = () => reconcileExistingMutation(octokit, kind, target);
1099
+ } else if (kind === 'thread-reply' || kind === 'thread-resolve') {
1100
+ await readReviewThread(octokit, operation.threadId, expectedProject, target.number);
1101
+ perform = kind === 'thread-reply'
1102
+ ? () => replyToReviewThread(octokit, operation.threadId, operation.body)
1103
+ : () => setReviewThreadResolved(octokit, operation.threadId, operation.resolved);
1104
+ reconcile = () => reconcileExistingMutation(octokit, kind, target, operation);
1023
1105
  } else if (kind === 'review') {
1024
1106
  const { verdict, body } = operation;
1025
1107
  perform = async () => {
@@ -1786,6 +1868,10 @@ export function registerGitHubRoutes(app, options = {}) {
1786
1868
 
1787
1869
  app.post(canonicalGitHubRoutePath('/pr/review'), (req, res) => runCanonicalMutation('review', req, res));
1788
1870
 
1871
+ app.post(canonicalGitHubRoutePath('/pr/thread/reply'), (req, res) => runCanonicalMutation('thread-reply', req, res));
1872
+
1873
+ app.post(canonicalGitHubRoutePath('/pr/thread/resolve'), (req, res) => runCanonicalMutation('thread-resolve', req, res));
1874
+
1789
1875
  app.post(canonicalGitHubRoutePath('/issues/comment'), (req, res) => runCanonicalMutation('issue-comment', req, res));
1790
1876
 
1791
1877
  app.post(canonicalGitHubRoutePath('/pr/state'), (req, res) => runCanonicalMutation('state', req, res));
@@ -634,6 +634,44 @@ describe('canonical GitHub mutations', () => {
634
634
  expect(requests).toEqual([]);
635
635
  });
636
636
 
637
+ const threadOn = (number, repo = 'app') => ({
638
+ data: { node: { __typename: 'PullRequestReviewThread', isResolved: false, pullRequest: { number, repository: { name: repo, owner: { login: 'acme' } } } } },
639
+ });
640
+
641
+ it('answers and resolves a review thread of the target pull request', async () => {
642
+ const account = await auth.setGitHubAuth({ accessToken: 'token-one', user: { id: 1, login: 'actor' } });
643
+ const requests = recordRequests((entry) => {
644
+ if (entry.method === 'GET') return jsonResponse(pullRequest());
645
+ const query = entry.body.query;
646
+ if (query.includes('addPullRequestReviewThreadReply')) return jsonResponse({ data: { addPullRequestReviewThreadReply: { comment: { id: 'PRRC_1' } } } });
647
+ if (query.includes('resolveReviewThread')) return jsonResponse({ data: { resolveReviewThread: { thread: { isResolved: true } } } });
648
+ return jsonResponse(threadOn(7));
649
+ });
650
+ const { app, store } = makeApp();
651
+
652
+ await request(app).post('/api/source-control/github/pr/thread/reply')
653
+ .send({ ...context(account.accountId, { target: pullTarget }), threadId: 'PRRT_one', body: 'Fixed' }).expect(200);
654
+ await request(app).post('/api/source-control/github/pr/thread/resolve')
655
+ .send({ ...context(account.accountId, { target: pullTarget, idempotencyKey: 'request-two' }), threadId: 'PRRT_one', resolved: true }).expect(200);
656
+
657
+ const writes = requests.filter((entry) => entry.method === 'POST' && /mutation/.test(entry.body.query));
658
+ expect(writes.map((entry) => entry.body.variables)).toEqual([{ threadId: 'PRRT_one', body: 'Fixed' }, { threadId: 'PRRT_one' }]);
659
+ expect(store.records.get('request-one')).toMatchObject({ kind: 'change-request-thread-reply', state: 'succeeded' });
660
+ expect(store.records.get('request-two')).toMatchObject({ kind: 'change-request-thread-resolve', state: 'succeeded' });
661
+ });
662
+
663
+ it('refuses a thread of another pull request and writes nothing', async () => {
664
+ const account = await auth.setGitHubAuth({ accessToken: 'token-one', user: { id: 1, login: 'actor' } });
665
+ const requests = recordRequests((entry) => (entry.method === 'GET' ? jsonResponse(pullRequest()) : jsonResponse(threadOn(8))));
666
+ const { app } = makeApp();
667
+
668
+ const response = await request(app).post('/api/source-control/github/pr/thread/reply')
669
+ .send({ ...context(account.accountId, { target: pullTarget }), threadId: 'PRRT_other', body: 'Fixed' }).expect(409);
670
+
671
+ expect(response.body.code).toBe('SOURCE_CONTROL_MUTATION_TARGET_INVALID');
672
+ expect(requests.some((entry) => entry.method === 'POST' && /mutation/.test(entry.body.query))).toBe(false);
673
+ });
674
+
637
675
  it("passes GitHub's reason when it refuses a review", async () => {
638
676
  const account = await auth.setGitHubAuth({ accessToken: 'token-one', user: { id: 1, login: 'actor' } });
639
677
  recordRequests((entry) => (entry.method === 'GET'
@@ -231,6 +231,7 @@ describe('GET /api/source-control/github/references', () => {
231
231
  changedFiles: 1,
232
232
  comments: { totalCount: 0, nodes: [] },
233
233
  reviews: { nodes: [] },
234
+ reviewThreads: { nodes: [] },
234
235
  commits: { totalCount: 0, nodes: [] },
235
236
  } } } }));
236
237
 
@@ -30,8 +30,11 @@ This module owns GitLab instance validation, authentication, remote resolution,
30
30
  - CI lookup is partial enrichment. A jobs failure or malformed jobs payload leaves the merge request authoritative and returns `ci: null`.
31
31
  - GitLab supports merge and squash through the shared mutation. Rebase is not advertised because GitLab cannot perform it as the same atomic merge operation.
32
32
  - Comments and reviews are canonical mutations too: `/pr/comment` and `/issues/comment` post a note (an issue resolves in the bound project, `resolveIssueMutation`), `/pr/review` approves through the approvals API with the target's `headSha` (a moved head is a target mismatch) or requests changes through GraphQL `mergeRequestRequestChanges` (the REST API has no such call; the requester posts to `../graphql` from the REST base, so the same credential and no-redirect rules apply). GraphQL answers a refusal (not a reviewer, an older GitLab) with errors and status 200; that is a definite `422` failure. GitLab answers an approval it does not allow with `401`, which is reported as `403` so it never invalidates the account. A review's text is a separate note posted after the verdict; if it fails the verdict stands and the result says `commented: false`. Comments and reviews reconcile as `outcome-unknown`.
33
+ - Threads (discussions): `/pr/thread/start` opens one on the merge request, `/pr/thread/reply` (`threadId`, `body`) answers one and `/pr/thread/resolve` (`threadId`, `resolved`) resolves or reopens it. Every call names the merge request in its path, so a discussion from elsewhere is not found. Start and reply reconcile as `outcome-unknown`; resolve reconciles by reading the discussion (resolved when every resolvable note is). A context read with `includeTimeline` reads the notes through the discussions API, and each note in a thread carries `thread: { id, resolved, resolvable, first }`; a note on its own (`individual_note`) carries none. The REST API does not say what this account may do, so the same read asks GraphQL (`../graphql`) for the merge request's `discussionLocked`, `userPermissions.createNote` and each discussion's `resolveNote` permission (first 100 discussions) and adds `canReply` / `canResolve` to the thread; when GraphQL cannot answer they are left out and the board shows the buttons, letting GitLab's refusal explain a write it does not allow. Other context reads keep the plain notes list.
33
34
  - `/pr/state` and `/issues/state` close or reopen through `stateEvent` (`close`/`reopen`) and check the returned state. Restart reconciliation (`reconcileStateMutation`) reads the merge request or issue: the asked state succeeds, the other open/closed state is a definite not-applied failure. GitLab refuses to reopen a merged merge request.
34
35
  - `/pr/labels`, `/issues/labels` and `/pr/reviewers` set the whole set through `edit` (`labels` joined by commas, empty clears; `reviewerIds` by numeric user id), deduplicated and sorted for the digest. `reconcileSetMutation` succeeds only when the current set matches, else `outcome-unknown`. `GET /references/labels` and `/references/reviewers` read one page of the project's labels and active members (inherited too) for a project in the bound network. The timeline context carries `reviewers`.
36
+ - Merge requests carry their `labels`; the issue and merge request lists ask with `withLabelsDetails`, so list items have colours while a single merge request read has names only. The board edits labels as a whole set, so a merge request read without them would have its labels replaced by whatever was picked.
37
+ - A context read with `includeDiff` takes each file's added and removed line counts from GraphQL `diffStats` (posted to `../graphql` like the request-changes mutation): GitLab sends no hunks for a file too large to show, so counting hunk lines misses it. When GraphQL cannot answer, the counts come from the hunks as before.
35
38
  - The four merge-request mutation routes are canonical only. They require the complete repository binding context and durable idempotency executor; missing validation or execution support returns `501`. Validation runs before credential lookup, client creation, project resolution, or provider access, and mutation authentication uses only the validated account.
36
39
  - Canonical mutation target resolution starts only from the trusted primary remote and that project's declared fork parent. The expected target project must match one of those projects. Parent lookup failures fail the request. Create accepts `remote` only when it equals the primary remote. `headRemote` defaults to the primary remote; an explicit value resolves that exact remote without ranking or fallback and must map to the already established primary/parent network.
37
40
  - Update, merge, and ready preflight the expected project, merge-request number, head, base, and head SHA against strictly mapped provider state immediately before execution. Mutation preflight, mutation responses, and restart reconciliation also require an authoritative boolean `draft` or `work_in_progress` field. Broader resource reads retain compatibility with older payloads that omit those fields. Durable targets contain the repository and binding revisions, primary remote, server project identity, and actual merge-request coordinates. Digests cover the exact credential account ID and revision, resolved target, and every normalized operation input. Durable records never contain titles, descriptions, provider payloads, tokens, or remote URLs.
@@ -40,6 +43,7 @@ This module owns GitLab instance validation, authentication, remote resolution,
40
43
  - Cross-process execution exclusion, lock errors, and stopped-writer orphan recovery follow the [source-control lock contract](../source-control/DOCUMENTATION.md#cross-process-locks-and-manual-recovery). A live or crashed owner's execution lock blocks reconciliation; restarting alone does not remove it.
41
44
  - `GET /pr/status` keeps a last-known answer per trusted read context (`source-control/status-cache.js`, 90 s TTL, credential revision in the key). A fresh repeat is answered from it unless `force` is set; a provider round trip is bounded to 12 s; a transient failure (unreachable, 429, 5xx, timeout) answers with the last-known status, or 503 when there is none, so a badge keeps its state through an outage. A refused credential (401) is never answered from it. A successful mutation drops the repository's entries; an invalidated account drops its own. Context, list, and history reads have no caches, and failed mutations do not alter unrelated server state.
42
45
  - Issue and merge-request lists take the pickers' `state` (`open` → `opened`, `closed`, `merged`, `all`) and `people` (`assigned` → `assigned_to_me`, `created` → `created_by_me`; `reviewRequested` filters merge requests by the account's own username, read once per service). Unknown values read as open and anyone. Direct number/context lookup resolves any record.
46
+ - `GET /uploads/:secret/:filename` (read context plus `owner`/`repo` in the query) streams a Markdown attachment of a project in the bound network through `GET /projects/:id/uploads/:secret/:filename`, which any member with the Guest role can read. `client.js` `createGitLabDownloader` sends the credential to the instance only and follows a storage redirect once without it, over HTTPS or on the instance; `Range` passes through for seeking. Only raster images and MP4/WebM/QuickTime video are served, with `nosniff` and a sandboxing CSP, so an uploaded page or SVG never runs on this server's origin. A refused file answers 404 and never invalidates the account. The route accepts the URL auth token, since `img` and `video` cannot send headers.
43
47
  - Shared picker and sidebar consumers select GitLab only from a matching repository remote. Self-managed hosts must already appear in source-control instance discovery; unknown hosts are never inferred as GitLab.
44
48
 
45
49
  ## Structure
@@ -96,6 +96,29 @@ function createRequesterFn(fetchImpl) {
96
96
  };
97
97
  }
98
98
 
99
+ /**
100
+ * A file read from the instance's API, for the bytes GitBeaker would buffer.
101
+ * The credential goes to the instance only: a redirect (object storage hands
102
+ * out signed URLs) is followed once, without it, and only over HTTPS or on
103
+ * the instance itself. A `Range` header passes through for video seeking.
104
+ */
105
+ export function createGitLabDownloader({ origin, token, tokenType = 'token', fetch: fetchImpl = (request) => fetch(request) }) {
106
+ const credential = tokenType === 'oauth' ? { authorization: `Bearer ${token}` } : { 'private-token': token };
107
+ return async (apiPath, { range, signal } = {}) => {
108
+ const headers = range ? { range } : {};
109
+ const url = new URL(`api/v4/${apiPath}`, `${origin}/`);
110
+ const response = await fetchImpl(new Request(url, { headers: { ...headers, ...credential }, redirect: 'manual', signal }));
111
+ if (response.status < 300 || response.status >= 400) return response;
112
+ await response.body?.cancel().catch(() => {});
113
+ const location = response.headers.get('location');
114
+ const next = location ? new URL(location, url) : null;
115
+ if (!next || (next.protocol !== 'https:' && next.origin !== url.origin)) {
116
+ throw new Error('GitLab redirected the file to an address it may not be read from');
117
+ }
118
+ return fetchImpl(new Request(next, { headers, redirect: 'error', signal }));
119
+ };
120
+ }
121
+
99
122
  export function createGitLabClient({ origin, token, tokenType = 'token', fetch: fetchImpl = (request) => fetch(request) }) {
100
123
  const requesterFn = createRequesterFn(fetchImpl);
101
124
  return tokenType === 'oauth'
@@ -1,5 +1,5 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest';
2
- import { createGitLabClient } from './client.js';
2
+ import { createGitLabClient, createGitLabDownloader } from './client.js';
3
3
 
4
4
  afterEach(() => vi.unstubAllGlobals());
5
5
 
@@ -69,3 +69,30 @@ describe('GitLab client credentials', () => {
69
69
  }
70
70
  });
71
71
  });
72
+
73
+ describe('GitLab file downloads', () => {
74
+ it('follows a storage redirect once, without the credential, keeping the range', async () => {
75
+ const fetch = vi.fn()
76
+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: 'https://storage.example.com/file?sig=1' } }))
77
+ .mockResolvedValueOnce(new Response('clip', { status: 206 }));
78
+ const download = createGitLabDownloader({ origin: 'https://gitlab.example.com', token: 'pat-token', fetch });
79
+
80
+ const result = await download('projects/2/uploads/abc/demo.mp4', { range: 'bytes=0-3' });
81
+
82
+ expect(result.status).toBe(206);
83
+ const [first, second] = fetch.mock.calls.map(([request]) => request);
84
+ expect(first.url).toBe('https://gitlab.example.com/api/v4/projects/2/uploads/abc/demo.mp4');
85
+ expect(first.headers.get('private-token')).toBe('pat-token');
86
+ expect(second.url).toBe('https://storage.example.com/file?sig=1');
87
+ expect(second.headers.get('private-token')).toBeNull();
88
+ expect(second.headers.get('range')).toBe('bytes=0-3');
89
+ });
90
+
91
+ it('refuses a redirect to plain HTTP elsewhere', async () => {
92
+ const fetch = vi.fn(async () => new Response(null, { status: 302, headers: { location: 'http://storage.example.com/file' } }));
93
+ const download = createGitLabDownloader({ origin: 'https://gitlab.example.com', token: 'oauth-token', tokenType: 'oauth', fetch });
94
+
95
+ await expect(download('projects/2/uploads/abc/demo.mp4')).rejects.toThrow('may not be read from');
96
+ expect(fetch).toHaveBeenCalledTimes(1);
97
+ });
98
+ });
@@ -66,6 +66,7 @@ export function mapGitLabMergeRequest(value, identity, project) {
66
66
  if (text(value.created_at)) request.createdAt = value.created_at;
67
67
  if (text(value.updated_at)) request.updatedAt = value.updated_at;
68
68
  if (text(value.references?.full)) request.headLabel = value.references.full;
69
+ request.labels = mapLabels(value.labels);
69
70
  const mergeState = text(value.detailed_merge_status || value.merge_status);
70
71
  if (mergeState) {
71
72
  request.mergeableState = mergeState;
@@ -116,6 +117,14 @@ export function mapGitLabNote(value, identity, fallbackUrl = '') {
116
117
  if (author) note.author = author;
117
118
  if (text(value.created_at)) note.createdAt = value.created_at;
118
119
  if (text(value.updated_at)) note.updatedAt = value.updated_at;
120
+ // Set by the resource service when the note was read with its discussion.
121
+ const thread = value.discussionThread;
122
+ if (isPlainObject(thread) && text(thread.id)) {
123
+ note.thread = { id: thread.id, resolved: thread.resolved === true, resolvable: thread.resolvable === true, first: thread.first === true };
124
+ // This account's permissions, when GitLab said.
125
+ if (thread.canResolve === true || thread.canResolve === false) note.thread.canResolve = thread.canResolve;
126
+ if (thread.canReply === true || thread.canReply === false) note.thread.canReply = thread.canReply;
127
+ }
119
128
  const position = isPlainObject(value.position) ? value.position : null;
120
129
  if (position && text(position.new_path || position.old_path)) {
121
130
  note.path = position.new_path || position.old_path;
@@ -152,7 +152,7 @@ function liveIssueSummary(ref, raw) {
152
152
  const MAX_FULL_FILE_BYTES = 5 * 1024 * 1024;
153
153
  const COMMIT_SHA = /^[0-9a-f]{40}$/;
154
154
 
155
- export function createGitLabResourceService({ origin, client, resolveProjects = resolveGitLabProjectsFromDirectory, canonicalReads = false }) {
155
+ export function createGitLabResourceService({ origin, client, download, resolveProjects = resolveGitLabProjectsFromDirectory, canonicalReads = false }) {
156
156
  const identity = { provider: 'gitlab', instance: origin };
157
157
 
158
158
  const showProject = async (path, remoteName) => {
@@ -239,6 +239,8 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
239
239
  sourceBranch: options.sourceBranch,
240
240
  search: options.search,
241
241
  showExpanded: options.showExpanded,
242
+ // Labels with their colours; without it GitLab lists only their names.
243
+ withLabelsDetails: true,
242
244
  orderBy: 'updated_at',
243
245
  sort: 'desc',
244
246
  });
@@ -453,6 +455,102 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
453
455
  if (!isPlainObject(result?.mergeRequest)) throw new Error('GitLab returned an invalid request-changes result');
454
456
  };
455
457
 
458
+ /**
459
+ * Merge request discussions as one list of notes, each one in a thread
460
+ * saying which thread, whether it opened it, and the thread's state. A note
461
+ * on its own (`individual_note`) is in no thread. A malformed discussion is
462
+ * passed on as it is, for the note checks to refuse.
463
+ */
464
+ const notesOfDiscussions = (discussions, permissions) => {
465
+ if (!Array.isArray(discussions)) return discussions;
466
+ return discussions.flatMap((discussion) => {
467
+ if (!isPlainObject(discussion) || !Array.isArray(discussion.notes)) return [discussion];
468
+ if (discussion.individual_note === true || !isString(discussion.id) || !discussion.id) return discussion.notes;
469
+ const opener = discussion.notes.find((note) => isPlainObject(note) && note.system !== true);
470
+ const resolvable = discussion.notes.filter((note) => isPlainObject(note) && note.resolvable === true);
471
+ const state = {
472
+ id: discussion.id,
473
+ resolvable: resolvable.length > 0,
474
+ resolved: resolvable.length > 0 && resolvable.every((note) => note.resolved === true),
475
+ };
476
+ // What this account may do, when GitLab said; left out when it did not.
477
+ const canResolve = permissions?.resolve.get(discussion.id);
478
+ if (canResolve !== undefined) state.canResolve = canResolve;
479
+ if (permissions) state.canReply = permissions.reply;
480
+ return discussion.notes.map((note) => (isPlainObject(note) && note.system !== true
481
+ ? { ...note, discussionThread: { ...state, first: note === opener } }
482
+ : note));
483
+ });
484
+ };
485
+ // The REST API says whether a thread can be resolved, not whether this
486
+ // account may; GraphQL says both, and whether the discussion is locked.
487
+ const THREAD_PERMISSIONS_QUERY = `query($path: ID!, $iid: String!) {
488
+ project(fullPath: $path) {
489
+ mergeRequest(iid: $iid) {
490
+ discussionLocked
491
+ userPermissions { createNote }
492
+ discussions(first: 100) { nodes { id notes(first: 1) { nodes { userPermissions { resolveNote } } } } }
493
+ }
494
+ }
495
+ }`;
496
+ /**
497
+ * Whether this account may answer the merge request's threads, and resolve
498
+ * each one by discussion id; null when GitLab cannot say (an older instance,
499
+ * an error). A thread past the first 100 is left out, so it is unknown.
500
+ */
501
+ const readThreadPermissions = async (project, number) => {
502
+ try {
503
+ const response = await client.MergeRequests.requester.post('../graphql', {
504
+ body: { query: THREAD_PERMISSIONS_QUERY, variables: { path: `${project.owner}/${project.name}`, iid: String(number) } },
505
+ });
506
+ const request = response?.body?.data?.project?.mergeRequest;
507
+ const nodes = request?.discussions?.nodes;
508
+ if (!isPlainObject(request) || !Array.isArray(nodes)) return null;
509
+ const resolve = new Map();
510
+ for (const node of nodes) {
511
+ const id = isString(node?.id) ? node.id.split('/').at(-1) : '';
512
+ const allowed = node?.notes?.nodes?.[0]?.userPermissions?.resolveNote;
513
+ if (id && (allowed === true || allowed === false)) resolve.set(id, allowed);
514
+ }
515
+ return { reply: request.discussionLocked !== true && request.userPermissions?.createNote !== false, resolve };
516
+ } catch {
517
+ return null;
518
+ }
519
+ };
520
+
521
+ /** Whether every note a thread can resolve is resolved; null for a thread GitLab did not describe. */
522
+ const discussionResolved = (raw) => {
523
+ if (!isPlainObject(raw) || !Array.isArray(raw.notes)) return null;
524
+ const resolvable = raw.notes.filter((note) => isPlainObject(note) && note.resolvable === true);
525
+ return resolvable.length > 0 && resolvable.every((note) => note.resolved === true);
526
+ };
527
+
528
+ // GitLab sends no hunks for a file too large to show, so counting lines in
529
+ // the diffs misses them; its own line counts per file cover every file.
530
+ const DIFF_STATS_QUERY = `query($path: ID!, $iid: String!) {
531
+ project(fullPath: $path) {
532
+ mergeRequest(iid: $iid) { diffStats { path additions deletions } }
533
+ }
534
+ }`;
535
+ /** Lines added and removed per file path, or null when GitLab cannot say (an older instance, an error). */
536
+ const readDiffStats = async (project, number) => {
537
+ try {
538
+ const response = await client.MergeRequests.requester.post('../graphql', {
539
+ body: { query: DIFF_STATS_QUERY, variables: { path: `${project.owner}/${project.name}`, iid: String(number) } },
540
+ });
541
+ const stats = response?.body?.data?.project?.mergeRequest?.diffStats;
542
+ if (!Array.isArray(stats)) return null;
543
+ const byPath = new Map();
544
+ for (const entry of stats) {
545
+ if (!isPlainObject(entry) || !isString(entry.path) || !Number.isInteger(entry.additions) || !Number.isInteger(entry.deletions)) return null;
546
+ byPath.set(entry.path, { additions: entry.additions, deletions: entry.deletions });
547
+ }
548
+ return byPath;
549
+ } catch {
550
+ return null;
551
+ }
552
+ };
553
+
456
554
  const resolveMutationActionTarget = async (payload) => {
457
555
  if (payload.providerTarget) {
458
556
  return {
@@ -535,6 +633,17 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
535
633
  });
536
634
  },
537
635
 
636
+ /**
637
+ * A file attached in a description or a note of a project in the bound
638
+ * network, as the upstream response. GitLab lets any member with the
639
+ * Guest role or above read it by secret and file name.
640
+ */
641
+ async readUpload(directory, selector, remote, { secret, filename, range, signal }) {
642
+ if (!download) throw new Error('GitLab file downloads are unavailable');
643
+ const target = await constrainedProject(directory, selector, remote);
644
+ return download(`projects/${target.project.id}/uploads/${secret}/${encodeURIComponent(filename)}`, { range, signal });
645
+ },
646
+
538
647
  /** One page of the project's active members, inherited ones too: who can be asked to review. */
539
648
  async listReviewerCandidates(directory, selector, remote) {
540
649
  const target = await constrainedProject(directory, selector, remote);
@@ -547,6 +656,38 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
547
656
  });
548
657
  },
549
658
 
659
+ /** Answers a thread. The request path names the merge request, so a thread from elsewhere is not found. */
660
+ async replyToThread(payload) {
661
+ const { projectId, number } = payload.providerTarget;
662
+ const raw = await client.MergeRequestDiscussions.addNote(projectId, number, payload.threadId, payload.body);
663
+ if (!isPlainObject(raw) || !Number.isInteger(raw.id)) throw new Error('GitLab returned an invalid note');
664
+ return {};
665
+ },
666
+
667
+ async resolveThread(payload) {
668
+ const { projectId, number } = payload.providerTarget;
669
+ const raw = await client.MergeRequestDiscussions.resolve(projectId, number, payload.threadId, payload.resolved);
670
+ if (!isPlainObject(raw) || raw.id !== payload.threadId || discussionResolved(raw) !== payload.resolved) {
671
+ throw new Error('GitLab returned an invalid thread');
672
+ }
673
+ return {};
674
+ },
675
+
676
+ /** Opens a thread on the merge request: a comment that waits to be resolved. */
677
+ async startThread(payload) {
678
+ const { projectId, number } = payload.providerTarget;
679
+ const raw = await client.MergeRequestDiscussions.create(projectId, number, payload.body);
680
+ if (!isPlainObject(raw) || !isString(raw.id) || !raw.id) throw new Error('GitLab returned an invalid thread');
681
+ return {};
682
+ },
683
+
684
+ /** Only the asked state is certain: someone may have flipped it since. */
685
+ async reconcileThreadResolve(providerTarget, threadId, resolved) {
686
+ const { projectId, number } = providerTarget;
687
+ const current = discussionResolved(await client.MergeRequestDiscussions.show(projectId, number, threadId));
688
+ return current === resolved ? { state: 'succeeded', result: {} } : { state: 'outcome-unknown' };
689
+ },
690
+
550
691
  /** The whole label set; an empty one clears them. */
551
692
  async setLabels(payload) {
552
693
  const { projectId, number } = payload.providerTarget;
@@ -817,8 +958,11 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
817
958
  constrainToPrimary: options.constrainToPrimary,
818
959
  remote: options.remote,
819
960
  });
820
- const [notes, diffs, ci, headProject, commitPage] = await Promise.all([
821
- readCollection((page) => client.MergeRequestNotes.all(target.project.id, number, page), 'GitLab merge request has more notes than OpenChamber reads'),
961
+ const [noteSource, diffs, ci, headProject, commitPage, diffStats, threadPermissions] = await Promise.all([
962
+ // The preview's timeline reads the notes as their threads; other readers keep the plain list.
963
+ options.includeTimeline
964
+ ? readCollection((page) => client.MergeRequestDiscussions.all(target.project.id, number, page), 'GitLab merge request has more threads than OpenChamber reads')
965
+ : readCollection((page) => client.MergeRequestNotes.all(target.project.id, number, page), 'GitLab merge request has more notes than OpenChamber reads'),
822
966
  options.includeDiff
823
967
  ? readCollection((page) => client.MergeRequests.allDiffs(target.project.id, number, page), 'GitLab merge request has more changed files than OpenChamber reads', DIFF_PER_PAGE)
824
968
  : Promise.resolve([]),
@@ -832,7 +976,10 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
832
976
  options.includeTimeline
833
977
  ? client.MergeRequests.allCommits(target.project.id, number, { maxPages: 1, perPage: TIMELINE_COMMIT_LIMIT, showExpanded: true }).then(readPage)
834
978
  : Promise.resolve(null),
979
+ options.includeDiff ? readDiffStats(target.project, number) : Promise.resolve(null),
980
+ options.includeTimeline ? readThreadPermissions(target.project, number) : Promise.resolve(null),
835
981
  ]);
982
+ const notes = options.includeTimeline ? notesOfDiscussions(noteSource, threadPermissions) : noteSource;
836
983
  if (canonicalReads && !Array.isArray(notes)) throw new Error('GitLab returned an invalid merge request note list');
837
984
  if (canonicalReads && !Array.isArray(diffs)) throw new Error('GitLab returned an invalid merge request diff list');
838
985
  const mappedNotes = asArray(notes).flatMap((note) => {
@@ -854,6 +1001,8 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
854
1001
  });
855
1002
  const files = asArray(diffs).flatMap((diff) => {
856
1003
  const mapped = mapGitLabDiff(diff);
1004
+ const stats = mapped ? diffStats?.get(mapped.path) : null;
1005
+ if (stats) Object.assign(mapped, stats);
857
1006
  if (mapped) return [mapped];
858
1007
  if (canonicalReads) throw new Error('GitLab returned an invalid merge request diff');
859
1008
  return [];
@@ -899,7 +1048,7 @@ export function createGitLabResourceService({ origin, client, resolveProjects =
899
1048
  const target = resolved.projects[0];
900
1049
  const page = readPage(await client.Issues.all({
901
1050
  projectId: target.project.id, ...await listFilter(options, 'issue'), page: options.page ?? 1,
902
- perPage: PER_PAGE, maxPages: 1, search: options.query, showExpanded: true,
1051
+ perPage: PER_PAGE, maxPages: 1, search: options.query, showExpanded: true, withLabelsDetails: true,
903
1052
  }));
904
1053
  if (canonicalReads && !Array.isArray(page.items)) throw new Error('GitLab returned an invalid issue list');
905
1054
  const rawItems = asArray(page.items);