@deepseek-ai/dsh-experimental-client-ui-forge 0.2.2-rc.5 → 0.2.3-alpha.2

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 (334) hide show
  1. package/README.i18n.yaml +12 -12
  2. package/README.md +47 -30
  3. package/README.zh.md +47 -30
  4. package/lib/client.js +18 -8
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +2444 -406
  7. package/lib/typert.host.js +3433 -950
  8. package/lib/typert.remote-client.d.ts +89 -14
  9. package/lib/typert.remote-client.d.ts.map +1 -1
  10. package/lib/typert.remote-client.js +3155 -978
  11. package/lib/types/branch-name.d.ts +30 -0
  12. package/lib/types/branch-name.d.ts.map +1 -0
  13. package/lib/types/branch-name.js.map +1 -0
  14. package/lib/types/client/AttentionIndicator.d.ts +22 -0
  15. package/lib/types/client/AttentionIndicator.d.ts.map +1 -0
  16. package/lib/types/client/AttentionIndicator.js.map +1 -0
  17. package/lib/types/client/BaseMenu.d.ts.map +1 -1
  18. package/lib/types/client/BaseMenu.js.map +1 -1
  19. package/lib/types/client/ChangeRequestCard.d.ts +87 -9
  20. package/lib/types/client/ChangeRequestCard.d.ts.map +1 -1
  21. package/lib/types/client/ChangeRequestCard.js.map +1 -1
  22. package/lib/types/client/ChangeRequestOverview.d.ts +126 -10
  23. package/lib/types/client/ChangeRequestOverview.d.ts.map +1 -1
  24. package/lib/types/client/ChangeRequestOverview.js.map +1 -1
  25. package/lib/types/client/ChangeRequestsSection.d.ts +76 -0
  26. package/lib/types/client/ChangeRequestsSection.d.ts.map +1 -0
  27. package/lib/types/client/ChangeRequestsSection.js.map +1 -0
  28. package/lib/types/client/ChangedFiles.d.ts +6 -2
  29. package/lib/types/client/ChangedFiles.d.ts.map +1 -1
  30. package/lib/types/client/ChangedFiles.js.map +1 -1
  31. package/lib/types/client/ChangesLoading.d.ts +14 -0
  32. package/lib/types/client/ChangesLoading.d.ts.map +1 -0
  33. package/lib/types/client/ChangesLoading.js.map +1 -0
  34. package/lib/types/client/ChangesTab.d.ts +62 -14
  35. package/lib/types/client/ChangesTab.d.ts.map +1 -1
  36. package/lib/types/client/ChangesTab.js.map +1 -1
  37. package/lib/types/client/ChangesTabTitle.js.map +1 -1
  38. package/lib/types/client/DiffFile.d.ts +23 -4
  39. package/lib/types/client/DiffFile.d.ts.map +1 -1
  40. package/lib/types/client/DiffFile.js.map +1 -1
  41. package/lib/types/client/EnvironmentRows.d.ts +79 -0
  42. package/lib/types/client/EnvironmentRows.d.ts.map +1 -0
  43. package/lib/types/client/EnvironmentRows.js.map +1 -0
  44. package/lib/types/client/FileTreePane.d.ts +5 -2
  45. package/lib/types/client/FileTreePane.d.ts.map +1 -1
  46. package/lib/types/client/FileTreePane.js.map +1 -1
  47. package/lib/types/client/LensFilter.d.ts +50 -0
  48. package/lib/types/client/LensFilter.d.ts.map +1 -0
  49. package/lib/types/client/LensFilter.js.map +1 -0
  50. package/lib/types/client/ReasonButton.d.ts +15 -0
  51. package/lib/types/client/ReasonButton.d.ts.map +1 -0
  52. package/lib/types/client/ReasonButton.js.map +1 -0
  53. package/lib/types/client/ReviewComposer.d.ts +11 -4
  54. package/lib/types/client/ReviewComposer.d.ts.map +1 -1
  55. package/lib/types/client/ReviewComposer.js.map +1 -1
  56. package/lib/types/client/ReviewControls.d.ts +18 -7
  57. package/lib/types/client/ReviewControls.d.ts.map +1 -1
  58. package/lib/types/client/ReviewControls.js.map +1 -1
  59. package/lib/types/client/ReviewThread.d.ts +3 -1
  60. package/lib/types/client/ReviewThread.d.ts.map +1 -1
  61. package/lib/types/client/ReviewThread.js.map +1 -1
  62. package/lib/types/client/ReviewThreads.d.ts +32 -2
  63. package/lib/types/client/ReviewThreads.d.ts.map +1 -1
  64. package/lib/types/client/ReviewThreads.js.map +1 -1
  65. package/lib/types/client/SessionHoverForge.d.ts.map +1 -1
  66. package/lib/types/client/SessionHoverForge.js.map +1 -1
  67. package/lib/types/client/SubmitReview.d.ts +4 -4
  68. package/lib/types/client/SubmitReview.d.ts.map +1 -1
  69. package/lib/types/client/SubmitReview.js.map +1 -1
  70. package/lib/types/client/ThreadList.js.map +1 -1
  71. package/lib/types/client/ViewOptionsMenu.d.ts +7 -1
  72. package/lib/types/client/ViewOptionsMenu.d.ts.map +1 -1
  73. package/lib/types/client/ViewOptionsMenu.js.map +1 -1
  74. package/lib/types/client/WorktreeNameDialog.d.ts +38 -0
  75. package/lib/types/client/WorktreeNameDialog.d.ts.map +1 -0
  76. package/lib/types/client/WorktreeNameDialog.js.map +1 -0
  77. package/lib/types/client/WorktreeProgress.d.ts +14 -3
  78. package/lib/types/client/WorktreeProgress.d.ts.map +1 -1
  79. package/lib/types/client/WorktreeProgress.js.map +1 -1
  80. package/lib/types/client/WorktreeToggle.d.ts +22 -15
  81. package/lib/types/client/WorktreeToggle.d.ts.map +1 -1
  82. package/lib/types/client/WorktreeToggle.js.map +1 -1
  83. package/lib/types/client/action-notices.d.ts +25 -0
  84. package/lib/types/client/action-notices.d.ts.map +1 -0
  85. package/lib/types/client/action-notices.js.map +1 -0
  86. package/lib/types/client/annotations.d.ts +41 -0
  87. package/lib/types/client/annotations.d.ts.map +1 -0
  88. package/lib/types/client/annotations.js.map +1 -0
  89. package/lib/types/client/branch-search.d.ts +38 -0
  90. package/lib/types/client/branch-search.d.ts.map +1 -0
  91. package/lib/types/client/branch-search.js.map +1 -0
  92. package/lib/types/client/change-requests-store.d.ts +25 -0
  93. package/lib/types/client/change-requests-store.d.ts.map +1 -0
  94. package/lib/types/client/change-requests-store.js.map +1 -0
  95. package/lib/types/client/changes-address.d.ts +3 -1
  96. package/lib/types/client/changes-address.d.ts.map +1 -1
  97. package/lib/types/client/changes-address.js.map +1 -1
  98. package/lib/types/client/changes-service.d.ts +119 -0
  99. package/lib/types/client/changes-service.d.ts.map +1 -0
  100. package/lib/types/client/changes-service.js.map +1 -0
  101. package/lib/types/client/changes-store.d.ts +6 -2
  102. package/lib/types/client/changes-store.d.ts.map +1 -1
  103. package/lib/types/client/changes-store.js.map +1 -1
  104. package/lib/types/client/checkout.d.ts.map +1 -1
  105. package/lib/types/client/checkout.js.map +1 -1
  106. package/lib/types/client/diff-rows.d.ts +49 -7
  107. package/lib/types/client/diff-rows.d.ts.map +1 -1
  108. package/lib/types/client/diff-rows.js.map +1 -1
  109. package/lib/types/client/file-tree.d.ts +7 -0
  110. package/lib/types/client/file-tree.d.ts.map +1 -1
  111. package/lib/types/client/file-tree.js.map +1 -1
  112. package/lib/types/client/forge-copy.d.ts +29 -0
  113. package/lib/types/client/forge-copy.d.ts.map +1 -0
  114. package/lib/types/client/forge-copy.js.map +1 -0
  115. package/lib/types/client/format.d.ts +8 -0
  116. package/lib/types/client/format.d.ts.map +1 -1
  117. package/lib/types/client/format.js.map +1 -1
  118. package/lib/types/client/glyphs.d.ts +3 -3
  119. package/lib/types/client/glyphs.d.ts.map +1 -1
  120. package/lib/types/client/glyphs.js.map +1 -1
  121. package/lib/types/client/highlight-context.d.ts +73 -0
  122. package/lib/types/client/highlight-context.d.ts.map +1 -0
  123. package/lib/types/client/highlight-context.js.map +1 -0
  124. package/lib/types/client/index.d.ts +9 -5
  125. package/lib/types/client/index.d.ts.map +1 -1
  126. package/lib/types/client/index.js.map +1 -1
  127. package/lib/types/client/lens-filter.d.ts +69 -0
  128. package/lib/types/client/lens-filter.d.ts.map +1 -0
  129. package/lib/types/client/lens-filter.js.map +1 -0
  130. package/lib/types/client/locales.d.ts +188 -36
  131. package/lib/types/client/locales.d.ts.map +1 -1
  132. package/lib/types/client/locales.js.map +1 -1
  133. package/lib/types/client/mount.d.ts +0 -4
  134. package/lib/types/client/mount.d.ts.map +1 -1
  135. package/lib/types/client/mount.js.map +1 -1
  136. package/lib/types/client/review-page/ReviewChat.d.ts +112 -0
  137. package/lib/types/client/review-page/ReviewChat.d.ts.map +1 -0
  138. package/lib/types/client/review-page/ReviewChat.js.map +1 -0
  139. package/lib/types/client/review-page/ReviewDetail.d.ts +56 -0
  140. package/lib/types/client/review-page/ReviewDetail.d.ts.map +1 -0
  141. package/lib/types/client/review-page/ReviewDetail.js.map +1 -0
  142. package/lib/types/client/review-page/ReviewLabels.d.ts +32 -0
  143. package/lib/types/client/review-page/ReviewLabels.d.ts.map +1 -0
  144. package/lib/types/client/review-page/ReviewLabels.js.map +1 -0
  145. package/lib/types/client/review-page/ReviewList.d.ts +68 -0
  146. package/lib/types/client/review-page/ReviewList.d.ts.map +1 -0
  147. package/lib/types/client/review-page/ReviewList.js.map +1 -0
  148. package/lib/types/client/review-page/ReviewNav.d.ts +28 -0
  149. package/lib/types/client/review-page/ReviewNav.d.ts.map +1 -0
  150. package/lib/types/client/review-page/ReviewNav.js.map +1 -0
  151. package/lib/types/client/review-page/ReviewPage.d.ts +61 -0
  152. package/lib/types/client/review-page/ReviewPage.d.ts.map +1 -0
  153. package/lib/types/client/review-page/ReviewPage.js.map +1 -0
  154. package/lib/types/client/review-page/ReviewStatus.d.ts +37 -0
  155. package/lib/types/client/review-page/ReviewStatus.d.ts.map +1 -0
  156. package/lib/types/client/review-page/ReviewStatus.js.map +1 -0
  157. package/lib/types/client/review-page/host-stream.d.ts +24 -0
  158. package/lib/types/client/review-page/host-stream.d.ts.map +1 -0
  159. package/lib/types/client/review-page/host-stream.js.map +1 -0
  160. package/lib/types/client/review-page/review-lists.d.ts +116 -0
  161. package/lib/types/client/review-page/review-lists.d.ts.map +1 -0
  162. package/lib/types/client/review-page/review-lists.js.map +1 -0
  163. package/lib/types/client/review-page/review-mount.d.ts +50 -0
  164. package/lib/types/client/review-page/review-mount.d.ts.map +1 -0
  165. package/lib/types/client/review-page/review-mount.js.map +1 -0
  166. package/lib/types/client/review-page/review-store.d.ts +79 -0
  167. package/lib/types/client/review-page/review-store.d.ts.map +1 -0
  168. package/lib/types/client/review-page/review-store.js.map +1 -0
  169. package/lib/types/client/review-queue.d.ts +19 -0
  170. package/lib/types/client/review-queue.d.ts.map +1 -1
  171. package/lib/types/client/review-queue.js.map +1 -1
  172. package/lib/types/client/review-threads.d.ts +0 -8
  173. package/lib/types/client/review-threads.d.ts.map +1 -1
  174. package/lib/types/client/review-threads.js.map +1 -1
  175. package/lib/types/client/review.d.ts +18 -0
  176. package/lib/types/client/review.d.ts.map +1 -1
  177. package/lib/types/client/review.js.map +1 -1
  178. package/lib/types/client/slots.d.ts +114 -0
  179. package/lib/types/client/slots.d.ts.map +1 -0
  180. package/lib/types/client/slots.js.map +1 -0
  181. package/lib/types/client/source.d.ts +29 -23
  182. package/lib/types/client/source.d.ts.map +1 -1
  183. package/lib/types/client/source.js.map +1 -1
  184. package/lib/types/client/status.d.ts +13 -2
  185. package/lib/types/client/status.d.ts.map +1 -1
  186. package/lib/types/client/status.js.map +1 -1
  187. package/lib/types/git.d.ts +4 -15
  188. package/lib/types/git.d.ts.map +1 -1
  189. package/lib/types/git.js.map +1 -1
  190. package/lib/types/index.d.ts +346 -28
  191. package/lib/types/index.d.ts.map +1 -1
  192. package/lib/types/index.js.map +1 -1
  193. package/lib/types/lens-version.d.ts +14 -0
  194. package/lib/types/lens-version.d.ts.map +1 -0
  195. package/lib/types/lens-version.js.map +1 -0
  196. package/lib/types/lenses.d.ts +122 -0
  197. package/lib/types/lenses.d.ts.map +1 -0
  198. package/lib/types/lenses.js.map +1 -0
  199. package/lib/types/local-diff.d.ts +16 -0
  200. package/lib/types/local-diff.d.ts.map +1 -1
  201. package/lib/types/local-diff.js.map +1 -1
  202. package/lib/types/panel.d.ts +59 -8
  203. package/lib/types/panel.d.ts.map +1 -1
  204. package/lib/types/panel.js.map +1 -1
  205. package/lib/types/parse.d.ts +24 -8
  206. package/lib/types/parse.d.ts.map +1 -1
  207. package/lib/types/parse.js.map +1 -1
  208. package/lib/types/review-cache.d.ts +29 -19
  209. package/lib/types/review-cache.d.ts.map +1 -1
  210. package/lib/types/review-cache.js.map +1 -1
  211. package/lib/types/states.d.ts +11 -7
  212. package/lib/types/states.d.ts.map +1 -1
  213. package/lib/types/states.js.map +1 -1
  214. package/lib/types/types.d.ts +266 -20
  215. package/lib/types/types.d.ts.map +1 -1
  216. package/lib/types/viewer-lists.d.ts +113 -0
  217. package/lib/types/viewer-lists.d.ts.map +1 -0
  218. package/lib/types/viewer-lists.js.map +1 -0
  219. package/lib/types/worktree.d.ts +20 -11
  220. package/lib/types/worktree.d.ts.map +1 -1
  221. package/lib/types/worktree.js.map +1 -1
  222. package/locale/de.json +1 -1
  223. package/locale/en.json +1 -1
  224. package/locale/es.json +1 -1
  225. package/locale/fr.json +1 -1
  226. package/locale/ja.json +1 -1
  227. package/locale/pt.json +1 -1
  228. package/locale/ru.json +1 -1
  229. package/locale/zh.json +1 -1
  230. package/package.json +61 -52
  231. package/src/branch-name.ts +74 -0
  232. package/src/client/AttentionIndicator.tsx +37 -0
  233. package/src/client/BaseMenu.module.css +0 -20
  234. package/src/client/BaseMenu.tsx +9 -52
  235. package/src/client/ChangeRequestCard.tsx +276 -131
  236. package/src/client/ChangeRequestOverview.module.css +1 -1
  237. package/src/client/ChangeRequestOverview.tsx +183 -67
  238. package/src/client/ChangeRequestsSection.tsx +234 -0
  239. package/src/client/ChangedFiles.module.css +5 -1
  240. package/src/client/ChangedFiles.tsx +72 -36
  241. package/src/client/ChangesLoading.module.css +110 -0
  242. package/src/client/ChangesLoading.tsx +69 -0
  243. package/src/client/ChangesTab.module.css +83 -114
  244. package/src/client/ChangesTab.tsx +331 -100
  245. package/src/client/ChangesTabTitle.tsx +3 -3
  246. package/src/client/DiffFile.tsx +241 -45
  247. package/src/client/EnvironmentRows.tsx +263 -0
  248. package/src/client/FileLabel.tsx +1 -1
  249. package/src/client/FileTreePane.tsx +11 -6
  250. package/src/client/{ForgeTab.module.css → Forge.module.css} +130 -275
  251. package/src/client/LensFilter.module.css +87 -0
  252. package/src/client/LensFilter.tsx +105 -0
  253. package/src/client/ReasonButton.tsx +23 -0
  254. package/src/client/ReviewComposer.module.css +2 -8
  255. package/src/client/ReviewComposer.tsx +27 -8
  256. package/src/client/ReviewControls.module.css +39 -0
  257. package/src/client/ReviewControls.tsx +71 -15
  258. package/src/client/ReviewThread.tsx +55 -30
  259. package/src/client/ReviewThreads.module.css +24 -0
  260. package/src/client/ReviewThreads.tsx +56 -21
  261. package/src/client/SessionHoverForge.tsx +2 -1
  262. package/src/client/SubmitReview.tsx +11 -8
  263. package/src/client/ThreadList.tsx +1 -1
  264. package/src/client/ViewOptionsMenu.tsx +19 -4
  265. package/src/client/WorktreeNameDialog.module.css +53 -0
  266. package/src/client/WorktreeNameDialog.tsx +93 -0
  267. package/src/client/WorktreeProgress.tsx +100 -35
  268. package/src/client/WorktreeToggle.module.css +121 -5
  269. package/src/client/WorktreeToggle.tsx +178 -61
  270. package/src/client/action-notices.ts +38 -0
  271. package/src/client/annotations.ts +105 -0
  272. package/src/client/branch-search.tsx +77 -0
  273. package/src/client/change-requests-store.ts +50 -0
  274. package/src/client/changes-address.ts +3 -1
  275. package/src/client/changes-service.ts +173 -0
  276. package/src/client/changes-store.ts +103 -91
  277. package/src/client/checkout.ts +2 -1
  278. package/src/client/diff-rows.ts +100 -16
  279. package/src/client/file-tree.ts +29 -0
  280. package/src/client/forge-copy.ts +49 -0
  281. package/src/client/format.ts +14 -0
  282. package/src/client/glyphs.tsx +12 -13
  283. package/src/client/highlight-context.ts +213 -0
  284. package/src/client/index.ts +20 -5
  285. package/src/client/lens-filter.ts +136 -0
  286. package/src/client/locales.ts +1504 -288
  287. package/src/client/mount.ts +228 -109
  288. package/src/client/review-page/ReviewChat.tsx +311 -0
  289. package/src/client/review-page/ReviewDetail.tsx +331 -0
  290. package/src/client/review-page/ReviewLabels.tsx +94 -0
  291. package/src/client/review-page/ReviewList.tsx +461 -0
  292. package/src/client/review-page/ReviewNav.tsx +47 -0
  293. package/src/client/review-page/ReviewPage.module.css +946 -0
  294. package/src/client/review-page/ReviewPage.tsx +287 -0
  295. package/src/client/review-page/ReviewStatus.tsx +259 -0
  296. package/src/client/review-page/host-stream.ts +63 -0
  297. package/src/client/review-page/review-lists.ts +207 -0
  298. package/src/client/review-page/review-mount.ts +228 -0
  299. package/src/client/review-page/review-store.ts +94 -0
  300. package/src/client/review-queue.ts +30 -0
  301. package/src/client/review-threads.ts +0 -12
  302. package/src/client/review.ts +27 -0
  303. package/src/client/slots.ts +92 -0
  304. package/src/client/source.ts +67 -43
  305. package/src/client/status.ts +16 -4
  306. package/src/git.ts +16 -38
  307. package/src/index.ts +900 -152
  308. package/src/lens-version.ts +27 -0
  309. package/src/lenses.ts +284 -0
  310. package/src/local-diff.ts +48 -1
  311. package/src/panel.ts +123 -28
  312. package/src/parse.ts +86 -10
  313. package/src/review-cache.ts +57 -37
  314. package/src/states.ts +38 -18
  315. package/src/types.ts +267 -21
  316. package/src/viewer-lists.ts +375 -0
  317. package/src/worktree.ts +64 -34
  318. package/lib/types/client/ForgeTab.d.ts +0 -65
  319. package/lib/types/client/ForgeTab.d.ts.map +0 -1
  320. package/lib/types/client/ForgeTab.js.map +0 -1
  321. package/lib/types/client/ForgeTabTitle.d.ts +0 -11
  322. package/lib/types/client/ForgeTabTitle.d.ts.map +0 -1
  323. package/lib/types/client/ForgeTabTitle.js.map +0 -1
  324. package/lib/types/client/HeaderButton.d.ts +0 -27
  325. package/lib/types/client/HeaderButton.d.ts.map +0 -1
  326. package/lib/types/client/HeaderButton.js.map +0 -1
  327. package/lib/types/client/LocalChangesCard.d.ts +0 -29
  328. package/lib/types/client/LocalChangesCard.d.ts.map +0 -1
  329. package/lib/types/client/LocalChangesCard.js.map +0 -1
  330. package/src/client/ForgeTab.tsx +0 -263
  331. package/src/client/ForgeTabTitle.tsx +0 -21
  332. package/src/client/HeaderButton.module.css +0 -29
  333. package/src/client/HeaderButton.tsx +0 -68
  334. package/src/client/LocalChangesCard.tsx +0 -83
