@deepseek-ai/dsh-experimental-client-ui-forge 0.2.2-alpha.3 → 0.2.2-rc.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 (272) hide show
  1. package/README.i18n.yaml +8 -8
  2. package/README.md +41 -14
  3. package/README.zh.md +40 -13
  4. package/lib/client.js +13 -11800
  5. package/lib/client.js.map +1 -0
  6. package/lib/index.js +1340 -115
  7. package/lib/typert.host.js +1715 -212
  8. package/lib/typert.remote-client.d.ts +42 -5
  9. package/lib/typert.remote-client.d.ts.map +1 -0
  10. package/lib/typert.remote-client.js +1523 -244
  11. package/lib/types/client/ActionToast.d.ts.map +1 -0
  12. package/lib/types/client/ActionToast.js.map +1 -0
  13. package/lib/types/client/BaseMenu.d.ts +30 -0
  14. package/lib/types/client/BaseMenu.d.ts.map +1 -0
  15. package/lib/types/client/BaseMenu.js.map +1 -0
  16. package/lib/types/client/ChangeRequestCard.d.ts +9 -5
  17. package/lib/types/client/ChangeRequestCard.d.ts.map +1 -0
  18. package/lib/types/client/ChangeRequestCard.js.map +1 -0
  19. package/lib/types/client/ChangeRequestOverview.d.ts +124 -0
  20. package/lib/types/client/ChangeRequestOverview.d.ts.map +1 -0
  21. package/lib/types/client/ChangeRequestOverview.js.map +1 -0
  22. package/lib/types/client/ChangedFiles.d.ts +2 -0
  23. package/lib/types/client/ChangedFiles.d.ts.map +1 -0
  24. package/lib/types/client/ChangedFiles.js.map +1 -0
  25. package/lib/types/client/ChangesTab.d.ts +30 -5
  26. package/lib/types/client/ChangesTab.d.ts.map +1 -0
  27. package/lib/types/client/ChangesTab.js.map +1 -0
  28. package/lib/types/client/ChangesTabTitle.d.ts.map +1 -0
  29. package/lib/types/client/ChangesTabTitle.js.map +1 -0
  30. package/lib/types/client/CommitMenu.d.ts +41 -0
  31. package/lib/types/client/CommitMenu.d.ts.map +1 -0
  32. package/lib/types/client/CommitMenu.js.map +1 -0
  33. package/lib/types/client/DiffFile.d.ts +47 -15
  34. package/lib/types/client/DiffFile.d.ts.map +1 -0
  35. package/lib/types/client/DiffFile.js.map +1 -0
  36. package/lib/types/client/FileLabel.d.ts.map +1 -0
  37. package/lib/types/client/FileLabel.js.map +1 -0
  38. package/lib/types/client/FileTreePane.d.ts +4 -2
  39. package/lib/types/client/FileTreePane.d.ts.map +1 -0
  40. package/lib/types/client/FileTreePane.js.map +1 -0
  41. package/lib/types/client/ForgeTab.d.ts +9 -1
  42. package/lib/types/client/ForgeTab.d.ts.map +1 -0
  43. package/lib/types/client/ForgeTab.js.map +1 -0
  44. package/lib/types/client/ForgeTabTitle.d.ts.map +1 -0
  45. package/lib/types/client/ForgeTabTitle.js.map +1 -0
  46. package/lib/types/client/HeaderButton.d.ts.map +1 -0
  47. package/lib/types/client/HeaderButton.js.map +1 -0
  48. package/lib/types/client/LocalChangesCard.d.ts.map +1 -0
  49. package/lib/types/client/LocalChangesCard.js.map +1 -0
  50. package/lib/types/client/RefreshGlyph.d.ts.map +1 -0
  51. package/lib/types/client/RefreshGlyph.js.map +1 -0
  52. package/lib/types/client/ReviewComposer.d.ts +20 -6
  53. package/lib/types/client/ReviewComposer.d.ts.map +1 -0
  54. package/lib/types/client/ReviewComposer.js.map +1 -0
  55. package/lib/types/client/ReviewControls.d.ts +79 -0
  56. package/lib/types/client/ReviewControls.d.ts.map +1 -0
  57. package/lib/types/client/ReviewControls.js.map +1 -0
  58. package/lib/types/client/ReviewThread.d.ts +4 -4
  59. package/lib/types/client/ReviewThread.d.ts.map +1 -0
  60. package/lib/types/client/ReviewThread.js.map +1 -0
  61. package/lib/types/client/ReviewThreads.d.ts +108 -0
  62. package/lib/types/client/ReviewThreads.d.ts.map +1 -0
  63. package/lib/types/client/ReviewThreads.js.map +1 -0
  64. package/lib/types/client/SessionHoverForge.d.ts.map +1 -0
  65. package/lib/types/client/SessionHoverForge.js.map +1 -0
  66. package/lib/types/client/SessionRowForge.d.ts +1 -1
  67. package/lib/types/client/SessionRowForge.d.ts.map +1 -0
  68. package/lib/types/client/SessionRowForge.js.map +1 -0
  69. package/lib/types/client/SubmitReview.d.ts +12 -4
  70. package/lib/types/client/SubmitReview.d.ts.map +1 -0
  71. package/lib/types/client/SubmitReview.js.map +1 -0
  72. package/lib/types/client/ThreadList.d.ts +43 -0
  73. package/lib/types/client/ThreadList.d.ts.map +1 -0
  74. package/lib/types/client/ThreadList.js.map +1 -0
  75. package/lib/types/client/ViewOptionsMenu.d.ts +31 -0
  76. package/lib/types/client/ViewOptionsMenu.d.ts.map +1 -0
  77. package/lib/types/client/ViewOptionsMenu.js.map +1 -0
  78. package/lib/types/client/WorktreeProgress.d.ts.map +1 -0
  79. package/lib/types/client/WorktreeProgress.js.map +1 -0
  80. package/lib/types/client/WorktreeSettings.d.ts +12 -0
  81. package/lib/types/client/WorktreeSettings.d.ts.map +1 -0
  82. package/lib/types/client/WorktreeSettings.js.map +1 -0
  83. package/lib/types/client/WorktreeToggle.d.ts.map +1 -0
  84. package/lib/types/client/WorktreeToggle.js.map +1 -0
  85. package/lib/types/client/changes-address.d.ts.map +1 -0
  86. package/lib/types/client/changes-address.js.map +1 -0
  87. package/lib/types/client/changes-store.d.ts +20 -5
  88. package/lib/types/client/changes-store.d.ts.map +1 -0
  89. package/lib/types/client/changes-store.js.map +1 -0
  90. package/lib/types/client/checkout.d.ts.map +1 -0
  91. package/lib/types/client/checkout.js.map +1 -0
  92. package/lib/types/client/code-selection.d.ts.map +1 -0
  93. package/lib/types/client/code-selection.js.map +1 -0
  94. package/lib/types/client/diff-rows.d.ts.map +1 -0
  95. package/lib/types/client/diff-rows.js.map +1 -0
  96. package/lib/types/client/file-tree.d.ts.map +1 -0
  97. package/lib/types/client/file-tree.js.map +1 -0
  98. package/lib/types/client/format.d.ts.map +1 -0
  99. package/lib/types/client/format.js.map +1 -0
  100. package/lib/types/client/glyphs.d.ts +4 -2
  101. package/lib/types/client/glyphs.d.ts.map +1 -0
  102. package/lib/types/client/glyphs.js.map +1 -0
  103. package/lib/types/client/host-viewed.d.ts +84 -0
  104. package/lib/types/client/host-viewed.d.ts.map +1 -0
  105. package/lib/types/client/host-viewed.js.map +1 -0
  106. package/lib/types/client/index.d.ts.map +1 -0
  107. package/lib/types/client/index.js.map +1 -0
  108. package/lib/types/client/locales.d.ts +175 -3
  109. package/lib/types/client/locales.d.ts.map +1 -0
  110. package/lib/types/client/locales.js.map +1 -0
  111. package/lib/types/client/menu-search.d.ts +10 -0
  112. package/lib/types/client/menu-search.d.ts.map +1 -0
  113. package/lib/types/client/menu-search.js.map +1 -0
  114. package/lib/types/client/mount.d.ts +4 -0
  115. package/lib/types/client/mount.d.ts.map +1 -0
  116. package/lib/types/client/mount.js.map +1 -0
  117. package/lib/types/client/review-queue.d.ts +5 -8
  118. package/lib/types/client/review-queue.d.ts.map +1 -0
  119. package/lib/types/client/review-queue.js.map +1 -0
  120. package/lib/types/client/review-threads.d.ts +108 -0
  121. package/lib/types/client/review-threads.d.ts.map +1 -0
  122. package/lib/types/client/review-threads.js.map +1 -0
  123. package/lib/types/client/review.d.ts +31 -4
  124. package/lib/types/client/review.d.ts.map +1 -0
  125. package/lib/types/client/review.js.map +1 -0
  126. package/lib/types/client/section-reach.d.ts +26 -0
  127. package/lib/types/client/section-reach.d.ts.map +1 -0
  128. package/lib/types/client/section-reach.js.map +1 -0
  129. package/lib/types/client/session-list.d.ts.map +1 -0
  130. package/lib/types/client/session-list.js.map +1 -0
  131. package/lib/types/client/source.d.ts.map +1 -0
  132. package/lib/types/client/source.js.map +1 -0
  133. package/lib/types/client/status.d.ts.map +1 -0
  134. package/lib/types/client/status.js.map +1 -0
  135. package/lib/types/client/thread-state.d.ts +68 -0
  136. package/lib/types/client/thread-state.d.ts.map +1 -0
  137. package/lib/types/client/thread-state.js.map +1 -0
  138. package/lib/types/client/toolbar-fold.d.ts +19 -0
  139. package/lib/types/client/toolbar-fold.d.ts.map +1 -0
  140. package/lib/types/client/toolbar-fold.js.map +1 -0
  141. package/lib/types/client/viewed-files.d.ts +70 -0
  142. package/lib/types/client/viewed-files.d.ts.map +1 -0
  143. package/lib/types/client/viewed-files.js.map +1 -0
  144. package/lib/types/client/worktree-settings-form.d.ts +32 -0
  145. package/lib/types/client/worktree-settings-form.d.ts.map +1 -0
  146. package/lib/types/client/worktree-settings-form.js.map +1 -0
  147. package/lib/types/commit-range.d.ts +17 -0
  148. package/lib/types/commit-range.d.ts.map +1 -0
  149. package/lib/types/commit-range.js.map +1 -0
  150. package/lib/types/diff.d.ts +10 -2
  151. package/lib/types/diff.d.ts.map +1 -0
  152. package/lib/types/diff.js.map +1 -0
  153. package/lib/types/git.d.ts.map +1 -0
  154. package/lib/types/git.js.map +1 -0
  155. package/lib/types/index.d.ts +194 -14
  156. package/lib/types/index.d.ts.map +1 -0
  157. package/lib/types/index.js.map +1 -0
  158. package/lib/types/layers.d.ts +66 -0
  159. package/lib/types/layers.d.ts.map +1 -0
  160. package/lib/types/layers.js.map +1 -0
  161. package/lib/types/local-diff.d.ts +54 -6
  162. package/lib/types/local-diff.d.ts.map +1 -0
  163. package/lib/types/local-diff.js.map +1 -0
  164. package/lib/types/panel.d.ts.map +1 -0
  165. package/lib/types/panel.js.map +1 -0
  166. package/lib/types/parse.d.ts +16 -0
  167. package/lib/types/parse.d.ts.map +1 -0
  168. package/lib/types/parse.js.map +1 -0
  169. package/lib/types/patch-cache.d.ts +12 -7
  170. package/lib/types/patch-cache.d.ts.map +1 -0
  171. package/lib/types/patch-cache.js.map +1 -0
  172. package/lib/types/review-cache.d.ts +54 -0
  173. package/lib/types/review-cache.d.ts.map +1 -0
  174. package/lib/types/review-cache.js.map +1 -0
  175. package/lib/types/states.d.ts.map +1 -0
  176. package/lib/types/states.js.map +1 -0
  177. package/lib/types/types.d.ts +113 -11
  178. package/lib/types/types.d.ts.map +1 -0
  179. package/lib/types/types.js.map +1 -0
  180. package/lib/types/wildmatch.d.ts +14 -0
  181. package/lib/types/wildmatch.d.ts.map +1 -0
  182. package/lib/types/wildmatch.js.map +1 -0
  183. package/lib/types/worktree.d.ts +8 -6
  184. package/lib/types/worktree.d.ts.map +1 -0
  185. package/lib/types/worktree.js.map +1 -0
  186. package/package.json +59 -49
  187. package/src/client/ActionToast.tsx +38 -0
  188. package/src/client/BaseMenu.module.css +153 -0
  189. package/src/client/BaseMenu.tsx +180 -0
  190. package/src/client/ChangeRequestCard.tsx +439 -0
  191. package/src/client/ChangeRequestOverview.module.css +196 -0
  192. package/src/client/ChangeRequestOverview.tsx +620 -0
  193. package/src/client/ChangedFiles.module.css +26 -0
  194. package/src/client/ChangedFiles.tsx +144 -0
  195. package/src/client/ChangesTab.module.css +984 -0
  196. package/src/client/ChangesTab.tsx +1288 -0
  197. package/src/client/ChangesTabTitle.tsx +28 -0
  198. package/src/client/CommitMenu.module.css +139 -0
  199. package/src/client/CommitMenu.tsx +186 -0
  200. package/src/client/DiffFile.tsx +621 -0
  201. package/src/client/FileLabel.module.css +53 -0
  202. package/src/client/FileLabel.tsx +66 -0
  203. package/src/client/FileTreePane.module.css +10 -0
  204. package/src/client/FileTreePane.tsx +79 -0
  205. package/src/client/ForgeTab.module.css +627 -0
  206. package/src/client/ForgeTab.tsx +263 -0
  207. package/src/client/ForgeTabTitle.tsx +21 -0
  208. package/src/client/HeaderButton.module.css +29 -0
  209. package/src/client/HeaderButton.tsx +68 -0
  210. package/src/client/LocalChangesCard.tsx +83 -0
  211. package/src/client/RefreshGlyph.module.css +22 -0
  212. package/src/client/RefreshGlyph.tsx +35 -0
  213. package/src/client/ReviewComposer.module.css +37 -0
  214. package/src/client/ReviewComposer.tsx +128 -0
  215. package/src/client/ReviewControls.module.css +162 -0
  216. package/src/client/ReviewControls.tsx +191 -0
  217. package/src/client/ReviewThread.tsx +96 -0
  218. package/src/client/ReviewThreads.module.css +326 -0
  219. package/src/client/ReviewThreads.tsx +443 -0
  220. package/src/client/SessionHoverForge.tsx +72 -0
  221. package/src/client/SessionList.module.css +85 -0
  222. package/src/client/SessionRowForge.tsx +86 -0
  223. package/src/client/SubmitReview.module.css +26 -0
  224. package/src/client/SubmitReview.tsx +95 -0
  225. package/src/client/ThreadList.module.css +218 -0
  226. package/src/client/ThreadList.tsx +165 -0
  227. package/src/client/ViewOptionsMenu.tsx +79 -0
  228. package/src/client/WorktreeProgress.module.css +226 -0
  229. package/src/client/WorktreeProgress.tsx +280 -0
  230. package/src/client/WorktreeSettings.module.css +29 -0
  231. package/src/client/WorktreeSettings.tsx +42 -0
  232. package/src/client/WorktreeToggle.module.css +132 -0
  233. package/src/client/WorktreeToggle.tsx +165 -0
  234. package/src/client/changes-address.ts +110 -0
  235. package/src/client/changes-store.ts +155 -0
  236. package/src/client/checkout.ts +75 -0
  237. package/src/client/code-selection.ts +53 -0
  238. package/src/client/diff-rows.ts +199 -0
  239. package/src/client/file-tree.ts +86 -0
  240. package/src/client/format.ts +37 -0
  241. package/src/client/glyphs.tsx +151 -0
  242. package/src/client/host-viewed.ts +195 -0
  243. package/src/client/index.ts +31 -0
  244. package/src/client/locales.ts +3446 -0
  245. package/src/client/menu-search.ts +16 -0
  246. package/src/client/mount.ts +439 -0
  247. package/src/client/review-queue.ts +256 -0
  248. package/src/client/review-threads.ts +204 -0
  249. package/src/client/review.ts +120 -0
  250. package/src/client/section-reach.ts +61 -0
  251. package/src/client/session-list.ts +79 -0
  252. package/src/client/source.ts +274 -0
  253. package/src/client/status.ts +171 -0
  254. package/src/client/thread-state.ts +127 -0
  255. package/src/client/toolbar-fold.ts +70 -0
  256. package/src/client/viewed-files.ts +178 -0
  257. package/src/client/worktree-settings-form.ts +43 -0
  258. package/src/commit-range.ts +27 -0
  259. package/src/css-modules.d.ts +5 -0
  260. package/src/diff.ts +162 -0
  261. package/src/git.ts +293 -0
  262. package/src/index.ts +1162 -0
  263. package/src/layers.ts +163 -0
  264. package/src/local-diff.ts +438 -0
  265. package/src/panel.ts +422 -0
  266. package/src/parse.ts +137 -0
  267. package/src/patch-cache.ts +73 -0
  268. package/src/review-cache.ts +98 -0
  269. package/src/states.ts +350 -0
  270. package/src/types.ts +504 -0
  271. package/src/wildmatch.ts +121 -0
  272. package/src/worktree.ts +576 -0
