@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
@@ -0,0 +1,576 @@
1
+ /** The worktree a Session requests before it starts: its record, its projection, and its creation. */
2
+
3
+ import { isAbsolute, relative, sep } from 'node:path'
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
6
+ import { CREATED_RECORD, createdWorktreeSchema, generatedWorktreeName } from '@deepseek-ai/dsh-experimental-worktree'
7
+ import type { CreatedWorktree, CreateWorktreePhase } from '@deepseek-ai/dsh-experimental-worktree'
8
+ import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'
9
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
10
+ import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
11
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
12
+ import type {} from '@deepseek-ai/dsh-working-directory'
13
+ import { z } from 'zod'
14
+ import type {
15
+ ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState,
16
+ ForgeWorktreeWaiting, WorktreeRecord,
17
+ } from './types.ts'
18
+
19
+ /** Plugin record type of worktree requests, withdrawals, and creations. */
20
+ export const WORKTREE_RECORD = 'plugin:client-ui-forge/worktree'
21
+
22
+ const EMPTY: Omit<ForgeWorktreeState, 'cwd'> = { request: null, created: null, locked: false, stepped: false, restoring: false }
23
+
24
+ const worktreeSchema: z.ZodType<ForgeSessionWorktree> = z.object({
25
+ path: z.string().min(1),
26
+ branch: z.string().min(1),
27
+ from: z.string().min(1).nullable(),
28
+ baseCommit: z.string().min(1),
29
+ repositoryRoot: z.string().min(1),
30
+ }).strict()
31
+
32
+ const recordSchema: z.ZodType<WorktreeRecord> = z.discriminatedUnion('action', [
33
+ z.object({ action: z.literal('request'), from: z.string().min(1).nullable() }).strict(),
34
+ z.object({ action: z.literal('cancel') }).strict(),
35
+ z.object({ action: z.literal('created'), worktree: worktreeSchema }).strict(),
36
+ z.object({ action: z.literal('restoring') }).strict(),
37
+ z.object({ action: z.literal('restored') }).strict(),
38
+ ])
39
+
40
+ const stateSchema: z.ZodType<ForgeWorktreeState> = z.object({
41
+ request: z.object({ from: z.string().min(1).nullable() }).strict().nullable(),
42
+ created: worktreeSchema.nullable(),
43
+ locked: z.boolean(),
44
+ stepped: z.boolean(),
45
+ restoring: z.boolean(),
46
+ cwd: z.string().min(1).nullable(),
47
+ }).strict()
48
+
49
+ /**
50
+ * The `forgeWorktree` unit. `request` and `cancel` records change the request
51
+ * until the first `turn/start` or creation; the first creation of an open
52
+ * request applies until the first `step/start`, read from the worktree
53
+ * service's `plugin:worktree/created` record, or from the `created` record that
54
+ * earlier panels wrote. Records outside those periods leave the state
55
+ * unchanged. The unit also follows the Session's working directory, so
56
+ * clients, including the Session summary, see the created worktree only while
57
+ * that directory is the worktree or lies below it. Restoration records retain
58
+ * incomplete checkout recovery across reloads.
59
+ */
60
+ export const forgeWorktreeProjection = {
61
+ key: 'forgeWorktree',
62
+ stateVersion: 5,
63
+ stateSchema,
64
+ init: header => ({ ...EMPTY, cwd: header.cwd ?? null }),
65
+ apply,
66
+ wire: {
67
+ viewSchema: worktreeSchema.nullable(),
68
+ view: state => state.created !== null && state.cwd !== null && within(state.created.path, state.cwd) ? state.created : null,
69
+ },
70
+ } satisfies ProjectionDefinition<'forgeWorktree', ForgeWorktreeState>
71
+
72
+ /**
73
+ * Whether `path` is `root` or lies below it.
74
+ * @param root - absolute directory.
75
+ * @param path - absolute path.
76
+ * @returns whether `root` contains `path`.
77
+ */
78
+ export function within(root: string, path: string): boolean {
79
+ const rest = relative(root, path)
80
+ return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest))
81
+ }
82
+
83
+ /**
84
+ * The text of a failure: an Error's message, or else the thrown value as a string.
85
+ * @param error - what was thrown.
86
+ * @returns the text.
87
+ */
88
+ export function messageOf(error: unknown): string {
89
+ return error instanceof Error ? error.message : String(error)
90
+ }
91
+
92
+ function apply(state: ForgeWorktreeState, event: SessionEvent): ForgeWorktreeState {
93
+ switch (event.type) {
94
+ case 'turn/start':
95
+ return state.locked ? state : { ...state, locked: true }
96
+ case 'step/start':
97
+ return state.stepped ? state : { ...state, stepped: true }
98
+ case 'working-directory/change':
99
+ return state.cwd === event.data.cwd ? state : { ...state, cwd: event.data.cwd }
100
+ // Every other event type, including plugin records, which sit outside SessionEventMap.
101
+ default:
102
+ return applyRecord(state, event)
103
+ }
104
+ }
105
+
106
+ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorktreeState {
107
+ const record = pluginRecordOf(event)
108
+ if (record?.type === CREATED_RECORD) {
109
+ const created = createdWorktreeSchema.safeParse(record.data)
110
+ return !created.success || state.created !== null || state.stepped || state.request === null
111
+ ? state
112
+ : { ...state, created: { ...created.data, from: state.request.from } }
113
+ }
114
+ if (record?.type !== WORKTREE_RECORD) return state
115
+ const parsed = recordSchema.safeParse(record.data)
116
+ if (!parsed.success) return state
117
+ const data = parsed.data
118
+ const settled = state.created !== null
119
+ switch (data.action) {
120
+ case 'request':
121
+ return state.locked || settled ? state : { ...state, request: { from: data.from } }
122
+ case 'cancel':
123
+ return state.locked || settled || state.request === null ? state : { ...state, request: null }
124
+ case 'created':
125
+ return settled || state.stepped || state.request === null ? state : { ...state, created: data.worktree }
126
+ case 'restoring':
127
+ return !settled || state.restoring ? state : { ...state, restoring: true }
128
+ case 'restored':
129
+ return !state.restoring ? state : { ...state, restoring: false }
130
+ /* v8 ignore next -- closed WorktreeRecord action union exhaustiveness guard */
131
+ default: return assertNever(data, 'WorktreeRecord.action')
132
+ }
133
+ }
134
+
135
+ /** A failed attempt to create a requested worktree; `cause` holds the worktree service's error. */
136
+ export class CreationFailure extends Error {
137
+ /**
138
+ * @param branch - branch the attempt created.
139
+ * @param phase - step that failed.
140
+ * @param reason - the worktree service's failure text.
141
+ * @param cause - the worktree service's error.
142
+ */
143
+ constructor(readonly branch: string, readonly phase: CreateWorktreePhase, readonly reason: string, cause: unknown) {
144
+ super(`The requested worktree ${branch} could not be created`, { cause })
145
+ this.name = 'CreationFailure'
146
+ }
147
+ }
148
+
149
+ /**
150
+ * The failure a waiting message shows for an attempt.
151
+ * @param error - what the attempt threw.
152
+ * @param from - base branch of the attempt, or null for HEAD.
153
+ * @returns the failure.
154
+ */
155
+ function failureOf(error: unknown, from: string | null): ForgeWorktreeFailure {
156
+ return error instanceof CreationFailure
157
+ ? { branch: error.branch, from, phase: error.phase, message: error.reason }
158
+ : { branch: null, from, phase: 'prepare', message: messageOf(error) }
159
+ }
160
+
161
+ /** Work on a Session's checkout that runs as maintenance of its Agent. */
162
+ export type HeldWork = (agent: Agent, signal: AbortSignal) => Promise<void>
163
+
164
+ /** A message's wait for the creation of the requested worktree. */
165
+ interface CreationHold {
166
+ readonly kind: 'creation'
167
+ /** Stops the running attempt. */
168
+ stop: AbortController | undefined
169
+ /** The wait for the next decision: another attempt, or reading the request again. */
170
+ next: PromiseWithResolvers<'retry' | 'recheck'> | undefined
171
+ }
172
+
173
+ /** A message's wait for the restoration or leaving of the removed worktree the Session works in. */
174
+ interface RestorationHold {
175
+ readonly kind: 'restoration'
176
+ /** Whether the check found the worktree gone. */
177
+ waiting: boolean
178
+ /** The wait for the work that restores or leaves the worktree, with its outcome. */
179
+ next: PromiseWithResolvers<{ readonly work: HeldWork; readonly done: PromiseWithResolvers<void> }> | undefined
180
+ }
181
+
182
+ type Hold = CreationHold | RestorationHold
183
+
184
+ /**
185
+ * Creates requested worktrees, one attempt with a new branch name per call,
186
+ * and holds the turn of a message while the Session's worktree is not ready.
187
+ * A hold is maintenance of the Session's Agent that starts while the message
188
+ * enters the inbox, before the delivery wakes the Agent, so the Agent starts
189
+ * the message's turn once the hold ends. A creation hold makes an attempt
190
+ * and, after a failed or stopped one, waits for another attempt or for the
191
+ * request to be withdrawn; a restoration hold checks the worktree the Session
192
+ * works in and, when it is gone, waits until it is restored or left. The
193
+ * Agent's cancellation and the panel's stop end a hold. The first step
194
+ * proposal of a Session whose request is still open also creates the
195
+ * worktree, which covers a message no hold took. The worktree service enters
196
+ * the created checkout and queues its directory notice; at a step proposal
197
+ * the notice joins the proposed messages so the first request already names
198
+ * the new directory, a proposal without messages leaves it queued, and a
199
+ * failure ends the turn with the request still open. A failed attempt may
200
+ * leave its branch or checkout behind.
201
+ */
202
+ export class WorktreeCreations {
203
+ private readonly live = new Map<Session, ForgeWorktreeCreation>()
204
+ private readonly restorations = new Map<Session, ForgeWorktreeRestoration>()
205
+ private readonly failures = new Map<Session, ForgeWorktreeFailure>()
206
+ private readonly holds = new Map<Session, Hold>()
207
+ private readonly lifetime = new AbortController()
208
+ private readonly pending = new Set<Promise<unknown>>()
209
+ /** Stop admission, cancel operations, and wait for their final callbacks. */
210
+ readonly dispose: () => Promise<void>
211
+
212
+ /**
213
+ * @param ctx - context that optionally provides `worktrees`.
214
+ * @param states - reads the `forgeWorktree` projection of a Session.
215
+ * @param prefix - branch name prefix that `generatedWorktreeName` combines with the Session id and random digits.
216
+ * @param changed - called after the creation or restoration of a Session starts, changes phase, or ends, after its
217
+ * failure changes, and after a wait starts or ends.
218
+ */
219
+ constructor(
220
+ private readonly ctx: Context,
221
+ private readonly states: ProjectionHandle<ForgeWorktreeState>,
222
+ private readonly prefix: string,
223
+ private readonly changed: (session: Session) => void,
224
+ ) {
225
+ ctx.on('agent/pre-step', async ({ agent, step, signal }, next): Promise<PreStepDecision> => await this.preStep(agent, step, signal, next))
226
+ this.dispose = ctx.effect(() => async () => {
227
+ this.lifetime.abort(new Error('The forge panel stopped'))
228
+ await Promise.allSettled(this.pending)
229
+ }, 'forge-panel: stop worktree operations')
230
+ }
231
+
232
+ /**
233
+ * Read the running creation of a Session.
234
+ * @param session - Session to read.
235
+ * @returns the running creation, or null.
236
+ */
237
+ of(session: Session): ForgeWorktreeCreation | null {
238
+ return this.live.get(session) ?? null
239
+ }
240
+
241
+ /**
242
+ * Read the running restoration of a Session.
243
+ * @param session - Session to read.
244
+ * @returns the running restoration, or null.
245
+ */
246
+ restorationOf(session: Session): ForgeWorktreeRestoration | null {
247
+ return this.restorations.get(session) ?? null
248
+ }
249
+
250
+ /**
251
+ * Read the failed attempt that a waiting message saw last.
252
+ * @param session - Session to read.
253
+ * @returns the failure, or null.
254
+ */
255
+ failureOf(session: Session): ForgeWorktreeFailure | null {
256
+ return this.failures.get(session) ?? null
257
+ }
258
+
259
+ /**
260
+ * Read what a message of a Session waits for before its turn starts.
261
+ * @param session - Session to read.
262
+ * @returns the creation or restoration the message waits for, or null while none waits.
263
+ */
264
+ waitingOf(session: Session): ForgeWorktreeWaiting | null {
265
+ const hold = this.holds.get(session)
266
+ if (hold === undefined || (hold.kind === 'restoration' && !hold.waiting)) return null
267
+ return hold.kind
268
+ }
269
+
270
+ /**
271
+ * Forget the failure of a Session whose request changes or is withdrawn; the record of that change republishes the panel.
272
+ * @param session - Session whose failure no longer applies.
273
+ */
274
+ forget(session: Session): void {
275
+ this.failures.delete(session)
276
+ }
277
+
278
+ /**
279
+ * Hold the turn of a message entering the inbox of a Session whose
280
+ * requested worktree does not exist yet, and create the worktree. Call it
281
+ * while the message enters, before the delivery wakes the Agent. A Session
282
+ * already held, or an Agent with other work, gets no new hold.
283
+ * @param agent - Agent of the Session.
284
+ */
285
+ holdCreation(agent: Agent): void {
286
+ this.hold(agent, { kind: 'creation', stop: undefined, next: undefined }, (hold, signal) => this.runCreation(agent, hold, signal))
287
+ }
288
+
289
+ /**
290
+ * Hold the turn of a message entering the inbox of a Session that works in
291
+ * its created worktree while `check` decides whether that worktree is gone,
292
+ * and until it is restored or left when it is. Call it while the message
293
+ * enters, before the delivery wakes the Agent. A Session already held, or an
294
+ * Agent with other work, gets no new hold.
295
+ * @param agent - Agent of the Session.
296
+ * @param check - answers whether the worktree is gone; a rejection lets the message go on.
297
+ */
298
+ holdRestoration(agent: Agent, check: (signal: AbortSignal) => Promise<ForgeMissingWorktree | null>): void {
299
+ this.hold(agent, { kind: 'restoration', waiting: false, next: undefined }, (hold, signal) => this.runRestoration(agent, hold, check, signal))
300
+ }
301
+
302
+ /**
303
+ * Make another attempt for the message that waits after a failed or stopped one.
304
+ * @param session - Session whose message waits.
305
+ * @returns whether a waiting message without a running attempt took the decision.
306
+ */
307
+ retry(session: Session): boolean {
308
+ const hold = this.holds.get(session)
309
+ if (hold?.kind !== 'creation' || hold.next === undefined) return false
310
+ hold.next.resolve('retry')
311
+ return true
312
+ }
313
+
314
+ /**
315
+ * Read the request again after it changed; a withdrawn request lets the waiting message go on.
316
+ * @param session - Session whose request changed.
317
+ */
318
+ recheck(session: Session): void {
319
+ const hold = this.holds.get(session)
320
+ if (hold?.kind === 'creation') hold.next?.resolve('recheck')
321
+ }
322
+
323
+ /**
324
+ * Run work on the removed worktree a message waits for, inside the wait; its success lets the message go on.
325
+ * @param session - Session whose message waits.
326
+ * @param work - restores or leaves the worktree.
327
+ * @returns the work's outcome, or undefined when no message waits for the removed worktree.
328
+ */
329
+ within(session: Session, work: HeldWork): Promise<void> | undefined {
330
+ const hold = this.holds.get(session)
331
+ if (hold?.kind !== 'restoration' || hold.next === undefined) return undefined
332
+ const done = Promise.withResolvers<void>()
333
+ hold.next.resolve({ work, done })
334
+ return done.promise
335
+ }
336
+
337
+ /**
338
+ * Stop the running attempt a message waits for; the message keeps waiting
339
+ * with the request still open. Without such an attempt the Session is unchanged.
340
+ * @param session - Session whose attempt stops.
341
+ */
342
+ stop(session: Session): void {
343
+ const hold = this.holds.get(session)
344
+ if (hold?.kind === 'creation') hold.stop?.abort(new Error('The worktree creation was stopped'))
345
+ }
346
+
347
+ /**
348
+ * Check the removed worktree of a Session out again through the worktree
349
+ * service; the running restoration is readable through
350
+ * {@link WorktreeCreations.restorationOf} until it ends.
351
+ * @param agent - Agent of the Session.
352
+ * @param worktrees - the worktree service.
353
+ * @param created - the worktree the Session created.
354
+ * @param signal - cancellation of the restoration.
355
+ * @param restored - runs once the checkout is back, before the restoration ends, so both changes publish together.
356
+ * @param available - checks whether the recorded checkout is already usable, within this operation's lifetime.
357
+ * @throws the worktree service's error when the restoration fails; the cancellation reason once `signal` aborts.
358
+ */
359
+ async restore(
360
+ agent: Agent,
361
+ worktrees: Context['worktrees'],
362
+ created: ForgeSessionWorktree,
363
+ signal: AbortSignal,
364
+ restored: () => void,
365
+ available: (signal: AbortSignal) => Promise<boolean>,
366
+ ): Promise<void> {
367
+ await this.run(signal, async (operation) => {
368
+ const usable = await available(operation)
369
+ operation.throwIfAborted()
370
+ if (!usable) await this.restoreCheckout(agent, worktrees, created, operation, restored)
371
+ })
372
+ }
373
+
374
+ private async restoreCheckout(
375
+ agent: Agent,
376
+ worktrees: Context['worktrees'],
377
+ created: ForgeSessionWorktree,
378
+ signal: AbortSignal,
379
+ restored: () => void,
380
+ ): Promise<void> {
381
+ const session = agent.session
382
+ appendPluginRecord(session, WORKTREE_RECORD, { action: 'restoring' })
383
+ try {
384
+ await worktrees.restore(agent, created, signal, (phase) => {
385
+ this.restorations.set(session, { phase })
386
+ this.changed(session)
387
+ })
388
+ signal.throwIfAborted()
389
+ appendPluginRecord(session, WORKTREE_RECORD, { action: 'restored' })
390
+ restored()
391
+ } finally {
392
+ this.restorations.delete(session)
393
+ this.changed(session)
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Create a Session's requested worktree with a new branch name, enter it, and
399
+ * record it on the Session. The running creation is readable through
400
+ * {@link WorktreeCreations.of} until the record exists or the attempt fails.
401
+ * @param agent - Agent of the Session.
402
+ * @param from - base branch, or null for HEAD of the current checkout.
403
+ * @param signal - cancellation of the attempt.
404
+ * @param held - whether a message waits for the creation before its turn starts.
405
+ * @returns the created worktree.
406
+ * @throws {@link CreationFailure} when the attempt fails; the cancellation reason once `signal` aborts.
407
+ */
408
+ async create(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise<CreatedWorktree> {
409
+ return await this.run(signal, operation => this.createCheckout(agent, from, operation, held))
410
+ }
411
+
412
+ private async createCheckout(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise<CreatedWorktree> {
413
+ const worktrees = this.ctx.get('worktrees')
414
+ if (worktrees === undefined) throw new Error('No worktree service is mounted')
415
+ const session = agent.session
416
+ let status: ForgeWorktreeCreation = { phase: 'prepare', branch: generatedWorktreeName(this.prefix, session.id), from, held }
417
+ this.failures.delete(session)
418
+ this.live.set(session, status)
419
+ this.changed(session)
420
+ try {
421
+ let created: CreatedWorktree
422
+ try {
423
+ created = await worktrees.create(agent, { name: status.branch, ...from === null ? {} : { from } }, signal, (phase) => {
424
+ status = { ...status, phase }
425
+ this.live.set(session, status)
426
+ this.changed(session)
427
+ })
428
+ } catch (error) {
429
+ signal.throwIfAborted()
430
+ throw new CreationFailure(status.branch, status.phase, messageOf(error), error)
431
+ }
432
+ signal.throwIfAborted()
433
+ return created
434
+ } finally {
435
+ // After the service's `plugin:worktree/created` record, so a follower never sees the creation end without its result.
436
+ this.live.delete(session)
437
+ this.changed(session)
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Run a hold as maintenance of the Agent, which latches the delivery's wake until the hold ends.
443
+ * @param agent - Agent of the Session.
444
+ * @param hold - the hold's state.
445
+ * @param body - waits for the worktree; settles once the message may go on.
446
+ */
447
+ private hold<H extends Hold>(agent: Agent, hold: H, body: (hold: H, signal: AbortSignal) => Promise<void>): void {
448
+ if (this.lifetime.signal.aborted) return
449
+ const session = agent.session
450
+ if (this.holds.has(session)) return
451
+ let task: Promise<void>
452
+ try {
453
+ task = agent.runMaintenance(async (maintenance) => {
454
+ // Leave the inbox mutation that announced the message before the hold touches the Session.
455
+ await Promise.resolve()
456
+ try {
457
+ await body(hold, AbortSignal.any([maintenance, this.lifetime.signal]))
458
+ } catch (error) {
459
+ void error // Only the Agent's cancellation or disposal and the panel's stop reject a hold's waits; each ends it.
460
+ } finally {
461
+ this.holds.delete(session)
462
+ this.failures.delete(session)
463
+ this.changed(session)
464
+ }
465
+ })
466
+ } catch (error) {
467
+ void error // A running turn or other maintenance owns the Agent, so the message takes its usual path.
468
+ return
469
+ }
470
+ this.holds.set(session, hold)
471
+ void this.join(task)
472
+ }
473
+
474
+ private async run<T>(signal: AbortSignal, body: (signal: AbortSignal) => Promise<T>): Promise<T> {
475
+ const operation = AbortSignal.any([signal, this.lifetime.signal])
476
+ operation.throwIfAborted()
477
+ return await this.join(body(operation))
478
+ }
479
+
480
+ private async join<T>(task: Promise<T>): Promise<T> {
481
+ this.pending.add(task)
482
+ try {
483
+ return await task
484
+ } finally {
485
+ this.pending.delete(task)
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Make attempts until one creates the worktree or the request no longer asks
491
+ * for one, waiting for a decision after each failed or stopped attempt.
492
+ */
493
+ private async runCreation(agent: Agent, hold: CreationHold, signal: AbortSignal): Promise<void> {
494
+ const session = agent.session
495
+ for (;;) {
496
+ const state = this.states.stateOf(session)
497
+ if (state.request === null || state.created !== null || state.locked) return
498
+ const stop = new AbortController()
499
+ hold.stop = stop
500
+ try {
501
+ await this.create(agent, state.request.from, AbortSignal.any([signal, stop.signal]), true)
502
+ return
503
+ } catch (error) {
504
+ signal.throwIfAborted()
505
+ if (stop.signal.aborted) this.failures.delete(session)
506
+ else this.failures.set(session, failureOf(error, state.request.from))
507
+ this.changed(session)
508
+ } finally {
509
+ hold.stop = undefined
510
+ }
511
+ while (await this.wait(hold, signal) !== 'retry') {
512
+ const current = this.states.stateOf(session)
513
+ if (current.request === null || current.created !== null || current.locked) return
514
+ }
515
+ }
516
+ }
517
+
518
+ /** Check the worktree the Session works in and, when it is gone, run the work that restores or leaves it until one succeeds. */
519
+ private async runRestoration(
520
+ agent: Agent,
521
+ hold: RestorationHold,
522
+ check: (signal: AbortSignal) => Promise<ForgeMissingWorktree | null>,
523
+ signal: AbortSignal,
524
+ ): Promise<void> {
525
+ let missing: ForgeMissingWorktree | null
526
+ try {
527
+ missing = await check(signal)
528
+ } catch (error) {
529
+ // Without an answer from the filesystem or Git the panel offers no restoration, so the message goes on.
530
+ signal.throwIfAborted()
531
+ void error
532
+ return
533
+ }
534
+ if (missing === null) return
535
+ hold.waiting = true
536
+ this.changed(agent.session)
537
+ for (;;) {
538
+ const { work, done } = await this.wait(hold, signal)
539
+ try {
540
+ await work(agent, signal)
541
+ } catch (error) {
542
+ done.reject(error)
543
+ signal.throwIfAborted()
544
+ continue
545
+ }
546
+ done.resolve()
547
+ return
548
+ }
549
+ }
550
+
551
+ /** Wait for the next decision on a hold; rejects with the abort reason once `signal` aborts. */
552
+ private async wait<T>(hold: { next: PromiseWithResolvers<T> | undefined }, signal: AbortSignal): Promise<T> {
553
+ signal.throwIfAborted()
554
+ const next = Promise.withResolvers<T>()
555
+ hold.next = next
556
+ const abort = (): void => { next.reject(signal.reason) }
557
+ signal.addEventListener('abort', abort, { once: true })
558
+ try {
559
+ return await next.promise
560
+ } finally {
561
+ signal.removeEventListener('abort', abort)
562
+ hold.next = undefined
563
+ }
564
+ }
565
+
566
+ private async preStep(agent: Agent, step: number, signal: AbortSignal, next: () => Promise<PreStepDecision>): Promise<PreStepDecision> {
567
+ const state = this.states.stateOf(agent.session)
568
+ if (step !== 1 || state.request === null || state.created !== null || state.stepped) return await next()
569
+ await this.create(agent, state.request.from, signal, false)
570
+ const decision = await next()
571
+ if (decision.kind === 'reject' || decision.messages.length === 0) return decision
572
+ const notices = agent.inbox.nextStep.filter(message => message.source.kind === 'working-directory')
573
+ for (const notice of notices) agent.inbox.remove(notice.id)
574
+ return notices.length === 0 ? decision : { ...decision, messages: [...decision.messages, ...notices] }
575
+ }
576
+ }