package/src/index.ts CHANGED
@@ -6,37 +6,48 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
6
6
  import type {} from '@deepseek-ai/dsh-api-remote-access'
7
7
  import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
8
8
  import type {
9
- BranchUpdateMethod, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure,
10
- ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
11
- ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
9
+ BranchUpdateMethod, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot,
10
+ ChangeRequestUpdate, ForgeActionFailure, ForgeCommitList,
11
+ ForgeFailure,
12
+ ForgeLineComment, ForgeRerunRequest, ForgeReviewChange, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult,
13
+ ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
12
14
  } from '@deepseek-ai/dsh-experimental-forge'
13
15
  import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
14
16
  import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
15
17
  import { appendPluginRecord } from '@deepseek-ai/dsh-session'
16
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
18
+ import type { Session, SessionEvent, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
17
19
  import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
18
20
  import type {} from '@deepseek-ai/dsh-session-projection-cache'
19
21
  import type {} from '@deepseek-ai/dsh-session-query'
20
22
  import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
21
23
  import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
22
24
  import { assertNever } from '@deepseek-ai/dsh-util-values'
23
- import { gitIn, inspectCheckout, listBranches } from './git.ts'
25
+ import { gitIn, hasBranch, inspectCheckout } from './git.ts'
24
26
  import type { Inspection } from './git.ts'
27
+ import { branchNameProblem } from './branch-name.ts'
25
28
  import { parseDiff } from './diff.ts'
26
29
  import {
27
30
  aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint,
28
- localCommits, localDiff, localText, NoForkPoint,
31
+ localCommits, localDiff, localOldText, localText, NoForkPoint,
29
32
  } from './local-diff.ts'
33
+ import type { ForkPoint } from './local-diff.ts'
34
+ import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from './lenses.ts'
35
+ import type { LensSubject } from './lenses.ts'
36
+ import { lensVersion } from './lens-version.ts'
30
37
  import { rangeStart } from './commit-range.ts'
31
38
  import { ATTRIBUTES_PATH, FileLayers } from './layers.ts'
32
39
  import { missingWorktree, SessionPanel } from './panel.ts'
40
+ import { BASE_REF_PREFIXES, parseWorktreeBases, remoteOrder, remoteRepository } from './parse.ts'
33
41
  import { PatchCache } from './patch-cache.ts'
34
42
  import { ReviewCache } from './review-cache.ts'
35
43
  import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
36
- import type { PanelConfig } from './panel.ts'
44
+ import { Reader, ViewerLists } from './viewer-lists.ts'
45
+ import type { KeptPanel, PanelConfig } from './panel.ts'
37
46
  import type {
38
- Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits,
39
- ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState,
47
+ Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
48
+ ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame,
49
+ ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope,
50
+ ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState,
40
51
  } from './types.ts'
41
52
  import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
42
53
  import type { HeldWork } from './worktree.ts'
@@ -50,8 +61,21 @@ declare module '@deepseek-ai/cordis' {
50
61
  }
51
62
  }