package/src/index.ts ADDED
@@ -0,0 +1,1162 @@
1
+ /** Host Remote of the forge panel: checkout, code host, sign-in, change request, and worktree state per Session. */
2
+
3
+ import { Context, Service } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import type { Agent } from '@deepseek-ai/dsh-agent'
6
+ import type {} from '@deepseek-ai/dsh-api-remote-access'
7
+ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
8
+ import type {
9
+ BranchUpdateMethod, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure,
10
+ ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
11
+ ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
12
+ } from '@deepseek-ai/dsh-experimental-forge'
13
+ import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
14
+ import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
15
+ import { appendPluginRecord } from '@deepseek-ai/dsh-session'
16
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
17
+ import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
18
+ import type {} from '@deepseek-ai/dsh-session-projection-cache'
19
+ import type {} from '@deepseek-ai/dsh-session-query'
20
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
21
+ import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
22
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
23
+ import { gitIn, inspectCheckout, listBranches } from './git.ts'
24
+ import type { Inspection } from './git.ts'
25
+ import { parseDiff } from './diff.ts'
26
+ import {
27
+ aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint,
28
+ localCommits, localDiff, localText, NoForkPoint,
29
+ } from './local-diff.ts'
30
+ import { rangeStart } from './commit-range.ts'
31
+ import { ATTRIBUTES_PATH, FileLayers } from './layers.ts'
32
+ import { missingWorktree, SessionPanel } from './panel.ts'
33
+ import { PatchCache } from './patch-cache.ts'
34
+ import { ReviewCache } from './review-cache.ts'
35
+ import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
36
+ import type { PanelConfig } from './panel.ts'
37
+ import type {
38
+ Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits,
39
+ ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState,
40
+ } from './types.ts'
41
+ import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
42
+ import type { HeldWork } from './worktree.ts'
43
+
44
+ export type * from './types.ts'
45
+
46
+ declare module '@deepseek-ai/cordis' {
47
+ interface Context {
48
+ /** Remote that serves the forge panel of the GUI. */
49
+ forgePanel: ForgePanelController
50
+ }
51
+ }
52
+
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 }
55
+
56
+ /**
57
+ * Serves the forge panel. Following a Session inspects the checkout of its
58
+ * current directory using the Session's permissions and execution world, recognizes the
59
+ * code host of the upstream remote or `origin`, probes sign-in for that host,
60
+ * and polls the Session's bound change requests through `ctx.forge` until the
61
+ * last follower of that Session leaves. A worktree request makes the panel
62
+ * create a branch and checkout through an optional `ctx.worktrees` and enter
63
+ * it while the Session's first message waits in the inbox, or at the first
64
+ * step proposal of a message no wait took. After a failed or stopped attempt
65
+ * the message keeps waiting for another attempt or for the request to be
66
+ * withdrawn. A message also waits while the worktree the Session works in is
67
+ * gone, until that worktree is checked out again or left for the source
68
+ * checkout. Changes to a Session's checkout run as Agent maintenance, so a
69
+ * message that arrives meanwhile waits for them.
70
+ */
71
+ export class ForgePanelController extends TypertRemoteService {
72
+ static inject = [
73
+ 'forge', 'forgeSession', 'sessionProjections', 'workingDirectory', 'fs', 'subprocess', 'sandbox', 'sandboxPolicy', 'agents',
74
+ ]
75
+
76
+ static Config: z<Config> = z.object({
77
+ gitCommand: z.string().default('git'),
78
+ gitTimeoutMs: z.number().default(10_000),
79
+ graceMs: z.number().default(1_000),
80
+ maxOutputBytes: z.number().default(1_048_576),
81
+ readinessTimeoutMs: z.number().default(15_000),
82
+ maxBranches: z.number().default(50),
83
+ worktreePrefix: z.string().default('dsh-'),
84
+ maxDiffBytes: z.number().default(8_388_608),
85
+ maxUntrackedFiles: z.number().default(100),
86
+ maxCachedDiffBytes: z.number().default(16_777_216),
87
+ maxCommits: z.number().default(250),
88
+ testPaths: z.array(z.string()).default([]),
89
+ interfacePaths: z.array(z.string()).default([]),
90
+ maxCachedReviewBytes: z.number().default(16_777_216),
91
+ reviewRefreshMs: z.number().default(60_000),
92
+ })
93
+
94
+ private readonly home: Context
95
+ private readonly config: ControllerConfig
96
+ private readonly panels = new Map<Session, SessionPanel>()
97
+ private worktreeStates!: ProjectionHandle<ForgeWorktreeState>
98
+ private creations!: WorktreeCreations
99
+ private readonly patches: PatchCache
100
+ private readonly layers: FileLayers
101
+ private readonly reviews: ReviewCache
102
+ private states: ChangeRequestStates | undefined
103
+ private readonly stopPanels: () => Promise<void>
104
+ private readonly stopStates: () => Promise<void>
105
+
106
+ constructor(ctx: Context, config: Config) {
107
+ super(ctx, 'forgePanel')
108
+ const resolved = config as Required<Config>
109
+ 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) {
111
+ const value = resolved[key]
112
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
113
+ throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
114
+ }
115
+ }
116
+ for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes'] as const) {
117
+ if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`)
118
+ }
119
+ if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
120
+ for (const key of ['testPaths', 'interfacePaths'] as const) {
121
+ if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`)
122
+ }
123
+ this.layers = new FileLayers(resolved.testPaths, resolved.interfacePaths)
124
+ this.home = ctx
125
+ this.config = resolved
126
+ this.patches = new PatchCache(resolved.maxCachedDiffBytes)
127
+ this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
128
+ this.stopPanels = ctx.effect(() => async () => {
129
+ const panels = [...this.panels.values()]
130
+ this.panels.clear()
131
+ await Promise.allSettled(panels.map(panel => panel.dispose()))
132
+ }, 'forge-panel: stop panels')
133
+ this.stopStates = ctx.effect(() => async () => {
134
+ await this.states?.dispose()
135
+ }, 'forge-panel: stop change request states')
136
+ }
137
+
138
+ protected async [Service.init](): Promise<void> {
139
+ const ctx = this.home
140
+ const stateOwner = ctx.plugin({
141
+ name: 'forge-panel-state',
142
+ inject: ['sessionProjections'],
143
+ apply: async (scope: Context) => {
144
+ this.worktreeStates = await scope.sessionProjections.register(forgeWorktreeProjection)
145
+ },
146
+ })
147
+ await stateOwner
148
+ // Inbox insertions, step proposals, and Session events read the worktree state, so they start once its reader is ready.
149
+ this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => {
150
+ this.panels.get(session)?.updateWorktree()
151
+ })
152
+ const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) })
153
+ const events = ctx.on('session/event', (session: Session, event: SessionEvent) => {
154
+ this.panels.get(session)?.observe(event)
155
+ })
156
+ const services = ctx.on('internal/service', (name: string) => {
157
+ if (name !== 'worktrees') return
158
+ for (const panel of this.panels.values()) panel.updateWorktree()
159
+ })
160
+ const { creations, stopPanels, stopStates } = this
161
+ ctx.effect(function* () {
162
+ yield stateOwner.dispose
163
+ yield inbox
164
+ yield events
165
+ yield services
166
+ yield stopPanels
167
+ yield stopStates
168
+ yield creations.dispose
169
+ }, 'forge-panel: drain before releasing state')
170
+ }
171
+
172
+ /**
173
+ * Stream the panel state of a Session: the current state first, then each
174
+ * later state. Intermediate states may be skipped when the reader is slower
175
+ * than the updates. The stream ends when `signal` aborts or the Remote stops.
176
+ * @param session - Session to follow.
177
+ * @param signal - ends the stream.
178
+ * @returns panel states in publication order.
179
+ */
180
+ @Remote({ mode: 'stream' })
181
+ async *follow(session: Session, signal: AbortSignal): AsyncIterable<ForgePanelState> {
182
+ yield* this.panelOf(session).follow(signal)
183
+ }
184
+
185
+ /**
186
+ * Stream the last known state of every change request that a listed
187
+ * Session the caller may read binds: the stored states first, then each
188
+ * state a poll changes or a new binding reveals. Listing reads no Session
189
+ * log: loaded Sessions report their bindings, others the cached Session
190
+ * summary, and a Session without one shows nothing until it is opened.
191
+ * Closed requests are polled at the idle cadence so reopening is observed. The
192
+ * stream ends when `signal` aborts or the Remote stops.
193
+ * @param signal - ends the stream.
194
+ * @returns frames in publication order.
195
+ * @throws when the Host lacks the Session query, projection cache, storage, or Session store service.
196
+ */
197
+ @Remote({ mode: 'stream' })
198
+ async *changeRequestStates(signal: AbortSignal): AsyncIterable<ForgeChangeRequestStatesFrame> {
199
+ const access = this.ctx.get('remoteAccess')
200
+ yield* this.changeRequestStatesHub().stream(id => access === undefined || access.allows({ kind: 'session', id }), signal)
201
+ }
202
+
203
+ /**
204
+ * 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.
206
+ * @param revision - null reads now; a matching revision waits for completion.
207
+ * @returns the cleanup state, or null without a worktree service, an attempt, or a current revision.
208
+ */
209
+ @Remote
210
+ async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null> {
211
+ return await this.home.get('worktrees')?.cleanupOf(session, revision) ?? null
212
+ }
213
+
214
+ /**
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.
217
+ * @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.
220
+ */
221
+ @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)
224
+ }
225
+
226
+ /**
227
+ * List the branches the `branch` scope of the Session's current checkout can compare with.
228
+ * @param session - Session whose checkout is read.
229
+ * @param query - text the branch names must contain, ignoring case; empty for every branch.
230
+ * @param signal - request cancellation.
231
+ * @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each,
232
+ * most recently committed first, without the checked-out branch.
233
+ * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
234
+ */
235
+ @Remote
236
+ async diffBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeBaseBranches> {
237
+ signal.throwIfAborted()
238
+ const inspection = await this.checkoutOf(session, signal)
239
+ // A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output.
240
+ const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
241
+ return await baseBranches(git, inspection, this.worktreeState(session).created, query, this.config.maxBranches)
242
+ }
243
+
244
+ /* oxlint-disable typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect */
245
+ /**
246
+ * Bind a change request to a Session by URL, or restore a dismissed binding.
247
+ * @param session - Session that receives the binding.
248
+ * @param url - web URL of the change request.
249
+ * @param signal - request cancellation.
250
+ * @throws `forgePanel/unrecognized-url` when no registered provider serves the URL.
251
+ */
252
+ @Remote
253
+ async track(session: Session, url: string, signal: AbortSignal): Promise<void> {
254
+ signal.throwIfAborted()
255
+ if (this.home.forge.changeRequestFromUrl(url) === undefined) {
256
+ throw new RemoteError('forgePanel/unrecognized-url', 'No code host provider recognizes the change request URL', {})
257
+ }
258
+ this.home.forgeSession.track(session, url)
259
+ }
260
+
261
+ /**
262
+ * Hide a visible binding of a Session; other URLs leave the Session unchanged.
263
+ * @param session - Session that owns the binding.
264
+ * @param url - web URL of the change request.
265
+ * @param signal - request cancellation.
266
+ */
267
+ @Remote
268
+ async dismiss(session: Session, url: string, signal: AbortSignal): Promise<void> {
269
+ signal.throwIfAborted()
270
+ this.home.forgeSession.dismiss(session, url)
271
+ }
272
+
273
+ /**
274
+ * Reinspect a followed Session's checkout, probe sign-in again, and poll its
275
+ * change requests at once; an unfollowed Session is unchanged.
276
+ * @param session - Session whose panel refreshes.
277
+ * @param signal - request cancellation.
278
+ * @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
279
+ */
280
+ @Remote
281
+ async refresh(session: Session, signal: AbortSignal): Promise<void> {
282
+ signal.throwIfAborted()
283
+ await this.panels.get(session)?.refresh()
284
+ }
285
+
286
+ /**
287
+ * Read the changes one scope covers in the checkout of the Session's
288
+ * current directory, with Git using the Session's sandbox policy.
289
+ * @param session - Session whose checkout is read.
290
+ * @param scope - which changes to read.
291
+ * @param signal - request cancellation.
292
+ * @returns the files, the base of the `branch` scope, and the untracked files left out.
293
+ * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
294
+ * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
295
+ * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
296
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
297
+ * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
298
+ * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.
299
+ */
300
+ @Remote
301
+ async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff> {
302
+ signal.throwIfAborted()
303
+ const inspection = await this.checkoutOf(session, signal)
304
+ const root = inspection.checkout.root
305
+ const git = gitIn(this.home, this.config, session, root, signal)
306
+ const created = this.worktreeState(session).created
307
+ const fork = scope.kind !== 'branch' ? null
308
+ : await diffing(scope.base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, scope.base))
309
+ return await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal))
310
+ }
311
+
312
+ /**
313
+ * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
314
+ * several of instead of the whole scope.
315
+ * @param session - Session whose checkout is read.
316
+ * @param base - the base ref of the `branch` scope, or null for its automatic fork point.
317
+ * @param signal - request cancellation.
318
+ * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
319
+ * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
320
+ * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
321
+ */
322
+ @Remote
323
+ async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits> {
324
+ signal.throwIfAborted()
325
+ const inspection = await this.checkoutOf(session, signal)
326
+ const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
327
+ const created = this.worktreeState(session).created
328
+ const fork = await diffing(base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, base))
329
+ if (fork === null) throw new RemoteError('forgePanel/no-fork-point', 'The checkout has no fork point to compare its branch with', {})
330
+ return await localCommits(git, fork, this.config.maxCommits)
331
+ }
332
+
333
+ /**
334
+ * Read the new side of one changed file in a scope, which supplies the
335
+ * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
336
+ * the `branch` scope, else the working tree.
337
+ * @param session - Session whose checkout is read.
338
+ * @param scope - the scope the diff was read in.
339
+ * @param path - path relative to the checkout's top-level directory, as the diff names it.
340
+ * @param signal - request cancellation.
341
+ * @returns the text.
342
+ * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
343
+ * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
344
+ * the checkout, binary content, or a failed read.
345
+ */
346
+ @Remote
347
+ async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise<string> {
348
+ signal.throwIfAborted()
349
+ const inspection = await this.checkoutOf(session, signal)
350
+ return await diffing(localText(this.home, this.config, session, inspection.checkout.root, scope, path, signal))
351
+ }
352
+
353
+ /**
354
+ * Load complete checks for the change request whose list the user opened.
355
+ * @param session - Session retaining the visible binding.
356
+ * @param url - binding URL.
357
+ * @param headSha - commit displayed by the card; a different head rejects the result.
358
+ * @param signal - cancellation when the list closes.
359
+ * @returns the complete snapshot at the displayed head.
360
+ * @throws `forgePanel/not-bound` for an invisible binding, `forgePanel/stale-head` for a moved head,
361
+ * or `forgePanel/checks-failed` when the provider cannot complete the read.
362
+ */
363
+ @Remote
364
+ async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ChangeRequestSnapshot> {
365
+ 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
371
+ }
372
+
373
+ /**
374
+ * List the commits of a change request of a Session at its current head, which the changes view can show one or
375
+ * several of instead of the whole change request.
376
+ * @param session - Session the change request is bound to.
377
+ * @param url - binding URL of the change request.
378
+ * @param signal - request cancellation.
379
+ * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits.
380
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
381
+ * `forgePanel/diff-failed` when the host does not list them.
382
+ */
383
+ @Remote
384
+ async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise<ForgeCommitList | null> {
385
+ signal.throwIfAborted()
386
+ const list = await this.home.forge.commits(this.bound(session, url).ref, signal)
387
+ if (list !== undefined && 'code' in list) throw readError(list)
388
+ return list ?? null
389
+ }
390
+
391
+ /**
392
+ * Read the changes of a change request of a Session as its code host
393
+ * computes them, with each file's layer following the root `.gitattributes`
394
+ * of the commit the diff ends at. Without `commits` the diff covers the change
395
+ * request at the head commit of its latest status; a patch already read at the
396
+ * same head commit and base branch is reused from memory with its attributes, for
397
+ * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those
398
+ * commits, from the first one's first parent to the last, and is read every time.
399
+ * @param session - Session the change request is bound to.
400
+ * @param url - binding URL of the change request.
401
+ * @param commits - consecutive commits of the change request, or null for all of it.
402
+ * @param signal - request cancellation.
403
+ * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head.
404
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
405
+ * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order;
406
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
407
+ * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again;
408
+ * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
409
+ * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host
410
+ * does not provide the commits, the diff, or an existing `.gitattributes` otherwise.
411
+ */
412
+ @Remote
413
+ async changeRequestDiff(
414
+ session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal,
415
+ ): Promise<ForgeChangeRequestDiff> {
416
+ 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 }
442
+ }
443
+
444
+ /**
445
+ * Read one file of a change request's repository at a commit, which
446
+ * supplies the unchanged lines between the hunks of its diff.
447
+ * @param session - Session the change request is bound to.
448
+ * @param url - binding URL of the change request.
449
+ * @param commit - commit object name, the head commit of the diff.
450
+ * @param path - path relative to the repository root.
451
+ * @param signal - request cancellation.
452
+ * @returns the text.
453
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
454
+ * `forgePanel/diff-too-large` when the host or its provider refuses the file over a size limit;
455
+ * `forgePanel/diff-failed` when the host does not provide the file otherwise.
456
+ */
457
+ @Remote
458
+ async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise<string> {
459
+ signal.throwIfAborted()
460
+ const text = await this.home.forge.fileText(this.bound(session, url).ref, commit, path, signal)
461
+ if (typeof text !== 'string') throw readError(text)
462
+ return text
463
+ }
464
+
465
+ /**
466
+ * 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.
468
+ * @param session - Session the change request is bound to.
469
+ * @param url - binding URL of the change request.
470
+ * @param headSha - head commit of the shown diff; marks read at another head are refused.
471
+ * @param signal - request cancellation.
472
+ * @returns the marks at `headSha`, or null when the provider keeps no viewed marks.
473
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
474
+ * `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed`
475
+ * when the host does not provide the marks otherwise.
476
+ */
477
+ @Remote
478
+ async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
479
+ 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
486
+ }
487
+
488
+ /**
489
+ * Set or clear the signed-in user's viewed mark on one file of a change request of a Session.
490
+ * @param session - Session the change request is bound to.
491
+ * @param url - binding URL of the change request.
492
+ * @param request - the file, its mark, and the head commit of the shown diff.
493
+ * @param signal - request cancellation.
494
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
495
+ * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's
496
+ * reason when the host refuses, cannot be reached, or keeps no viewed marks; `forgePanel/action-unknown` when the host
497
+ * did not confirm whether it saved the mark.
498
+ */
499
+ @Remote
500
+ async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise<void> {
501
+ 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)
506
+ }
507
+
508
+ /**
509
+ * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read
510
+ * at the same head commit and update time are reused from memory, for any Session, until they are
511
+ * `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read
512
+ * again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull
513
+ * request's update time.
514
+ * @param session - Session the change request is bound to.
515
+ * @param url - binding URL of the change request.
516
+ * @param headSha - head commit of the displayed diff.
517
+ * @param fresh - whether to read from the host even when threads at this head and update time are kept, as after the
518
+ * reader refreshes the view; the result replaces the kept threads.
519
+ * @param signal - request cancellation.
520
+ * @returns the threads at `headSha`, with `current` positions numbering the files of that diff.
521
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
522
+ * `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again;
523
+ * `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the
524
+ * status was read and when the host does not provide the threads otherwise.
525
+ */
526
+ @Remote
527
+ async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData> {
528
+ 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
546
+ }
547
+
548
+ /**
549
+ * Publish a line comment or completed review for a visible Session binding. The threads kept for the change request
550
+ * are dropped once the host answers, so the next read shows the comments.
551
+ * @param session - Session retaining the change request.
552
+ * @param url - visible binding URL.
553
+ * @param request - reviewed head, ranges, plain text, and explicit review decision.
554
+ * @param signal - request cancellation.
555
+ * @returns confirmed publication or a typed failure; unknown outcomes require reconciliation on the host.
556
+ */
557
+ @Remote
558
+ async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
559
+ 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
+ }
570
+ }
571
+
572
+ /**
573
+ * Write to the review threads or the pending review of a change request of a Session while its head is still the
574
+ * head the user saw. The threads kept for the change request are dropped once the host answers, so the next read
575
+ * shows the write, which a resolve does not show through a GitHub pull request's update time.
576
+ * @param session - Session the change request is bound to.
577
+ * @param url - binding URL of the change request.
578
+ * @param write - the write and the head commit of the threads the user saw.
579
+ * @param signal - request cancellation.
580
+ * @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and
581
+ * `unknown` when the outcome must be checked on the host before the write is tried again.
582
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error
583
+ * for a write without text, a head that is not a commit object name, or an invalid line range.
584
+ */
585
+ @Remote
586
+ async changeRequestReviewWrite(
587
+ session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal,
588
+ ): Promise<ForgeReviewWriteResult> {
589
+ 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
+ }
598
+ }
599
+
600
+ /**
601
+ * Mark a draft change request of a Session ready for review; the change
602
+ * request is polled again once the host answers.
603
+ * @param session - Session the change request is bound to.
604
+ * @param url - binding URL of the change request.
605
+ * @param signal - request cancellation.
606
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
607
+ * `forgePanel/action-failed` with the host's reason when the host refuses or cannot be reached.
608
+ */
609
+ @Remote
610
+ async markReady(session: Session, url: string, signal: AbortSignal): Promise<void> {
611
+ signal.throwIfAborted()
612
+ const failure = await this.home.forge.markReady(this.bound(session, url).ref, signal)
613
+ if (failure !== undefined) throw actionError(failure)
614
+ }
615
+
616
+ /**
617
+ * Merge a change request of a Session while its head is still `headSha`;
618
+ * the change request is polled again once the host answers.
619
+ * @param session - Session the change request is bound to.
620
+ * @param url - binding URL of the change request.
621
+ * @param method - how the commits enter the base branch.
622
+ * @param headSha - head commit the user confirmed.
623
+ * @param signal - request cancellation.
624
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
625
+ * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's
626
+ * reason when the host refuses otherwise or cannot be reached.
627
+ */
628
+ @Remote
629
+ async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void> {
630
+ signal.throwIfAborted()
631
+ const failure = await this.home.forge.merge(this.bound(session, url).ref, { method, headSha }, signal)
632
+ if (failure !== undefined) throw actionError(failure)
633
+ }
634
+
635
+ /**
636
+ * Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user
637
+ * saw; the change request is polled again once the host answers.
638
+ * @param session - Session the change request is bound to.
639
+ * @param url - binding URL of the change request.
640
+ * @param request - the head commit whose checks the user saw.
641
+ * @param signal - request cancellation.
642
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
643
+ * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's
644
+ * reason when the host refuses, cannot be reached, or reruns no checks; `forgePanel/action-unknown` when the host did
645
+ * not confirm whether it started the rerun.
646
+ */
647
+ @Remote
648
+ async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise<void> {
649
+ signal.throwIfAborted()
650
+ const failure = await this.home.forge.rerunChecks(this.bound(session, url).ref, request, signal)
651
+ if (failure !== undefined) throw actionError(failure)
652
+ }
653
+
654
+ /**
655
+ * Request reviews of a change request of a Session from more reviewers; the change request is polled again once the
656
+ * host answers.
657
+ * @param session - Session the change request is bound to.
658
+ * @param url - binding URL of the change request.
659
+ * @param reviewers - the reviewers to ask, by kind and login.
660
+ * @param signal - request cancellation.
661
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
662
+ * `forgePanel/action-failed` with the host's reason when the host refuses, cannot be reached, or requests no reviews;
663
+ * `forgePanel/action-unknown` when the host did not confirm whether it requested the reviews.
664
+ */
665
+ @Remote
666
+ async requestReviews(
667
+ session: Session, url: string, reviewers: readonly Pick<ChangeRequestReviewer, 'kind' | 'login'>[], signal: AbortSignal,
668
+ ): Promise<void> {
669
+ 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)
674
+ }
675
+
676
+ /**
677
+ * List accounts a review of a change request of a Session can be requested from.
678
+ * @param session - Session the change request is bound to.
679
+ * @param url - binding URL of the change request.
680
+ * @param query - text the login or name contains; empty for the host's suggestions and first accounts.
681
+ * @param signal - request cancellation.
682
+ * @returns the accounts, the host's suggestions first.
683
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
684
+ * `forgePanel/reviewers-failed` when the host does not list them.
685
+ */
686
+ @Remote
687
+ async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[]> {
688
+ 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
692
+ }
693
+
694
+ /**
695
+ * Bring the base branch's new commits into the head branch of a change request of a Session while its head is still
696
+ * `headSha`; the change request is polled again once the host answers.
697
+ * @param session - Session the change request is bound to.
698
+ * @param url - binding URL of the change request.
699
+ * @param method - merge commit or rebase.
700
+ * @param headSha - head commit the user confirmed.
701
+ * @param signal - request cancellation.
702
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
703
+ * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's reason when
704
+ * the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not
705
+ * confirm whether it started the update.
706
+ */
707
+ @Remote
708
+ async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise<void> {
709
+ signal.throwIfAborted()
710
+ const failure = await this.home.forge.updateBranch(this.bound(session, url).ref, { method, headSha }, signal)
711
+ if (failure !== undefined) throw actionError(failure)
712
+ }
713
+
714
+ /**
715
+ * Ask for a new worktree before the Session's first turn, replacing an open
716
+ * 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}.
721
+ * @param session - Session without a started turn.
722
+ * @param from - local base branch, or null for HEAD.
723
+ * @param signal - request cancellation.
724
+ * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable`
725
+ * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was
726
+ * created; `forgePanel/session-busy` while the worktree is being created.
727
+ */
728
+ @Remote
729
+ async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void> {
730
+ signal.throwIfAborted()
731
+ if (from?.length === 0) throw new RemoteError('forgePanel/invalid-branch', 'The base branch name is empty', {})
732
+ this.editableWorktree(session)
733
+ this.creations.forget(session)
734
+ appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from })
735
+ this.creations.recheck(session)
736
+ }
737
+
738
+ /**
739
+ * Withdraw the open worktree request of a Session with its failed attempt,
740
+ * which lets a waiting message go on in the current checkout; without a
741
+ * request the Session is unchanged. Withdrawing needs no worktree service.
742
+ * @param session - Session without a started turn.
743
+ * @param signal - request cancellation.
744
+ * @throws `forgePanel/session-started` after a turn started or the worktree was created;
745
+ * `forgePanel/session-busy` while the worktree is being created.
746
+ */
747
+ @Remote
748
+ async cancelWorktree(session: Session, signal: AbortSignal): Promise<void> {
749
+ signal.throwIfAborted()
750
+ if (this.changeableWorktree(session).request === null) return
751
+ this.creations.forget(session)
752
+ appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' })
753
+ this.creations.recheck(session)
754
+ }
755
+
756
+ /**
757
+ * Stop the creation a message of the Session waits for; the message keeps
758
+ * waiting with the request still open. Without such a creation the Session
759
+ * is unchanged.
760
+ * @param session - Session whose creation stops.
761
+ * @param signal - request cancellation.
762
+ */
763
+ @Remote
764
+ async stopCreation(session: Session, signal: AbortSignal): Promise<void> {
765
+ signal.throwIfAborted()
766
+ this.creations.stop(session)
767
+ }
768
+
769
+ /**
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.
772
+ * @param session - Session whose message waits.
773
+ * @param signal - request cancellation.
774
+ * @throws `forgePanel/not-waiting` when no message waits or an attempt is running.
775
+ */
776
+ @Remote
777
+ async retryWorktree(session: Session, signal: AbortSignal): Promise<void> {
778
+ signal.throwIfAborted()
779
+ if (!this.creations.retry(session)) {
780
+ throw new RemoteError('forgePanel/not-waiting', 'No message waits for another attempt at the worktree', {})
781
+ }
782
+ }
783
+
784
+ /**
785
+ * Check out the created worktree of a Session again at its recorded
786
+ * directory when that directory is gone: its branch when the branch still
787
+ * exists, otherwise a new branch of the same name at the base commit. Changes
788
+ * that were never committed are not recovered. Runs as Agent maintenance,
789
+ * inside the wait of a message that waits for the restoration, which then
790
+ * goes on; without a missing directory the Session is unchanged.
791
+ * @param session - Session whose worktree directory is gone.
792
+ * @param signal - request cancellation, which aborts the restoration.
793
+ * @throws `forgePanel/no-worktree` without a created worktree; `forgePanel/worktrees-unavailable`
794
+ * without a worktree service; `forgePanel/session-busy` while the Session's Agent is not loaded or
795
+ * has other work; `forgePanel/restore-failed` when Git fails.
796
+ */
797
+ @Remote
798
+ async restoreWorktree(session: Session, signal: AbortSignal): Promise<void> {
799
+ signal.throwIfAborted()
800
+ const created = this.createdWorktree(session)
801
+ const worktrees = this.home.get('worktrees')
802
+ if (worktrees === undefined) throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {})
803
+ await this.maintain(session, async (agent, work) => {
804
+ const operation = AbortSignal.any([signal, work])
805
+ try {
806
+ await this.creations.restore(agent, worktrees, created, operation,
807
+ () => { this.panels.get(session)?.restored() },
808
+ async check => await missingWorktree(this.home, this.config, session, this.worktreeState(session), created.path, check) === null)
809
+ } catch (error) {
810
+ operation.throwIfAborted()
811
+ throw new RemoteError('forgePanel/restore-failed', messageOf(error), {}, { cause: error })
812
+ }
813
+ })
814
+ this.panels.get(session)?.reinspect()
815
+ }
816
+
817
+ /**
818
+ * Move a Session from its created worktree to the source checkout the
819
+ * worktree came from; the Session no longer works in the worktree. Runs as
820
+ * Agent maintenance, inside the wait of a message that waits for the removed
821
+ * worktree, which then goes on.
822
+ * @param session - Session with a created worktree.
823
+ * @param signal - request cancellation.
824
+ * @throws `forgePanel/no-worktree` without a created worktree; `forgePanel/session-busy` while the
825
+ * Session's Agent is not loaded or has other work; the working-directory service's error when the
826
+ * source checkout no longer exists.
827
+ */
828
+ @Remote
829
+ async continueInProject(session: Session, signal: AbortSignal): Promise<void> {
830
+ signal.throwIfAborted()
831
+ const created = this.createdWorktree(session)
832
+ await this.maintain(session, async (agent, work) => {
833
+ await this.home.workingDirectory.set(agent, created.repositoryRoot, AbortSignal.any([signal, work]))
834
+ })
835
+ }
836
+
837
+ /* oxlint-enable typescript/require-await */
838
+
839
+ /**
840
+ * Hold the turn of a message entering a Session's inbox while the
841
+ * Session's requested worktree does not exist yet, or while the worktree
842
+ * the Session works in is checked and, when gone, until it is restored or
843
+ * left. The message is entering, so the delivery has not woken the Agent
844
+ * yet and its wake waits for the hold.
845
+ * @param agent - Agent whose inbox receives the message.
846
+ */
847
+ private holdTurn(agent: Agent): void {
848
+ const session = agent.session
849
+ const state = this.worktreeState(session)
850
+ if (state.request !== null && state.created === null && !state.locked) {
851
+ this.creations.holdCreation(agent)
852
+ } else if (state.created !== null && within(state.created.path, this.home.workingDirectory.get(session))) {
853
+ this.creations.holdRestoration(agent, signal => this.missingFor(session, signal))
854
+ }
855
+ }
856
+
857
+ /**
858
+ * Check whether the worktree the Session works in is gone.
859
+ * @param session - Session to check.
860
+ * @param signal - cancellation of the check.
861
+ * @returns the missing worktree, or null while it exists or once the Session works elsewhere.
862
+ * @throws when the filesystem or Git cannot answer.
863
+ */
864
+ private async missingFor(session: Session, signal: AbortSignal): Promise<ForgeMissingWorktree | null> {
865
+ const directory = this.home.workingDirectory.get(session)
866
+ const panel = this.panels.get(session)
867
+ const missing = panel === undefined
868
+ ? await missingWorktree(this.home, this.config, session, this.worktreeState(session), directory, signal)
869
+ : await panel.checkMissing(signal)
870
+ return this.home.workingDirectory.get(session) === directory ? missing : null
871
+ }
872
+
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> {
875
+ const list = await this.home.forge.commits(ref, signal)
876
+ if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {})
877
+ if ('code' in list) throw readError(list)
878
+ const start = rangeStart(list.commits, commits)
879
+ if (start === 'missing') throw new RemoteError('forgePanel/commits-missing', 'The chosen commits are no longer in the change request', {})
880
+ if (start === 'not-linear') throw new RemoteError('forgePanel/commits-not-linear', 'The chosen commits are not one run of first parents', {})
881
+ const parent = start.parent
882
+ if (parent === null) throw new RemoteError('forgePanel/diff-failed', 'The first chosen commit has no parent to compare with', {})
883
+ const { patch, attributes } = await this.patchAt(
884
+ ref, commits.to, async operation => await this.home.forge.compare(ref, parent, commits.to, operation), signal,
885
+ )
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 }
889
+ }
890
+
891
+ /**
892
+ * Read a patch that ends at `commit` together with the root `.gitattributes` at that commit. A failed patch read
893
+ * cancels the attributes read. Both reads end before the result: the patch's failure passes on first, and the
894
+ * attributes failure only after the patch was read, so the outcome does not depend on which read ends first.
895
+ * @param ref - change request whose repository holds the commit.
896
+ * @param commit - commit the patch ends at.
897
+ * @param readPatch - reads the patch under the given cancellation.
898
+ * @param signal - request cancellation.
899
+ * @returns the patch and the attributes text, empty when the commit has none.
900
+ * @throws the Remote error for a refused patch or attributes read, or `signal.reason` when it aborts.
901
+ */
902
+ private async patchAt(
903
+ ref: ChangeRequestRef, commit: string, readPatch: (signal: AbortSignal) => Promise<string | ForgeFailure>, signal: AbortSignal,
904
+ ): Promise<{ readonly patch: string; readonly attributes: string }> {
905
+ const unneeded = new AbortController()
906
+ const patch = readPatch(signal).then((result) => {
907
+ if (typeof result !== 'string') throw readError(result)
908
+ return result
909
+ })
910
+ const attributes = this.attributesAt(ref, commit, AbortSignal.any([signal, unneeded.signal]))
911
+ void patch.then(undefined, () => { unneeded.abort() })
912
+ const [text, rules] = await Promise.allSettled([patch, attributes])
913
+ if (text.status === 'rejected') throw text.reason
914
+ if (rules.status === 'rejected') throw rules.reason
915
+ return { patch: text.value, attributes: rules.value }
916
+ }
917
+
918
+ /** The root `.gitattributes` of a change request's repository at a commit, empty when the commit has none. */
919
+ private async attributesAt(ref: ChangeRequestRef, commit: string, signal: AbortSignal): Promise<string> {
920
+ const attributes = await this.home.forge.fileText(ref, commit, ATTRIBUTES_PATH, signal)
921
+ if (typeof attributes === 'string') return attributes
922
+ if (attributes.code === 'not-found') return ''
923
+ throw readError(attributes)
924
+ }
925
+
926
+ /** Inspect the checkout of the Session's current directory, which local diffs read. */
927
+ private async checkoutOf(session: Session, signal: AbortSignal): Promise<Inspection> {
928
+ const inspection = await inspectCheckout(this.home, this.config, session, this.home.workingDirectory.get(session), signal)
929
+ if (inspection === undefined) throw new RemoteError('forgePanel/not-a-checkout', 'The Session\'s directory is not inside a Git checkout', {})
930
+ return inspection
931
+ }
932
+
933
+ /** A visible binding of the Session that a provider serves, which actions and reads are limited to. */
934
+ private bound(session: Session, url: string): SessionChangeRequest & { readonly ref: NonNullable<SessionChangeRequest['ref']> } {
935
+ const entry = this.home.forgeSession.changeRequests(session).find(candidate => candidate.url === url)
936
+ if (entry?.ref == null) throw new RemoteError('forgePanel/not-bound', 'The change request is not bound to this Session or no provider serves it', {})
937
+ return { ...entry, ref: entry.ref }
938
+ }
939
+
940
+ private worktreeState(session: Session): ForgeWorktreeState {
941
+ return this.worktreeStates.stateOf(session)
942
+ }
943
+
944
+ private editableWorktree(session: Session): ForgeWorktreeState {
945
+ if (this.home.get('worktrees') === undefined) {
946
+ throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {})
947
+ }
948
+ return this.changeableWorktree(session)
949
+ }
950
+
951
+ /** The worktree state of a Session whose request may still change: no turn started, nothing created, and no attempt running. */
952
+ private changeableWorktree(session: Session): ForgeWorktreeState {
953
+ const state = this.worktreeState(session)
954
+ if (state.locked || state.created !== null) {
955
+ throw new RemoteError('forgePanel/session-started', 'The Session has started, so its worktree can no longer change', {})
956
+ }
957
+ // A creation records its worktree only for the request it started from.
958
+ if (this.creations.of(session) !== null) throw new RemoteError('forgePanel/session-busy', 'The worktree is being created', {})
959
+ return state
960
+ }
961
+
962
+ private createdWorktree(session: Session): ForgeSessionWorktree {
963
+ const created = this.worktreeState(session).created
964
+ if (created === null) throw new RemoteError('forgePanel/no-worktree', 'The Session has no created worktree', {})
965
+ return created
966
+ }
967
+
968
+ /**
969
+ * Run work as maintenance of the Session's Agent: inside the wait of a
970
+ * message that waits for the removed worktree, else as a task of its own,
971
+ * which the Agent refuses while it has other work.
972
+ */
973
+ private async maintain(session: Session, work: HeldWork): Promise<void> {
974
+ const held = this.creations.within(session, work)
975
+ if (held !== undefined) {
976
+ await held
977
+ return
978
+ }
979
+ const agent = this.home.agents.get(session.id)
980
+ if (agent === undefined) throw new RemoteError('forgePanel/session-busy', 'The Session is not loaded', {})
981
+ let running: Promise<void>
982
+ try {
983
+ running = agent.runMaintenance(async (signal) => { await work(agent, signal) })
984
+ } catch (error) {
985
+ throw new RemoteError('forgePanel/session-busy', 'The Session is busy', {}, { cause: error })
986
+ }
987
+ await running
988
+ }
989
+
990
+ /** The shared change request states, created for the first stream from the Host's Session and storage services. */
991
+ private changeRequestStatesHub(): ChangeRequestStates {
992
+ if (this.states !== undefined) return this.states
993
+ const ctx = this.home
994
+ const query = ctx.get('sessionQuery')
995
+ const cache = ctx.get('sessionProjectionCache')
996
+ const storage = ctx.get('storageDomain')
997
+ const store = ctx.get('sessions')
998
+ if (query === undefined || cache === undefined || storage === undefined || store === undefined) {
999
+ throw new Error('forge-panel: change request states need the sessionQuery, sessionProjectionCache, storageDomain, and sessions services')
1000
+ }
1001
+ const visibleUrls = (session: Session): string[] => ctx.forgeSession.changeRequests(session).map(entry => entry.url)
1002
+ this.states = new ChangeRequestStates({
1003
+ sessions: async signal => (await query.listSessions(signal)).map(({ header }) => {
1004
+ const live = store.get(header.id)
1005
+ if (live !== undefined) return { id: header.id, urls: visibleUrls(live) }
1006
+ const bindings = cache.cachedSnapshot(header, ['forgeChangeRequests'])?.values.forgeChangeRequests
1007
+ return { id: header.id, urls: bindings?.filter(binding => !binding.dismissed).map(binding => binding.url) }
1008
+ }),
1009
+ onBindings: listener => ctx.sessionProjections.onChanged((session, key) => {
1010
+ if (key === 'forgeChangeRequests') listener(session.id, visibleUrls(session))
1011
+ }),
1012
+ refOf: url => ctx.forge.changeRequestFromUrl(url),
1013
+ watch: (ref, listener) => ctx.forge.watch(ref, listener),
1014
+ open: async () => {
1015
+ const domain = await storage.open(changeRequestStatesDomain)
1016
+ return { table: domain.table('states'), close: () => domain.close() }
1017
+ },
1018
+ report: (error) => { ctx.logger.warn(`forge-panel: storing a change request state failed: ${String(error)}`) },
1019
+ })
1020
+ return this.states
1021
+ }
1022
+
1023
+ private panelOf(session: Session): SessionPanel {
1024
+ let panel = this.panels.get(session)
1025
+ if (panel === undefined) {
1026
+ const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, () => {
1027
+ if (this.panels.get(session) !== created) return
1028
+ this.panels.delete(session)
1029
+ void created.dispose()
1030
+ })
1031
+ panel = created
1032
+ this.panels.set(session, panel)
1033
+ }
1034
+ return panel
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * Whether a value names a full commit object name.
1040
+ * @param value - the value from the browser.
1041
+ * @returns whether it is 40 or 64 hexadecimal digits.
1042
+ */
1043
+ function isCommit(value: string): boolean {
1044
+ return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value)
1045
+ }
1046
+
1047
+ /**
1048
+ * Whether a line comment from the browser names a path, consecutive positive lines, and text.
1049
+ * @param comment - the comment.
1050
+ * @returns whether a provider may write it.
1051
+ */
1052
+ function validComment(comment: ForgeLineComment): boolean {
1053
+ return comment.path !== '' && comment.body.trim() !== '' && Number.isSafeInteger(comment.startLine) && comment.startLine >= 1
1054
+ && Number.isSafeInteger(comment.endLine) && comment.endLine >= comment.startLine
1055
+ }
1056
+
1057
+ /**
1058
+ * Whether a review write from the browser names its target and carries text where the write needs it.
1059
+ * @param write - the write.
1060
+ * @returns whether a provider may perform it.
1061
+ */
1062
+ function validWrite(write: ForgeReviewWrite): boolean {
1063
+ switch (write.kind) {
1064
+ case 'reply': return write.thread !== '' && write.body.trim() !== ''
1065
+ case 'resolve': return write.thread !== ''
1066
+ case 'edit-comment': return write.comment !== '' && write.body.trim() !== ''
1067
+ case 'delete-comment': return write.comment !== ''
1068
+ case 'add-pending': return validComment(write.comment)
1069
+ case 'submit-pending': return write.review !== '' && (write.event !== 'request-changes' || write.body.trim() !== '')
1070
+ case 'discard-pending': return write.review !== ''
1071
+ /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
1072
+ default: return assertNever(write, 'ForgeReviewWrite.kind')
1073
+ }
1074
+ }
1075
+
1076
+ /**
1077
+ * Report why the code host did not provide a diff or file.
1078
+ * @param failure - the provider's failure.
1079
+ * @returns `forgePanel/diff-too-large` for an answer over a size limit, `forgePanel/stale-head` for a head that moved,
1080
+ * else `forgePanel/diff-failed`, with the provider's message.
1081
+ */
1082
+ function readError(failure: ForgeFailure): RemoteError {
1083
+ switch (failure.code) {
1084
+ case 'too-large': return new RemoteError('forgePanel/diff-too-large', failure.message, {})
1085
+ case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
1086
+ case 'not-found':
1087
+ case 'unauthenticated':
1088
+ case 'unsupported':
1089
+ case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {})
1090
+ /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
1091
+ default: return assertNever(failure.code, 'ForgeFailure.code')
1092
+ }
1093
+ }
1094
+
1095
+ /**
1096
+ * Report why the code host did not provide review threads.
1097
+ * @param failure - the provider's failure.
1098
+ * @returns `forgePanel/stale-head` for a head that moved, `forgePanel/review-unsupported` for a provider without
1099
+ * review reads, else `forgePanel/review-failed`, with the provider's message.
1100
+ */
1101
+ function reviewError(failure: ForgeFailure): RemoteError {
1102
+ switch (failure.code) {
1103
+ case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
1104
+ case 'unsupported': return new RemoteError('forgePanel/review-unsupported', failure.message, {})
1105
+ case 'not-found':
1106
+ case 'unauthenticated':
1107
+ case 'too-large':
1108
+ case 'unavailable': return new RemoteError('forgePanel/review-failed', failure.message, {})
1109
+ /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
1110
+ default: return assertNever(failure.code, 'ForgeFailure.code')
1111
+ }
1112
+ }
1113
+
1114
+ /**
1115
+ * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, a missing base branch, and chosen
1116
+ * commits that are not on the branch as Remote errors.
1117
+ * @param reading - the read.
1118
+ * @returns what the read returned.
1119
+ */
1120
+ async function diffing<T>(reading: Promise<T>): Promise<T> {
1121
+ try {
1122
+ return await reading
1123
+ } catch (error) {
1124
+ if (error instanceof FilterConfigError) throw new RemoteError('forgePanel/filter-config-failed', error.message, {}, { cause: error })
1125
+ if (error instanceof DiffTooLarge) throw new RemoteError('forgePanel/diff-too-large', error.message, {}, { cause: error })
1126
+ if (error instanceof NoForkPoint) throw new RemoteError('forgePanel/no-fork-point', error.message, {}, { cause: error })
1127
+ if (error instanceof BaseMissing) throw new RemoteError('forgePanel/base-missing', error.message, {}, { cause: error })
1128
+ if (error instanceof CommitsMissing) throw new RemoteError('forgePanel/commits-missing', error.message, {}, { cause: error })
1129
+ if (error instanceof CommitsNotLinear) throw new RemoteError('forgePanel/commits-not-linear', error.message, {}, { cause: error })
1130
+ throw error
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * Report a failed change request action, separating a head that moved since the user confirmed it.
1136
+ * @param failure - the provider's failure.
1137
+ * @returns the Remote error to throw.
1138
+ */
1139
+ function actionError(failure: ForgeActionFailure): RemoteError {
1140
+ const code = failure.code === 'stale' ? 'forgePanel/stale-head' : failure.code === 'unknown' ? 'forgePanel/action-unknown'
1141
+ : 'forgePanel/action-failed'
1142
+ return new RemoteError(code, failure.message, {})
1143
+ }
1144
+
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
+ export default ForgePanelController