52
63
 
53
- /** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */
54
- type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string }
64
+ /** A change request a read or action addresses, with its latest polling result. */
65
+ interface ChangeRequestTarget {
66
+ readonly ref: ChangeRequestRef
67
+ readonly update: ChangeRequestUpdate | null
68
+ }
69
+
70
+ /** Panel limits and worktree branch prefix plus the branch and commit listing limits and the lens and annotation limits. */
71
+ type ControllerConfig = PanelConfig & {
72
+ readonly maxBranches: number
73
+ readonly maxCommits: number
74
+ readonly lensTimeoutMs: number
75
+ readonly maxLensReadBytes: number
76
+ readonly maxCachedLensBytes: number
77
+ readonly maxAnnotationsPerFile: number
78
+ }
55
79
 
56
80
  /**
57
81
  * Serves the forge panel. Following a Session inspects the checkout of its
@@ -89,17 +113,39 @@ export class ForgePanelController extends TypertRemoteService {
89
113
  interfacePaths: z.array(z.string()).default([]),
90
114
  maxCachedReviewBytes: z.number().default(16_777_216),
91
115
  reviewRefreshMs: z.number().default(60_000),
116
+ statusMaxAgeMs: z.number().default(10_000),
117
+ lensTimeoutMs: z.number().default(60_000),
118
+ maxLensReadBytes: z.number().default(33_554_432),
119
+ maxCachedLensBytes: z.number().default(4_194_304),
120
+ maxAnnotationsPerFile: z.number().default(100),
121
+ reviewListIntervalMs: z.number().default(120_000),
122
+ reviewCountIntervalMs: z.number().default(300_000),
123
+ reviewMaxBackoffMs: z.number().default(1_800_000),
124
+ reviewPageSize: z.number().default(50),
92
125
  })
93
126
 
94
127
  private readonly home: Context
95
128
  private readonly config: ControllerConfig
96
129
  private readonly panels = new Map<Session, SessionPanel>()
130
+ /** What the last panel of a Session kept when its last follower left. */
131
+ private readonly keptPanels = new WeakMap<Session, KeptPanel>()
97
132
  private worktreeStates!: ProjectionHandle<ForgeWorktreeState>
98
133
  private creations!: WorktreeCreations
99
134
  private readonly patches: PatchCache
100
135
  private readonly layers: FileLayers
101
- private readonly reviews: ReviewCache
136
+ private readonly reviews: ReviewCache<ForgeReviewData>
137
+ /** The viewed marks read for each change request, by head commit. */
138
+ private readonly viewed: ReviewCache<ForgeViewedFiles>
139
+ private readonly lenses = new LensRegistry()
140
+ private readonly lensResults: LensCache
141
+ /** Review changes `forge/review-changed` announced per change request, which each panel entry reports. */
142
+ private readonly reviewRevisions = new Map<ChangeRequestKey, number>()
102
143
  private states: ChangeRequestStates | undefined
144
+ private readonly viewerLists: ViewerLists
145
+ /** The change request a review conversation's draft quotes, per Session, bound once its first message enters the inbox. */
146
+ private readonly staged = new Map<SessionId, string>()
147
+ /** Review page streams of change requests shown in full, which a review change makes publish again. */
148
+ private readonly reviewFollowers = new Set<{ readonly key: ChangeRequestKey; readonly emit: () => void }>()
103
149
  private readonly stopPanels: () => Promise<void>
104
150
  private readonly stopStates: () => Promise<void>
105
151
 
@@ -107,16 +153,26 @@ export class ForgePanelController extends TypertRemoteService {
107
153
  super(ctx, 'forgePanel')
108
154
  const resolved = config as Required<Config>
109
155
  if (resolved.gitCommand.trim().length === 0) throw new Error('forge-panel: gitCommand must not be empty')
110
- for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs'] as const) {
156
+ for (const key of [
157
+ 'gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs', 'statusMaxAgeMs', 'lensTimeoutMs',
158
+ 'reviewListIntervalMs', 'reviewCountIntervalMs', 'reviewMaxBackoffMs',
159
+ ] as const) {
111
160
  const value = resolved[key]
112
161
  if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
113
162
  throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
114
163
  }
115
164
  }
116
- for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes'] as const) {
165
+ for (const key of [
166
+ 'maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes', 'maxLensReadBytes',
167
+ 'maxCachedLensBytes', 'maxAnnotationsPerFile', 'reviewPageSize',
168
+ ] as const) {
117
169
  if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`)
118
170
  }
119
- if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
171
+ if (resolved.reviewMaxBackoffMs < Math.max(resolved.reviewListIntervalMs, resolved.reviewCountIntervalMs)) {
172
+ throw new Error('forge-panel: reviewMaxBackoffMs must be at least reviewListIntervalMs and reviewCountIntervalMs')
173
+ }
174
+ // Generated names append hexadecimal digits, so the prefix followed by one digit must be a valid branch name.
175
+ if (branchNameProblem(`${resolved.worktreePrefix}0`) !== null) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
120
176
  for (const key of ['testPaths', 'interfacePaths'] as const) {
121
177
  if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`)
122
178
  }
@@ -125,6 +181,9 @@ export class ForgePanelController extends TypertRemoteService {
125
181
  this.config = resolved
126
182
  this.patches = new PatchCache(resolved.maxCachedDiffBytes)
127
183
  this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
184
+ this.viewed = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
185
+ this.lensResults = new LensCache(resolved.maxCachedLensBytes)
186
+ ctx.effect(() => () => { this.lenses.close() }, 'forge-panel: lens streams')
128
187
  this.stopPanels = ctx.effect(() => async () => {
129
188
  const panels = [...this.panels.values()]
130
189
  this.panels.clear()
@@ -133,6 +192,19 @@ export class ForgePanelController extends TypertRemoteService {
133
192
  this.stopStates = ctx.effect(() => async () => {
134
193
  await this.states?.dispose()
135
194
  }, 'forge-panel: stop change request states')
195
+ this.viewerLists = new ViewerLists({
196
+ sources: () => ctx.forge.viewerSources(),
197
+ list: async (forge, query, signal) => await ctx.forge.listForViewer(forge, query, signal),
198
+ count: async (forge, host, signal) => await ctx.forge.countForViewer(forge, host, signal),
199
+ report: (error) => { ctx.logger.warn(`forge-panel: reading a review list failed: ${String(error)}`) },
200
+ }, {
201
+ listIntervalMs: resolved.reviewListIntervalMs,
202
+ countIntervalMs: resolved.reviewCountIntervalMs,
203
+ maxBackoffMs: resolved.reviewMaxBackoffMs,
204
+ pageSize: resolved.reviewPageSize,
205
+ })
206
+ const viewerLists = this.viewerLists
207
+ ctx.effect(() => async () => { await viewerLists.dispose() }, 'forge-panel: stop review lists')
136
208
  }
137
209
 
138
210
  protected async [Service.init](): Promise<void> {
@@ -149,10 +221,19 @@ export class ForgePanelController extends TypertRemoteService {
149
221
  this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => {
150
222
  this.panels.get(session)?.updateWorktree()
151
223
  })
152
- const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) })
224
+ const inbox = ctx.on('agent/inbox/inserted', ({ agent, message }) => {
225
+ this.bindStaged(agent.session)
226
+ this.holdTurn(agent, message)
227
+ })
228
+ const providers = ctx.on('forge/providers-changed', () => { this.viewerLists.sourcesChanged() })
153
229
  const events = ctx.on('session/event', (session: Session, event: SessionEvent) => {
154
230
  this.panels.get(session)?.observe(event)
155
231
  })
232
+ // A change request staged for a Session that is disposed before its next message is never bound.
233
+ const disposed = ctx.on('session/disposed', (session: Session) => { this.staged.delete(session.id) })
234
+ const reviewChanges = ctx.on('forge/review-changed', (ref: ChangeRequestRef, change: ForgeReviewChange) => {
235
+ this.reviewChanged(ref, change)
236
+ })
156
237
  const services = ctx.on('internal/service', (name: string) => {
157
238
  if (name !== 'worktrees') return
158
239
  for (const panel of this.panels.values()) panel.updateWorktree()
@@ -162,6 +243,9 @@ export class ForgePanelController extends TypertRemoteService {
162
243
  yield stateOwner.dispose
163
244
  yield inbox
164
245
  yield events
246
+ yield disposed
247
+ yield reviewChanges
248
+ yield providers
165
249
  yield services
166
250
  yield stopPanels
167
251
  yield stopStates
@@ -200,27 +284,393 @@ export class ForgePanelController extends TypertRemoteService {
200
284
  yield* this.changeRequestStatesHub().stream(id => access === undefined || access.allows({ kind: 'session', id }), signal)
201
285
  }
202
286
 
287
+ /**
288
+ * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on:
289
+ * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one
290
+ * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to
291
+ * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.
292
+ * @param repository - one repository to list in, or null for every repository the user can read.
293
+ * @param signal - ends the stream.
294
+ * @returns frames, each complete.
295
+ */
296
+ @Remote({ mode: 'stream' })
297
+ async *reviewLists(
298
+ repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal,
299
+ ): AsyncIterable<ForgeReviewFrame> {
300
+ yield* this.viewerLists.lists(repository, signal)
301
+ }
302
+
303
+ /**
304
+ * Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read:
305
+ * the latest count first, then each change. It is read every `reviewCountIntervalMs` while some stream lasts, and a
306
+ * list stream of every repository updates it as well. The stream ends when `signal` aborts or the Remote stops.
307
+ * @param signal - ends the stream.
308
+ * @returns frames, each complete.
309
+ */
310
+ @Remote({ mode: 'stream' })
311
+ async *reviewCount(signal: AbortSignal): AsyncIterable<ForgeReviewCountFrame> {
312
+ yield* this.viewerLists.count(signal)
313
+ }
314
+
315
+ /**
316
+ * Read every streamed review page list and the count again at once.
317
+ * @param signal - request cancellation.
318
+ */
319
+ @Remote
320
+ // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect
321
+ async reviewRefresh(signal: AbortSignal): Promise<void> {
322
+ signal.throwIfAborted()
323
+ this.viewerLists.refresh()
324
+ }
325
+
326
+ /**
327
+ * Poll one change request the review page shows at once; its stream reports the result.
328
+ * @param url - web URL of the change request.
329
+ * @param signal - request cancellation.
330
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL.
331
+ */
332
+ @Remote
333
+ // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect
334
+ async reviewPoll(url: string, signal: AbortSignal): Promise<void> {
335
+ signal.throwIfAborted()
336
+ this.home.forge.refresh(this.served(url).ref)
337
+ }
338
+
339
+ /**
340
+ * Stream one change request the review page shows in full: its latest polling result first, then each later result
341
+ * and each review change `forge/review-changed` announces for it. The change request is polled through `ctx.forge`
342
+ * while the stream lasts. Review page reads and actions name a change request by URL and need no Session binding, so
343
+ * only callers that may use the Host's code host credentials reach them.
344
+ * @param url - web URL of the change request.
345
+ * @param signal - ends the stream.
346
+ * @returns frames, each complete.
347
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL.
348
+ */
349
+ @Remote({ mode: 'stream' })
350
+ async *reviewChangeRequest(url: string, signal: AbortSignal): AsyncIterable<ForgeReviewChangeRequest> {
351
+ signal.throwIfAborted()
352
+ const { ref } = this.served(url)
353
+ const key = changeRequestKey(ref)
354
+ const reader = new Reader<ForgeReviewChangeRequest>(signal)
355
+ let update: ChangeRequestUpdate | null = this.home.forge.latest(ref) ?? null
356
+ let snapshot = update !== null && 'snapshot' in update ? update.snapshot : null
357
+ const emit = (): void => {
358
+ const forge = this.home.forge.describe(ref.repository.forge) ?? null
359
+ reader.push({ url, ref, forge, update, snapshot, reviewRevision: this.reviewRevisions.get(key) ?? 0 })
360
+ }
361
+ const follower = { key, emit }
362
+ this.reviewFollowers.add(follower)
363
+ const stop = this.home.forge.watch(ref, (next) => {
364
+ update = next
365
+ if ('snapshot' in next) snapshot = next.snapshot
366
+ emit()
367
+ }, { maxAgeMs: this.config.statusMaxAgeMs })
368
+ emit()
369
+ try {
370
+ yield* reader.frames()
371
+ } finally {
372
+ stop()
373
+ this.reviewFollowers.delete(follower)
374
+ reader.dispose()
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Read the description and labels of a change request for the review page.
380
+ * @param url - web URL of the change request.
381
+ * @param signal - request cancellation.
382
+ * @returns the description.
383
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/description-failed` with the
384
+ * host's reason when the host does not provide it.
385
+ */
386
+ @Remote
387
+ async reviewDescription(url: string, signal: AbortSignal): Promise<ChangeRequestDescription> {
388
+ signal.throwIfAborted()
389
+ const result = await this.home.forge.readDescription(this.served(url).ref, signal)
390
+ if ('code' in result) throw new RemoteError('forgePanel/description-failed', result.message, {})
391
+ return result
392
+ }
393
+
394
+ /**
395
+ * Read every check of a change request the review page shows.
396
+ * @param url - web URL of the change request.
397
+ * @param headSha - head commit whose checks the page shows.
398
+ * @param signal - request cancellation.
399
+ * @returns the snapshot with every check.
400
+ * @throws as {@link ForgePanelController.changeRequestChecks} does, with `forgePanel/unrecognized-url` in place of
401
+ * `forgePanel/not-bound`.
402
+ */
403
+ @Remote
404
+ async reviewChecks(url: string, headSha: string, signal: AbortSignal): Promise<ChangeRequestSnapshot> {
405
+ signal.throwIfAborted()
406
+ return await this.readChecks(this.served(url).ref, headSha, signal, () => {})
407
+ }
408
+
409
+ /**
410
+ * Read the review threads of a change request the review page shows, at the head of its latest status.
411
+ * @param url - web URL of the change request.
412
+ * @param headSha - head commit the page shows.
413
+ * @param fresh - whether to read from the host even when threads at this head and update time are kept.
414
+ * @param signal - request cancellation.
415
+ * @returns the threads at `headSha`.
416
+ * @throws as {@link ForgePanelController.changeRequestReview} does, with `forgePanel/unrecognized-url` in place of
417
+ * `forgePanel/not-bound`.
418
+ */
419
+ @Remote
420
+ async reviewThreads(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData> {
421
+ signal.throwIfAborted()
422
+ return await this.readThreads(this.served(url), headSha, fresh, signal)
423
+ }
424
+
425
+ /**
426
+ * Write to the review threads or the pending review of a change request the review page shows.
427
+ * @param url - web URL of the change request.
428
+ * @param write - the write and the head commit the user saw.
429
+ * @param signal - request cancellation.
430
+ * @returns whether the host took the write, as {@link ForgePanelController.changeRequestReviewWrite} does.
431
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid write.
432
+ */
433
+ @Remote
434
+ async reviewThreadWrite(url: string, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult> {
435
+ signal.throwIfAborted()
436
+ return await this.writeThreads(this.served(url).ref, write, signal)
437
+ }
438
+
439
+ /**
440
+ * Publish a line comment or a completed review on a change request the review page shows.
441
+ * @param url - web URL of the change request.
442
+ * @param request - reviewed head, ranges, plain text, and explicit review decision.
443
+ * @param signal - request cancellation.
444
+ * @returns confirmed publication or a typed failure, as {@link ForgePanelController.submitReview} does.
445
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid review.
446
+ */
447
+ @Remote
448
+ async reviewSubmit(url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
449
+ signal.throwIfAborted()
450
+ return await this.publishReview(this.served(url).ref, request, signal)
451
+ }
452
+
453
+ /**
454
+ * Read the changes of a change request the review page shows, or of consecutive commits of it.
455
+ * @param url - web URL of the change request.
456
+ * @param commits - consecutive commits of the change request, or null for all of it.
457
+ * @param signal - request cancellation.
458
+ * @returns the files and the commit they end at, without a local checkout count.
459
+ * @throws as {@link ForgePanelController.changeRequestDiff} does, with `forgePanel/unrecognized-url` in place of
460
+ * `forgePanel/not-bound`.
461
+ */
462
+ @Remote
463
+ async reviewDiff(url: string, commits: ForgeCommitRange | null, signal: AbortSignal): Promise<ForgeChangeRequestDiff> {
464
+ signal.throwIfAborted()
465
+ return await this.readDiff(this.served(url), commits, signal, async () => await Promise.resolve(null))
466
+ }
467
+
468
+ /**
469
+ * List the commits of a change request the review page shows.
470
+ * @param url - web URL of the change request.
471
+ * @param signal - request cancellation.
472
+ * @returns the commits, or null when the provider does not read commits.
473
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-failed` when the host does
474
+ * not list them.
475
+ */
476
+ @Remote
477
+ async reviewCommits(url: string, signal: AbortSignal): Promise<ForgeCommitList | null> {
478
+ signal.throwIfAborted()
479
+ const list = await this.home.forge.commits(this.served(url).ref, signal)
480
+ if (list !== undefined && 'code' in list) throw readError(list)
481
+ return list ?? null
482
+ }
483
+
484
+ /**
485
+ * Read one file of a change request's repository at a commit for the review page.
486
+ * @param url - web URL of the change request.
487
+ * @param commit - commit object name.
488
+ * @param path - path relative to the repository root.
489
+ * @param signal - request cancellation.
490
+ * @returns the text.
491
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-too-large` or
492
+ * `forgePanel/diff-failed` when the host does not provide the file.
493
+ */
494
+ @Remote
495
+ async reviewText(url: string, commit: string, path: string, signal: AbortSignal): Promise<string> {
496
+ signal.throwIfAborted()
497
+ const text = await this.home.forge.fileText(this.served(url).ref, commit, path, signal)
498
+ if (typeof text !== 'string') throw readError(text)
499
+ return text
500
+ }
501
+
502
+ /**
503
+ * Read the signed-in user's viewed marks on the files of a change request the review page shows, as
504
+ * {@link ForgePanelController.changeRequestViewed} keeps them.
505
+ * @param url - web URL of the change request.
506
+ * @param headSha - head commit of the shown diff.
507
+ * @param fresh - whether to read the host although kept marks could answer, as after a refresh.
508
+ * @param signal - request cancellation.
509
+ * @returns the marks, or null when the provider keeps no viewed marks.
510
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or
511
+ * `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does.
512
+ */
513
+ @Remote
514
+ async reviewViewed(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
515
+ signal.throwIfAborted()
516
+ return await this.readViewed(this.served(url).ref, headSha, fresh, signal)
517
+ }
518
+
519
+ /**
520
+ * Set or clear the signed-in user's viewed mark on one file of a change request the review page shows.
521
+ * @param url - web URL of the change request.
522
+ * @param request - the file, its mark, and the head commit of the shown diff.
523
+ * @param signal - request cancellation.
524
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; the action errors of
525
+ * {@link ForgePanelController.setFileViewed}.
526
+ */
527
+ @Remote
528
+ async reviewSetViewed(url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise<void> {
529
+ signal.throwIfAborted()
530
+ await this.writeViewed(this.served(url).ref, request, signal)
531
+ }
532
+
533
+ /**
534
+ * Mark a draft change request the review page shows ready for review.
535
+ * @param url - web URL of the change request.
536
+ * @param signal - request cancellation.
537
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or
538
+ * `forgePanel/action-unknown` with the host's reason.
539
+ */
540
+ @Remote
541
+ async reviewMarkReady(url: string, signal: AbortSignal): Promise<void> {
542
+ signal.throwIfAborted()
543
+ const failure = await this.home.forge.markReady(this.served(url).ref, signal)
544
+ if (failure !== undefined) throw actionError(failure)
545
+ }
546
+
547
+ /**
548
+ * Merge a change request the review page shows while its head is still `headSha`.
549
+ * @param url - web URL of the change request.
550
+ * @param method - how the commits enter the base branch.
551
+ * @param headSha - head commit the user confirmed.
552
+ * @param signal - request cancellation.
553
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
554
+ * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
555
+ */
556
+ @Remote
557
+ async reviewMerge(url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void> {
558
+ signal.throwIfAborted()
559
+ const failure = await this.home.forge.merge(this.served(url).ref, { method, headSha }, signal)
560
+ if (failure !== undefined) throw actionError(failure)
561
+ }
562
+
563
+ /**
564
+ * Rerun the failed checks of a change request the review page shows.
565
+ * @param url - web URL of the change request.
566
+ * @param request - the head commit whose checks the user saw.
567
+ * @param signal - request cancellation.
568
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
569
+ * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
570
+ */
571
+ @Remote
572
+ async reviewRerunChecks(url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise<void> {
573
+ signal.throwIfAborted()
574
+ const failure = await this.home.forge.rerunChecks(this.served(url).ref, request, signal)
575
+ if (failure !== undefined) throw actionError(failure)
576
+ }
577
+
578
+ /**
579
+ * Request reviews of a change request the review page shows from more reviewers.
580
+ * @param url - web URL of the change request.
581
+ * @param reviewers - the reviewers to ask, by kind and login.
582
+ * @param signal - request cancellation.
583
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or
584
+ * `forgePanel/action-unknown` with the host's reason; an error without reviewers.
585
+ */
586
+ @Remote
587
+ async reviewRequestReviews(url: string, reviewers: readonly Pick<ChangeRequestReviewer, 'kind' | 'login'>[], signal: AbortSignal): Promise<void> {
588
+ signal.throwIfAborted()
589
+ await this.askReviews(this.served(url).ref, reviewers, signal)
590
+ }
591
+
592
+ /**
593
+ * List accounts a review of a change request the review page shows can be requested from.
594
+ * @param url - web URL of the change request.
595
+ * @param query - text the login or name contains; empty for the host's suggestions.
596
+ * @param signal - request cancellation.
597
+ * @returns the accounts, the host's suggestions first.
598
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/reviewers-failed` when the host
599
+ * does not list them.
600
+ */
601
+ @Remote
602
+ async reviewReviewerCandidates(url: string, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[]> {
603
+ signal.throwIfAborted()
604
+ return await this.candidatesOf(this.served(url).ref, query, signal)
605
+ }
606
+
607
+ /**
608
+ * Bring the base branch's new commits into the head branch of a change request the review page shows.
609
+ * @param url - web URL of the change request.
610
+ * @param method - merge or rebase.
611
+ * @param headSha - head commit the user confirmed.
612
+ * @param signal - request cancellation.
613
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
614
+ * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
615
+ */
616
+ @Remote
617
+ async reviewUpdateBranch(url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise<void> {
618
+ signal.throwIfAborted()
619
+ const failure = await this.home.forge.updateBranch(this.served(url).ref, { method, headSha }, signal)
620
+ if (failure !== undefined) throw actionError(failure)
621
+ }
622
+
623
+ /**
624
+ * Remember the change request a review conversation's draft quotes, or forget it with null. When the Session's next
625
+ * message enters its inbox, the change request is bound to the Session with a `track` record before the turn starts;
626
+ * a Session that already started is bound at its next message. The choice lives in memory until then.
627
+ * @param sessionId - the Session whose draft quotes the change request; staging neither loads nor resumes it.
628
+ * @param url - web URL of the change request, or null.
629
+ * @param signal - request cancellation.
630
+ * @throws `forgePanel/unrecognized-url` when no provider serves the URL.
631
+ */
632
+ @Remote
633
+ // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect
634
+ async reviewStage(sessionId: SessionId, url: string | null, signal: AbortSignal): Promise<void> {
635
+ signal.throwIfAborted()
636
+ if (url === null) {
637
+ this.staged.delete(sessionId)
638
+ return
639
+ }
640
+ this.served(url)
641
+ this.staged.set(sessionId, url)
642
+ }
643
+
203
644
  /**
204
645
  * Read or await the worktree service's archive cleanup of the Session's checkout.
205
- * @param session - Session whose cleanup is visible to the caller.
646
+ * @param sessionId - Session whose cleanup is visible to the caller; reading neither loads nor resumes it.
206
647
  * @param revision - null reads now; a matching revision waits for completion.
207
648
  * @returns the cleanup state, or null without a worktree service, an attempt, or a current revision.
208
649
  */
209
650
  @Remote
210
- async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null> {
211
- return await this.home.get('worktrees')?.cleanupOf(session, revision) ?? null
651
+ async worktreeCleanup(sessionId: SessionId, revision: number | null): Promise<WorktreeCleanup | null> {
652
+ return await this.home.get('worktrees')?.cleanupOf(sessionId, revision) ?? null
212
653
  }
213
654
 
214
655
  /**
215
- * List the local branches that can start a worktree of the Session's current checkout.
216
- * @param session - Session whose current directory is listed.
656
+ * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each
657
+ * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the
658
+ * order the panel recognizes code hosts.
659
+ * @param session - Session whose checkout is read.
660
+ * @param query - text the branch names must contain, ignoring case; empty for every branch.
217
661
  * @param signal - request cancellation.
218
- * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first.
219
- * @throws when the current directory is not inside a checkout or Git fails.
662
+ * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.
663
+ * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
220
664
  */
221
665
  @Remote
222
- async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches> {
223
- return await listBranches(this.home, this.config, session, this.home.workingDirectory.get(session), this.config.maxBranches, signal)
666
+ async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases> {
667
+ signal.throwIfAborted()
668
+ const inspection = await this.checkoutOf(session, signal)
669
+ // A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output.
670
+ const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
671
+ const refs = await git('worktree-bases', ['for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES])
672
+ return parseWorktreeBases(refs.stdout, inspection.checkout.branch, remoteOrder(inspection.upstream, inspection.remotes), query,
673
+ this.config.maxBranches, remote => remoteRepository(remote, url => this.home.forge.repositoryFromRemote(url)))
224
674
  }
225
675
 
226
676
  /**
@@ -273,14 +723,29 @@ export class ForgePanelController extends TypertRemoteService {
273
723
  /**
274
724
  * Reinspect a followed Session's checkout, probe sign-in again, and poll its
275
725
  * change requests at once; an unfollowed Session is unchanged.
276
- * @param session - Session whose panel refreshes.
726
+ * @param sessionId - Session whose panel refreshes; refreshing neither loads nor resumes it.
277
727
  * @param signal - request cancellation.
278
728
  * @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
279
729
  */
280
730
  @Remote
281
- async refresh(session: Session, signal: AbortSignal): Promise<void> {
731
+ async refresh(sessionId: SessionId, signal: AbortSignal): Promise<void> {
282
732
  signal.throwIfAborted()
283
- await this.panels.get(session)?.refresh()
733
+ for (const [session, panel] of this.panels) if (session.id === sessionId) await panel.refresh()
734
+ }
735
+
736
+ /**
737
+ * Bring a followed Session's panel up to date after its surface showed again: reinspect the checkout, poll the
738
+ * change requests whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found
739
+ * the host ready, and look the upstream branch up again while the Session shows no change request; an unfollowed
740
+ * Session is unchanged.
741
+ * @param sessionId - Session whose panel is revisited; revisiting neither loads nor resumes it.
742
+ * @param signal - request cancellation.
743
+ * @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
744
+ */
745
+ @Remote
746
+ async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void> {
747
+ signal.throwIfAborted()
748
+ for (const [session, panel] of this.panels) if (session.id === sessionId) await panel.revisit()
284
749
  }
285
750
 
286
751
  /**
@@ -363,11 +828,7 @@ export class ForgePanelController extends TypertRemoteService {
363
828
  @Remote
364
829
  async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ChangeRequestSnapshot> {
365
830
  signal.throwIfAborted()
366
- const result = await this.home.forge.fetchChecks(this.bound(session, url).ref, signal)
367
- this.bound(session, url)
368
- if ('code' in result) throw new RemoteError('forgePanel/checks-failed', result.message, {})
369
- if (result.headSha !== headSha) throw new RemoteError('forgePanel/stale-head', 'The change request head changed; refresh its status', {})
370
- return result
831
+ return await this.readChecks(this.bound(session, url).ref, headSha, signal, () => { this.bound(session, url) })
371
832
  }
372
833
 
373
834
  /**
@@ -414,31 +875,14 @@ export class ForgePanelController extends TypertRemoteService {
414
875
  session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal,
415
876
  ): Promise<ForgeChangeRequestDiff> {
416
877
  signal.throwIfAborted()
417
- const { ref, update } = this.bound(session, url)
418
- if (update === null || !('snapshot' in update)) {
419
- throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {})
420
- }
421
- if (commits !== null) return await this.commitsDiff(ref, commits, signal)
422
- const { headSha, headBranch, baseBranch } = update.snapshot
423
- const key = changeRequestKey(ref)
424
- const version = JSON.stringify([headSha, baseBranch])
425
- let read = this.patches.get(key, version)
426
- if (read === undefined) {
427
- read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal)
428
- this.patches.set(key, version, read)
429
- }
430
- const files = this.layers.classify(parseDiff(read.patch), read.attributes)
431
- let localAhead: number | null = null
432
- try {
433
- localAhead = await aheadOf(
434
- gitIn(this.home, this.config, session, this.home.workingDirectory.get(session), signal), headBranch, headSha,
435
- )
436
- } catch (_error) {
437
- // The count only adds a notice; without Git the view still shows the host's diff.
438
- }
439
- signal.throwIfAborted()
440
- const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, headSha, file.path)]))
441
- return { headSha, files, localAhead, fileUrls }
878
+ return await this.readDiff(this.bound(session, url), commits, signal, async (headBranch, headSha) => {
879
+ try {
880
+ return await aheadOf(gitIn(this.home, this.config, session, this.home.workingDirectory.get(session), signal), headBranch, headSha)
881
+ } catch (_error) {
882
+ // The count only adds a notice; without Git the view still shows the host's diff.
883
+ return null
884
+ }
885
+ })
442
886
  }
443
887
 
444
888
  /**
@@ -462,12 +906,95 @@ export class ForgePanelController extends TypertRemoteService {
462
906
  return text
463
907
  }
464
908
 
909
+ /**
910
+ * Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending
911
+ * the registration aborts its running classifications and waits for them.
912
+ * @param lens - the lens.
913
+ * @returns the disposer that unregisters the lens and waits for its classifications to stop.
914
+ * @throws when another registration holds `lens.id`.
915
+ */
916
+ registerLens(lens: ForgeLens): () => Promise<void> {
917
+ const dispose = this.ctx.effect(() => this.lenses.add(lens), 'forge-panel: lens')
918
+ return async () => { await dispose() }
919
+ }
920
+
921
+ /**
922
+ * Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts
923
+ * after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops.
924
+ * @param signal - ends the stream.
925
+ * @returns the registered lenses and the annotation limit, in publication order.
926
+ */
927
+ @Remote({ mode: 'stream' })
928
+ async *extensions(signal: AbortSignal): AsyncIterable<ForgeExtensionState> {
929
+ for await (const lenses of this.lenses.follow(signal)) yield { lenses, maxAnnotationsPerFile: this.config.maxAnnotationsPerFile }
930
+ }
931
+
932
+ /**
933
+ * Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens
934
+ * runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until
935
+ * `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files
936
+ * are those `changeRequestDiff` reads.
937
+ * @param session - Session whose checkout or binding the view shows.
938
+ * @param request - the view's source, the version of the files it shows, and the lens.
939
+ * @param signal - ends the classification.
940
+ * @returns progress frames, then one result frame.
941
+ * @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends;
942
+ * `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and
943
+ * when local files changed while the lens ran;
944
+ * `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers
945
+ * over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files.
946
+ */
947
+ @Remote({ mode: 'stream' })
948
+ async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable<ForgeLensFrame> {
949
+ signal.throwIfAborted()
950
+ const registration = this.lenses.get(request.lens)
951
+ if (registration === undefined) throw new RemoteError('forgePanel/lens-missing', `No lens "${request.lens}" is registered`, {})
952
+ const subject = await this.lensSubject(session, request.source, signal)
953
+ // The registration may have ended while the files were read; its lens neither runs nor answers from memory then.
954
+ signal.throwIfAborted()
955
+ if (registration.lifetime.aborted) throw new RemoteError('forgePanel/lens-missing', `No lens "${request.lens}" is registered`, {})
956
+ if (lensVersion(subject.files) !== request.version) {
957
+ throw new RemoteError('forgePanel/lens-stale', 'The changes were read again since the view showed them', {})
958
+ }
959
+ const key = JSON.stringify([subject.key, request.version, request.lens, registration.lens.version])
960
+ const kept = this.lensResults.get(key)
961
+ if (kept !== undefined) {
962
+ yield { kind: 'result', files: kept }
963
+ return
964
+ }
965
+ const limits = {
966
+ timeoutMs: this.config.lensTimeoutMs, maxReadBytes: this.config.maxLensReadBytes, maxResultBytes: this.config.maxCachedLensBytes,
967
+ }
968
+ try {
969
+ for await (const frame of lensFrames(progress => runLens(registration, subject, limits, signal, progress))) {
970
+ if (frame.kind === 'result') {
971
+ // Local files can change while the lens reads them; a result about other contents is neither kept nor sent.
972
+ if (request.source.kind === 'local') {
973
+ const now = await this.lensSubject(session, request.source, signal)
974
+ if (lensVersion(now.files) !== request.version) {
975
+ throw new RemoteError('forgePanel/lens-stale', 'The changes moved while the lens read them', {})
976
+ }
977
+ }
978
+ this.lensResults.set(key, frame.files)
979
+ }
980
+ yield frame
981
+ }
982
+ } catch (error) {
983
+ if (error instanceof LensWithdrawn) throw new RemoteError('forgePanel/lens-missing', error.message, {})
984
+ if (error instanceof LensFailed) throw new RemoteError('forgePanel/lens-failed', error.message, {})
985
+ throw error
986
+ }
987
+ }
988
+
465
989
  /**
466
990
  * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
467
- * whole change request.
991
+ * whole change request. Marks read at the same head are kept in memory and returned until they are `reviewRefreshMs`
992
+ * old or `maxCachedReviewBytes` evicts them; a mark saved through `ctx.forge` at that head replaces the kept state
993
+ * of its file, so the read after a save costs no request.
468
994
  * @param session - Session the change request is bound to.
469
995
  * @param url - binding URL of the change request.
470
996
  * @param headSha - head commit of the shown diff; marks read at another head are refused.
997
+ * @param fresh - whether to read the host although kept marks could answer, as after a refresh.
471
998
  * @param signal - request cancellation.
472
999
  * @returns the marks at `headSha`, or null when the provider keeps no viewed marks.
473
1000
  * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
@@ -475,14 +1002,11 @@ export class ForgePanelController extends TypertRemoteService {
475
1002
  * when the host does not provide the marks otherwise.
476
1003
  */
477
1004
  @Remote
478
- async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
1005
+ async changeRequestViewed(
1006
+ session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal,
1007
+ ): Promise<ForgeViewedFiles | null> {
479
1008
  signal.throwIfAborted()
480
- const result = await this.home.forge.viewedFiles(this.bound(session, url).ref, headSha, signal)
481
- if (result === undefined) return null
482
- if ('code' in result) {
483
- throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {})
484
- }
485
- return result
1009
+ return await this.readViewed(this.bound(session, url).ref, headSha, fresh, signal)
486
1010
  }
487
1011
 
488
1012
  /**
@@ -499,10 +1023,7 @@ export class ForgePanelController extends TypertRemoteService {
499
1023
  @Remote
500
1024
  async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise<void> {
501
1025
  signal.throwIfAborted()
502
- const { ref } = this.bound(session, url)
503
- if (request.path === '') throw new Error('Invalid viewed file')
504
- const failure = await this.home.forge.setViewed(ref, request, signal)
505
- if (failure !== undefined) throw actionError(failure)
1026
+ await this.writeViewed(this.bound(session, url).ref, request, signal)
506
1027
  }
507
1028
 
508
1029
  /**
@@ -526,23 +1047,7 @@ export class ForgePanelController extends TypertRemoteService {
526
1047
  @Remote
527
1048
  async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData> {
528
1049
  signal.throwIfAborted()
529
- const { ref, update } = this.bound(session, url)
530
- if (update === null || !('snapshot' in update)) {
531
- throw new RemoteError('forgePanel/review-failed', 'The change request status has not been read yet', {})
532
- }
533
- if (update.snapshot.headSha !== headSha) {
534
- throw new RemoteError('forgePanel/stale-head', `The change request head moved from ${headSha} to ${update.snapshot.headSha}`, {})
535
- }
536
- const key = changeRequestKey(ref)
537
- const version = JSON.stringify([headSha, update.snapshot.updatedAt])
538
- const readAt = Date.now()
539
- const kept = fresh ? undefined : this.reviews.get(key, version, readAt)
540
- if (kept !== undefined) return kept
541
- const token = this.reviews.token()
542
- const review = await this.home.forge.readReview(ref, headSha, signal)
543
- if ('code' in review) throw reviewError(review)
544
- this.reviews.set(key, version, review, readAt, token)
545
- return review
1050
+ return await this.readThreads(this.bound(session, url), headSha, fresh, signal)
546
1051
  }
547
1052
 
548
1053
  /**
@@ -557,16 +1062,7 @@ export class ForgePanelController extends TypertRemoteService {
557
1062
  @Remote
558
1063
  async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
559
1064
  signal.throwIfAborted()
560
- const { ref } = this.bound(session, url)
561
- if (!isCommit(request.headSha)) throw new Error('Invalid review commit')
562
- const comments = request.kind === 'comment' ? [request.comment] : request.comments
563
- if (!comments.every(validComment)) throw new Error('Invalid review comment')
564
- if (request.kind === 'review' && request.event !== 'approve' && request.body.trim() === '' && comments.length === 0) throw new Error('Empty review')
565
- try {
566
- return await this.home.forge.submitReview(ref, request, signal)
567
- } finally {
568
- this.reviews.drop(changeRequestKey(ref))
569
- }
1065
+ return await this.publishReview(this.bound(session, url).ref, request, signal)
570
1066
  }
571
1067
 
572
1068
  /**
@@ -587,14 +1083,7 @@ export class ForgePanelController extends TypertRemoteService {
587
1083
  session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal,
588
1084
  ): Promise<ForgeReviewWriteResult> {
589
1085
  signal.throwIfAborted()
590
- const { ref } = this.bound(session, url)
591
- if (!isCommit(write.headSha)) throw new Error('Invalid review commit')
592
- if (!validWrite(write)) throw new Error('Invalid review write')
593
- try {
594
- return await this.home.forge.writeReview(ref, write, signal)
595
- } finally {
596
- this.reviews.drop(changeRequestKey(ref))
597
- }
1086
+ return await this.writeThreads(this.bound(session, url).ref, write, signal)
598
1087
  }
599
1088
 
600
1089
  /**
@@ -667,10 +1156,7 @@ export class ForgePanelController extends TypertRemoteService {
667
1156
  session: Session, url: string, reviewers: readonly Pick<ChangeRequestReviewer, 'kind' | 'login'>[], signal: AbortSignal,
668
1157
  ): Promise<void> {
669
1158
  signal.throwIfAborted()
670
- const { ref } = this.bound(session, url)
671
- if (reviewers.length === 0 || reviewers.some(reviewer => reviewer.login.trim() === '')) throw new Error('Invalid reviewers')
672
- const failure = await this.home.forge.requestReviews(ref, { reviewers }, signal)
673
- if (failure !== undefined) throw actionError(failure)
1159
+ await this.askReviews(this.bound(session, url).ref, reviewers, signal)
674
1160
  }
675
1161
 
676
1162
  /**
@@ -686,9 +1172,7 @@ export class ForgePanelController extends TypertRemoteService {
686
1172
  @Remote
687
1173
  async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[]> {
688
1174
  signal.throwIfAborted()
689
- const result = await this.home.forge.reviewerCandidates(this.bound(session, url).ref, query, signal)
690
- if ('code' in result) throw new RemoteError('forgePanel/reviewers-failed', result.message, {})
691
- return result
1175
+ return await this.candidatesOf(this.bound(session, url).ref, query, signal)
692
1176
  }
693
1177
 
694
1178
  /**
@@ -714,24 +1198,34 @@ export class ForgePanelController extends TypertRemoteService {
714
1198
  /**
715
1199
  * Ask for a new worktree before the Session's first turn, replacing an open
716
1200
  * request and forgetting a failed attempt. While the next message waits in
717
- * the inbox, or else at the first step proposal, the panel creates a branch
718
- * from `from`, or from HEAD of the current checkout when it is null, and
719
- * enters its checkout. A message that already waits after a failed or
720
- * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}.
1201
+ * the inbox, or else at the first step proposal, the panel creates the
1202
+ * branch `name`, or a generated branch per attempt when it is null, from
1203
+ * `from`, or from HEAD of the current checkout when it is null, and enters
1204
+ * its checkout; a remote-tracking `from` is fetched first. A message that
1205
+ * already waits after a failed or stopped attempt keeps waiting for
1206
+ * {@link ForgePanelController.retryWorktree}.
721
1207
  * @param session - Session without a started turn.
722
- * @param from - local base branch, or null for HEAD.
1208
+ * @param from - full name of a local or remote-tracking base branch, or null for HEAD.
1209
+ * @param name - new branch name, or null to generate one per attempt.
723
1210
  * @param signal - request cancellation.
724
- * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable`
1211
+ * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks
1212
+ * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`;
1213
+ * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable`
725
1214
  * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was
726
1215
  * created; `forgePanel/session-busy` while the worktree is being created.
727
1216
  */
728
1217
  @Remote
729
- async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void> {
1218
+ async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise<void> {
730
1219
  signal.throwIfAborted()
731
1220
  if (from?.length === 0) throw new RemoteError('forgePanel/invalid-branch', 'The base branch name is empty', {})
732
1221
  this.editableWorktree(session)
1222
+ if (name !== null) {
1223
+ await this.checkBranchName(session, name, signal)
1224
+ // The Session may have started or begun a creation while Git answered.
1225
+ this.editableWorktree(session)
1226
+ }
733
1227
  this.creations.forget(session)
734
- appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from })
1228
+ appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from, ...name === null ? {} : { name } })
735
1229
  this.creations.recheck(session)
736
1230
  }
737
1231
 
@@ -767,16 +1261,19 @@ export class ForgePanelController extends TypertRemoteService {
767
1261
  }
768
1262
 
769
1263
  /**
770
- * Make another attempt, with a new branch name, at the worktree a message
771
- * of the Session waits for after a failed or stopped attempt.
1264
+ * Make another attempt, on the requested branch name or a new generated
1265
+ * one, at the worktree a message of the Session waits for after a failed or
1266
+ * stopped attempt.
772
1267
  * @param session - Session whose message waits.
1268
+ * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the
1269
+ * commit last fetched.
773
1270
  * @param signal - request cancellation.
774
1271
  * @throws `forgePanel/not-waiting` when no message waits or an attempt is running.
775
1272
  */
776
1273
  @Remote
777
- async retryWorktree(session: Session, signal: AbortSignal): Promise<void> {
1274
+ async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise<void> {
778
1275
  signal.throwIfAborted()
779
- if (!this.creations.retry(session)) {
1276
+ if (!this.creations.retry(session, fetch)) {
780
1277
  throw new RemoteError('forgePanel/not-waiting', 'No message waits for another attempt at the worktree', {})
781
1278
  }
782
1279
  }
@@ -837,14 +1334,17 @@ export class ForgePanelController extends TypertRemoteService {
837
1334
  /* oxlint-enable typescript/require-await */
838
1335
 
839
1336
  /**
840
- * Hold the turn of a message entering a Session's inbox while the
1337
+ * Hold the turn of a message entering a Session's next-turn queue while the
841
1338
  * Session's requested worktree does not exist yet, or while the worktree
842
1339
  * the Session works in is checked and, when gone, until it is restored or
843
1340
  * left. The message is entering, so the delivery has not woken the Agent
844
- * yet and its wake waits for the hold.
1341
+ * yet and its wake waits for the hold. A message for the next step, such as
1342
+ * a notice another plugin queues, opens no turn and gets no hold.
845
1343
  * @param agent - Agent whose inbox receives the message.
1344
+ * @param message - the entering message.
846
1345
  */
847
- private holdTurn(agent: Agent): void {
1346
+ private holdTurn(agent: Agent, message: UserMessage): void {
1347
+ if (!agent.inbox.nextTurn.some(queued => queued.id === message.id)) return
848
1348
  const session = agent.session
849
1349
  const state = this.worktreeState(session)
850
1350
  if (state.request !== null && state.created === null && !state.locked) {
@@ -870,8 +1370,23 @@ export class ForgePanelController extends TypertRemoteService {
870
1370
  return this.home.workingDirectory.get(session) === directory ? missing : null
871
1371
  }
872
1372
 
873
- /** The changes of consecutive commits of a change request, from the first one's first parent to the last. */
874
- private async commitsDiff(ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal): Promise<ForgeChangeRequestDiff> {
1373
+ /** The files of a change request at the head a status recorded, read once per head and base branch while the cache keeps them. */
1374
+ private async headFiles(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise<ForgeDiffFile[]> {
1375
+ const { headSha, baseBranch } = snapshot
1376
+ const key = changeRequestKey(ref)
1377
+ const version = JSON.stringify([headSha, baseBranch])
1378
+ let read = this.patches.get(key, version)
1379
+ if (read === undefined) {
1380
+ read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal)
1381
+ this.patches.set(key, version, read)
1382
+ }
1383
+ return this.layers.classify(parseDiff(read.patch), read.attributes)
1384
+ }
1385
+
1386
+ /** The files of consecutive commits of a change request, from the first one's first parent, which is returned too, to the last. */
1387
+ private async commitFiles(
1388
+ ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal,
1389
+ ): Promise<{ readonly files: ForgeDiffFile[]; readonly parent: string }> {
875
1390
  const list = await this.home.forge.commits(ref, signal)
876
1391
  if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {})
877
1392
  if ('code' in list) throw readError(list)
@@ -883,9 +1398,7 @@ export class ForgePanelController extends TypertRemoteService {
883
1398
  const { patch, attributes } = await this.patchAt(
884
1399
  ref, commits.to, async operation => await this.home.forge.compare(ref, parent, commits.to, operation), signal,
885
1400
  )
886
- const files = this.layers.classify(parseDiff(patch), attributes)
887
- const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)]))
888
- return { headSha: commits.to, files, localAhead: null, fileUrls }
1401
+ return { files: this.layers.classify(parseDiff(patch), attributes), parent }
889
1402
  }
890
1403
 
891
1404
  /**
@@ -930,6 +1443,137 @@ export class ForgePanelController extends TypertRemoteService {
930
1443
  return inspection
931
1444
  }
932
1445
 
1446
+ /** Read every check of a change request, refusing a list read at another head; `recheck` runs once the host answers. */
1447
+ private async readChecks(
1448
+ ref: ChangeRequestRef, headSha: string, signal: AbortSignal, recheck: () => void,
1449
+ ): Promise<ChangeRequestSnapshot> {
1450
+ const result = await this.home.forge.fetchChecks(ref, signal)
1451
+ recheck()
1452
+ if ('code' in result) throw new RemoteError('forgePanel/checks-failed', result.message, {})
1453
+ if (result.headSha !== headSha) throw new RemoteError('forgePanel/stale-head', 'The change request head changed; refresh its status', {})
1454
+ return result
1455
+ }
1456
+
1457
+ /** Read the changes of a change request at the head of its latest status, or of chosen commits; `ahead` counts local commits. */
1458
+ private async readDiff(
1459
+ target: ChangeRequestTarget, commits: ForgeCommitRange | null, signal: AbortSignal,
1460
+ ahead: (headBranch: string, headSha: string) => Promise<number | null>,
1461
+ ): Promise<ForgeChangeRequestDiff> {
1462
+ const { ref, update } = target
1463
+ if (update === null || !('snapshot' in update)) {
1464
+ throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {})
1465
+ }
1466
+ if (commits !== null) {
1467
+ const { files } = await this.commitFiles(ref, commits, signal)
1468
+ const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)]))
1469
+ return { headSha: commits.to, files, localAhead: null, fileUrls }
1470
+ }
1471
+ const { headSha, headBranch } = update.snapshot
1472
+ const files = await this.headFiles(ref, update.snapshot, signal)
1473
+ const localAhead = await ahead(headBranch, headSha)
1474
+ signal.throwIfAborted()
1475
+ const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, headSha, file.path)]))
1476
+ return { headSha, files, localAhead, fileUrls }
1477
+ }
1478
+
1479
+ /** Read the viewed marks at a head commit, reusing marks kept for that head unless `fresh`. */
1480
+ private async readViewed(ref: ChangeRequestRef, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
1481
+ const key = changeRequestKey(ref)
1482
+ const readAt = Date.now()
1483
+ const kept = fresh ? undefined : this.viewed.get(key, headSha, readAt)
1484
+ if (kept !== undefined) return kept
1485
+ const token = this.viewed.token()
1486
+ const result = await this.home.forge.viewedFiles(ref, headSha, signal)
1487
+ if (result === undefined) return null
1488
+ if ('code' in result) throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {})
1489
+ this.viewed.set(key, headSha, result, readAt, token)
1490
+ return result
1491
+ }
1492
+
1493
+ /** Set or clear a viewed mark. */
1494
+ private async writeViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise<void> {
1495
+ if (request.path === '') throw new Error('Invalid viewed file')
1496
+ const failure = await this.home.forge.setViewed(ref, request, signal)
1497
+ if (failure !== undefined) throw actionError(failure)
1498
+ }
1499
+
1500
+ /** Read the review threads at the head of the latest status, reusing threads kept for that head and update time. */
1501
+ private async readThreads(target: ChangeRequestTarget, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData> {
1502
+ const { ref, update } = target
1503
+ if (update === null || !('snapshot' in update)) {
1504
+ throw new RemoteError('forgePanel/review-failed', 'The change request status has not been read yet', {})
1505
+ }
1506
+ if (update.snapshot.headSha !== headSha) {
1507
+ throw new RemoteError('forgePanel/stale-head', `The change request head moved from ${headSha} to ${update.snapshot.headSha}`, {})
1508
+ }
1509
+ const key = changeRequestKey(ref)
1510
+ const version = JSON.stringify([headSha, update.snapshot.updatedAt])
1511
+ const readAt = Date.now()
1512
+ const kept = fresh ? undefined : this.reviews.get(key, version, readAt)
1513
+ if (kept !== undefined) return kept
1514
+ const token = this.reviews.token()
1515
+ const review = await this.home.forge.readReview(ref, headSha, signal)
1516
+ if ('code' in review) throw reviewError(review)
1517
+ this.reviews.set(key, version, review, readAt, token)
1518
+ return review
1519
+ }
1520
+
1521
+ /** Publish a comment or a completed review, then drop the threads kept for the change request. */
1522
+ private async publishReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
1523
+ if (!isCommit(request.headSha)) throw new Error('Invalid review commit')
1524
+ const comments = request.kind === 'comment' ? [request.comment] : request.comments
1525
+ if (!comments.every(validComment)) throw new Error('Invalid review comment')
1526
+ if (request.kind === 'review' && request.event !== 'approve' && request.body.trim() === '' && comments.length === 0) throw new Error('Empty review')
1527
+ try {
1528
+ return await this.home.forge.submitReview(ref, request, signal)
1529
+ } finally {
1530
+ this.reviews.drop(changeRequestKey(ref))
1531
+ }
1532
+ }
1533
+
1534
+ /** Write to the review threads or the pending review, then drop the threads kept for the change request. */
1535
+ private async writeThreads(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult> {
1536
+ if (!isCommit(write.headSha)) throw new Error('Invalid review commit')
1537
+ if (!validWrite(write)) throw new Error('Invalid review write')
1538
+ try {
1539
+ return await this.home.forge.writeReview(ref, write, signal)
1540
+ } finally {
1541
+ this.reviews.drop(changeRequestKey(ref))
1542
+ }
1543
+ }
1544
+
1545
+ /** The change request a review page URL names, with its latest polling result. */
1546
+ /** Request reviews of a change request from the given accounts, refusing an empty list or an empty login. */
1547
+ private async askReviews(
1548
+ ref: ChangeRequestRef, reviewers: readonly Pick<ChangeRequestReviewer, 'kind' | 'login'>[], signal: AbortSignal,
1549
+ ): Promise<void> {
1550
+ if (reviewers.length === 0 || reviewers.some(reviewer => reviewer.login.trim() === '')) throw new Error('Invalid reviewers')
1551
+ const failure = await this.home.forge.requestReviews(ref, { reviewers }, signal)
1552
+ if (failure !== undefined) throw actionError(failure)
1553
+ }
1554
+
1555
+ /** List accounts a review of a change request can be requested from, failing with the host's reason. */
1556
+ private async candidatesOf(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[]> {
1557
+ const result = await this.home.forge.reviewerCandidates(ref, query, signal)
1558
+ if ('code' in result) throw new RemoteError('forgePanel/reviewers-failed', result.message, {})
1559
+ return result
1560
+ }
1561
+
1562
+ private served(url: string): ChangeRequestTarget {
1563
+ const ref = this.home.forge.changeRequestFromUrl(url)
1564
+ if (ref === undefined) throw new RemoteError('forgePanel/unrecognized-url', 'No provider serves this change request URL', {})
1565
+ return { ref, update: this.home.forge.latest(ref) ?? null }
1566
+ }
1567
+
1568
+ /** Bind the change request a review conversation staged once the Session's message enters its inbox. */
1569
+ private bindStaged(session: Session): void {
1570
+ const url = this.staged.get(session.id)
1571
+ if (url === undefined) return
1572
+ this.staged.delete(session.id)
1573
+ // A provider withdrawn since the draft was staged leaves the message unbound.
1574
+ if (this.home.forge.changeRequestFromUrl(url) !== undefined) this.home.forgeSession.track(session, url)
1575
+ }
1576
+
933
1577
  /** A visible binding of the Session that a provider serves, which actions and reads are limited to. */
934
1578
  private bound(session: Session, url: string): SessionChangeRequest & { readonly ref: NonNullable<SessionChangeRequest['ref']> } {
935
1579
  const entry = this.home.forgeSession.changeRequests(session).find(candidate => candidate.url === url)
@@ -941,6 +1585,18 @@ export class ForgePanelController extends TypertRemoteService {
941
1585
  return this.worktreeStates.stateOf(session)
942
1586
  }
943
1587
 
1588
+ /**
1589
+ * Refuse a new branch name that breaks a branch-name rule or names a local branch of the Session's checkout. The
1590
+ * rules cover every name `git check-ref-format` refuses, which the worktree service runs again at creation.
1591
+ */
1592
+ private async checkBranchName(session: Session, name: string, signal: AbortSignal): Promise<void> {
1593
+ if (branchNameProblem(name) !== null) throw new RemoteError('forgePanel/invalid-name', 'The new branch name is invalid', {})
1594
+ const root = (await this.checkoutOf(session, signal)).checkout.root
1595
+ if (await hasBranch(this.home, this.config, session, root, name, signal)) {
1596
+ throw new RemoteError('forgePanel/branch-exists', `A local branch named ${name} exists`, {})
1597
+ }
1598
+ }
1599
+
944
1600
  private editableWorktree(session: Session): ForgeWorktreeState {
945
1601
  if (this.home.get('worktrees') === undefined) {
946
1602
  throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {})
@@ -1010,7 +1666,7 @@ export class ForgePanelController extends TypertRemoteService {
1010
1666
  if (key === 'forgeChangeRequests') listener(session.id, visibleUrls(session))
1011
1667
  }),
1012
1668
  refOf: url => ctx.forge.changeRequestFromUrl(url),
1013
- watch: (ref, listener) => ctx.forge.watch(ref, listener),
1669
+ watch: (ref, listener, known) => ctx.forge.watchBrief(ref, listener, known),
1014
1670
  open: async () => {
1015
1671
  const domain = await storage.open(changeRequestStatesDomain)
1016
1672
  return { table: domain.table('states'), close: () => domain.close() }
@@ -1020,14 +1676,121 @@ export class ForgePanelController extends TypertRemoteService {
1020
1676
  return this.states
1021
1677
  }
1022
1678
 
1679
+ /**
1680
+ * Bring what is kept for a change request up to date after an accepted review change, and let its panel entries
1681
+ * report it: a saved viewed mark replaces the kept state of its file, which a host lists for every changed file, and
1682
+ * leaves the kept threads; any other change drops the kept threads.
1683
+ */
1684
+ private reviewChanged(ref: ChangeRequestRef, change: ForgeReviewChange): void {
1685
+ const key = changeRequestKey(ref)
1686
+ switch (change.kind) {
1687
+ case 'viewed': {
1688
+ const { path, viewed } = change
1689
+ this.viewed.amend(key, change.headSha, marks => path in marks.files
1690
+ ? { ...marks, files: { ...marks.files, [path]: viewed ? 'viewed' : 'unviewed' } } : marks)
1691
+ break
1692
+ }
1693
+ case 'write':
1694
+ case 'submit':
1695
+ this.reviews.drop(key)
1696
+ break
1697
+ /* v8 ignore next -- closed ForgeReviewChange kind union exhaustiveness guard */
1698
+ default: assertNever(change, 'ForgeReviewChange.kind')
1699
+ }
1700
+ this.reviewRevisions.set(key, (this.reviewRevisions.get(key) ?? 0) + 1)
1701
+ for (const panel of this.panels.values()) panel.reviewChanged()
1702
+ for (const follower of this.reviewFollowers) if (follower.key === key) follower.emit()
1703
+ }
1704
+
1705
+ /** The files a lens request names with their reader and the key results for them are kept under. */
1706
+ private async lensSubject(
1707
+ session: Session, source: ForgeLensRequest['source'], signal: AbortSignal,
1708
+ ): Promise<LensSubject & { readonly key: string }> {
1709
+ if (source.kind === 'local') {
1710
+ const inspection = await this.checkoutOf(session, signal)
1711
+ const root = inspection.checkout.root
1712
+ const { scope } = source
1713
+ const fork: ForkPoint | null = scope.kind !== 'branch' ? null : await diffing(scope.base === null
1714
+ ? forkPoint(gitIn(this.home, this.config, session, root, signal), inspection, this.worktreeState(session).created)
1715
+ : chosenForkPoint(gitIn(this.home, this.config, session, root, signal), scope.base))
1716
+ const { files } = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal))
1717
+ return {
1718
+ key: JSON.stringify(['local', session.id, scope]),
1719
+ source: { kind: 'local', scope },
1720
+ files,
1721
+ read: async (side, file, inner) => {
1722
+ if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null
1723
+ return side === 'new'
1724
+ ? await diffing(localText(this.home, this.config, session, root, scope, file.path, inner))
1725
+ : await diffing(localOldText(this.home, this.config, session, root, scope, fork, file.previousPath ?? file.path, inner))
1726
+ },
1727
+ }
1728
+ }
1729
+ const { ref, update } = this.bound(session, source.url)
1730
+ if (update === null || !('snapshot' in update)) {
1731
+ throw new RemoteError('forgePanel/lens-stale', 'The change request status has not been read yet', {})
1732
+ }
1733
+ const { snapshot } = update
1734
+ const { commits } = source
1735
+ let files: ForgeDiffFile[]
1736
+ let newCommit: string
1737
+ let oldCommit: (inner: AbortSignal) => Promise<string>
1738
+ if (commits === null) {
1739
+ files = await this.headFiles(ref, snapshot, signal)
1740
+ newCommit = snapshot.headSha
1741
+ // One merge base serves every old side of the run; a failed lookup is tried again by the next read.
1742
+ let base: Promise<string> | undefined
1743
+ oldCommit = async (inner) => {
1744
+ base ??= this.mergeBaseOf(ref, snapshot, inner)
1745
+ try {
1746
+ return await base
1747
+ } catch (error) {
1748
+ base = undefined
1749
+ throw error
1750
+ }
1751
+ }
1752
+ } else {
1753
+ const read = await this.commitFiles(ref, commits, signal)
1754
+ files = read.files
1755
+ newCommit = commits.to
1756
+ oldCommit = () => Promise.resolve(read.parent)
1757
+ }
1758
+ return {
1759
+ key: JSON.stringify(['change', changeRequestKey(ref), newCommit, commits]),
1760
+ source: { kind: 'change', ref, headSha: snapshot.headSha, commits },
1761
+ files,
1762
+ read: async (side, file, inner) => {
1763
+ if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null
1764
+ const commit = side === 'new' ? newCommit : await oldCommit(inner)
1765
+ const text = await this.home.forge.fileText(ref, commit, side === 'new' ? file.path : file.previousPath ?? file.path, inner)
1766
+ if (typeof text === 'string') return text
1767
+ if (text.code === 'not-found') return null
1768
+ throw new Error(text.message)
1769
+ },
1770
+ }
1771
+ }
1772
+
1773
+ /** The merge base whose files the old side of a change request's diff at the status's head shows. */
1774
+ private async mergeBaseOf(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise<string> {
1775
+ if (snapshot.baseSha === undefined) throw new Error('The code host provider reports no base commit to read the old side at')
1776
+ const base = await this.home.forge.mergeBase(ref, snapshot.baseSha, snapshot.headSha, signal)
1777
+ if (typeof base !== 'string') throw new Error(base.message)
1778
+ return base
1779
+ }
1780
+
1023
1781
  private panelOf(session: Session): SessionPanel {
1024
1782
  let panel = this.panels.get(session)
1025
1783
  if (panel === undefined) {
1026
- const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, () => {
1784
+ const revision = (ref: ChangeRequestRef): number => this.reviewRevisions.get(changeRequestKey(ref)) ?? 0
1785
+ const idle = (): void => {
1027
1786
  if (this.panels.get(session) !== created) return
1028
1787
  this.panels.delete(session)
1788
+ this.keptPanels.set(session, created.keep())
1029
1789
  void created.dispose()
1030
- })
1790
+ }
1791
+ const created: SessionPanel = new SessionPanel(
1792
+ this.home, this.config, session, this.worktreeStates, this.creations, revision, this.keptPanels.get(session), idle,
1793
+ )
1031
1794
  panel = created
1032
1795
  this.panels.set(session, panel)
1033
1796
  }
@@ -1085,6 +1848,7 @@ function readError(failure: ForgeFailure): RemoteError {
1085
1848
  case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
1086
1849
  case 'not-found':
1087
1850
  case 'unauthenticated':
1851
+ case 'rate-limited':
1088
1852
  case 'unsupported':
1089
1853
  case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {})
1090
1854
  /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
@@ -1105,6 +1869,7 @@ function reviewError(failure: ForgeFailure): RemoteError {
1105
1869
  case 'not-found':
1106
1870
  case 'unauthenticated':
1107
1871
  case 'too-large':
1872
+ case 'rate-limited':
1108
1873
  case 'unavailable': return new RemoteError('forgePanel/review-failed', failure.message, {})
1109
1874
  /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
1110
1875
  default: return assertNever(failure.code, 'ForgeFailure.code')
@@ -1142,21 +1907,4 @@ function actionError(failure: ForgeActionFailure): RemoteError {
1142
1907
  return new RemoteError(code, failure.message, {})
1143
1908
  }
1144
1909
 
1145
- /**
1146
- * Whether `prefix` followed by hexadecimal digits is a branch name that Git
1147
- * accepts: no leading `-` or `/`, no empty component, no component that
1148
- * starts with `.` or ends with `.lock`, and none of `..`, `@{`, whitespace,
1149
- * control characters, `~`, `^`, `:`, `?`, `*`, `[`, or `\`.
1150
- * @param prefix - configured worktree branch prefix.
1151
- * @returns whether every generated name passes `git check-ref-format --branch`.
1152
- */
1153
- function branchPrefix(prefix: string): boolean {
1154
- const name = `${prefix}0`
1155
- if (name.startsWith('-') || name.includes('..') || name.includes('@{')) return false
1156
- for (const char of name) {
1157
- if (char <= ' ' || char === '\x7f' || '~^:?*[\\'.includes(char)) return false
1158
- }
1159
- return name.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock'))
1160
- }
1161
-
1162
1910
  export default ForgePanelController