@bevel-software/platform-core-frontend 0.1.0

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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/package.json +70 -0
  3. package/src/core/CoreAppShell.tsx +444 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
  5. package/src/core/events.ts +29 -0
  6. package/src/core/registry.ts +336 -0
  7. package/src/css-side-effect-imports.d.ts +7 -0
  8. package/src/html-extensions.ts +12 -0
  9. package/src/index.css +49 -0
  10. package/src/index.ts +23 -0
  11. package/src/lib/api.ts +57 -0
  12. package/src/lib/utils.ts +138 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
  14. package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
  15. package/src/modules/access/api.ts +205 -0
  16. package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
  17. package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
  18. package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
  19. package/src/modules/access/hooks/useFileAccess.ts +151 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
  22. package/src/modules/admin/services/admin.api.ts +92 -0
  23. package/src/modules/admin/services/roles.api.ts +136 -0
  24. package/src/modules/admin/state/admin.context.tsx +223 -0
  25. package/src/modules/auth/components/LoginScreen.tsx +135 -0
  26. package/src/modules/auth/hooks/useAuthState.ts +59 -0
  27. package/src/modules/auth/services/auth.api.ts +24 -0
  28. package/src/modules/auth/services/microsoft-oauth.ts +57 -0
  29. package/src/modules/auth/state/auth.context.ts +18 -0
  30. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
  31. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
  32. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
  33. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
  34. package/src/modules/git/__tests__/git.api.test.ts +113 -0
  35. package/src/modules/git/__tests__/pr.api.test.ts +44 -0
  36. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
  37. package/src/modules/git/components/BranchSwitcher.tsx +527 -0
  38. package/src/modules/git/components/DiffView.tsx +30 -0
  39. package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
  40. package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
  41. package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
  42. package/src/modules/git/components/PullNeededBanner.tsx +204 -0
  43. package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
  44. package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
  45. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
  46. package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
  47. package/src/modules/git/hooks/useGitState.ts +335 -0
  48. package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
  49. package/src/modules/git/services/error-messages.ts +257 -0
  50. package/src/modules/git/services/git.api.ts +163 -0
  51. package/src/modules/git/services/pr-prompts.ts +159 -0
  52. package/src/modules/git/services/pr.api.ts +39 -0
  53. package/src/modules/git/state/auto-update.context.ts +21 -0
  54. package/src/modules/git/state/git.context.ts +82 -0
  55. package/src/modules/layout/components/AppLayout.tsx +40 -0
  56. package/src/modules/layout/components/DemoBanner.tsx +57 -0
  57. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
  58. package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
  59. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
  60. package/src/modules/layout/components/SlideOverlay.tsx +224 -0
  61. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
  62. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
  63. package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
  64. package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
  65. package/src/modules/layout/state/layout.context.ts +46 -0
  66. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
  67. package/src/modules/library/__tests__/diff.test.ts +62 -0
  68. package/src/modules/library/__tests__/loadout.test.tsx +72 -0
  69. package/src/modules/library/__tests__/status.test.ts +117 -0
  70. package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
  71. package/src/modules/library/components/CompareView.tsx +357 -0
  72. package/src/modules/library/components/DetailDialog.tsx +566 -0
  73. package/src/modules/library/components/GearIcon.tsx +12 -0
  74. package/src/modules/library/components/LibraryCard.tsx +132 -0
  75. package/src/modules/library/components/LibraryPage.tsx +254 -0
  76. package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
  77. package/src/modules/library/components/StatusGem.tsx +21 -0
  78. package/src/modules/library/components/SuggestChange.tsx +171 -0
  79. package/src/modules/library/components/particles.ts +50 -0
  80. package/src/modules/library/hooks/useLibraryData.ts +119 -0
  81. package/src/modules/library/hooks/useSkillDetail.ts +74 -0
  82. package/src/modules/library/library.css +320 -0
  83. package/src/modules/library/services/library.api.ts +164 -0
  84. package/src/modules/library/state/loadout.tsx +129 -0
  85. package/src/modules/library/state/toast.tsx +42 -0
  86. package/src/modules/library/utils/diff.ts +102 -0
  87. package/src/modules/library/utils/status.ts +116 -0
  88. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
  89. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
  90. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
  91. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
  92. package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
  93. package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
  94. package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
  96. package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
  97. package/src/modules/pr/components/PrCancelButton.tsx +99 -0
  98. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
  99. package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
  100. package/src/modules/pr/components/PrCommentThread.tsx +168 -0
  101. package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
  102. package/src/modules/pr/components/PrDiffPane.tsx +425 -0
  103. package/src/modules/pr/components/PrFileRow.tsx +164 -0
  104. package/src/modules/pr/components/PrFilesList.tsx +53 -0
  105. package/src/modules/pr/components/PrHeader.tsx +45 -0
  106. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
  107. package/src/modules/pr/components/PrMergeButton.tsx +268 -0
  108. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
  109. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
  110. package/src/modules/pr/components/PrViewer.tsx +364 -0
  111. package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
  112. package/src/modules/pr/services/pr-approvals.api.ts +31 -0
  113. package/src/modules/pr/services/pr-cancel.api.ts +19 -0
  114. package/src/modules/pr/services/pr-comments.api.ts +45 -0
  115. package/src/modules/pr/services/pr-detail.api.ts +17 -0
  116. package/src/modules/pr/services/pr-merge.api.ts +53 -0
  117. package/src/modules/pr/services/pr-open.api.ts +30 -0
  118. package/src/modules/pr/state/pr-viewer.context.ts +34 -0
  119. package/src/modules/pr/utils/bucketize-comments.ts +55 -0
  120. package/src/modules/pr/utils/parsePatch.ts +57 -0
  121. package/src/modules/review/__tests__/review.api.test.ts +121 -0
  122. package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
  123. package/src/modules/review/components/DiffViewer.tsx +78 -0
  124. package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
  125. package/src/modules/review/components/ReviewFileRow.tsx +114 -0
  126. package/src/modules/review/components/ReviewPanel.tsx +260 -0
  127. package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
  128. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
  129. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
  130. package/src/modules/review/hooks/useReviewState.ts +256 -0
  131. package/src/modules/review/services/review.api.ts +72 -0
  132. package/src/modules/review/state/ReviewProvider.tsx +28 -0
  133. package/src/modules/review/state/review.context.ts +29 -0
  134. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
  135. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
  136. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
  137. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
  138. package/src/modules/secrets-vault/services/connect.api.ts +113 -0
  139. package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
  140. package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
  141. package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
  142. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
  144. package/src/modules/toolbar/components/Toolbar.tsx +123 -0
  145. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
  146. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
  147. package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
  148. package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
  149. package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
  150. package/src/modules/workflow/hooks/useFileLock.ts +430 -0
  151. package/src/modules/workflow/services/lock.api.ts +139 -0
  152. package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
  153. package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
  154. package/src/modules/workflow/state/event-bus.context.ts +75 -0
  155. package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
  156. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
  157. package/src/modules/workspace/components/EditorTabs.tsx +384 -0
  158. package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
  159. package/src/modules/workspace/components/FileRoute.tsx +392 -0
  160. package/src/modules/workspace/components/FileViewer.tsx +906 -0
  161. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
  162. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
  163. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
  164. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
  165. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
  166. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
  167. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
  168. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
  169. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
  170. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
  171. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
  172. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
  173. package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
  174. package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
  175. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
  176. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
  177. package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
  178. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
  179. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
  180. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
  181. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
  182. package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
  183. package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
  184. package/src/modules/workspace/components/renderers/index.ts +39 -0
  185. package/src/modules/workspace/components/renderers/types.ts +27 -0
  186. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
  189. package/src/modules/workspace/routing/kb-routes.ts +266 -0
  190. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
  191. package/src/modules/workspace/services/workspace.api.ts +185 -0
  192. package/src/modules/workspace/state/workspace.context.ts +235 -0
  193. package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
  194. package/src/modules/workspace/utils/diff.ts +53 -0
  195. package/src/modules/workspace/utils/fileTree.ts +179 -0
  196. package/src/modules/workspace/utils/frontmatter.ts +80 -0
  197. package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
  198. package/src/modules/workspace/utils/tab-persistence.ts +23 -0
  199. package/src/shared/components/Dialog.tsx +198 -0
  200. package/src/shared/components/PageShell.tsx +51 -0
  201. package/src/shared/components/useModalLayer.ts +35 -0
  202. package/src/shared/markdown/Markdown.tsx +62 -0
  203. package/src/test-setup.ts +59 -0
@@ -0,0 +1,257 @@
1
+ import { protectedBranchDisplayName } from '@bevel-software/platform-shared';
2
+ import { GitApiError } from './git.api';
3
+
4
+ /**
5
+ * Discriminator the backend's `NoSharedHistoryError` puts in the JSON body.
6
+ * Pinned here so the share dialog can render the agent-handoff affordance for
7
+ * draft branches that don't share history with their target. Drift with the
8
+ * backend literal is caught by the cross-package test that asserts both sides
9
+ * use the same string.
10
+ */
11
+ export const NO_SHARED_HISTORY_KIND = 'no-shared-history' as const;
12
+
13
+ /**
14
+ * Plain-language chat prompt seeded into the composer when the user clicks
15
+ * "Ask the assistant to resolve this" on the no-shared-history banner. Names
16
+ * the head + base so the agent fixes the right draft (the user might have
17
+ * several open) and steers it toward the two known recoveries — recreate
18
+ * from the right protected branch, or rebase onto it — without prescribing
19
+ * one over the other.
20
+ */
21
+ export const NO_SHARED_HISTORY_RECOVERY_PROMPT = (head: string, base: string): string => {
22
+ return [
23
+ `My draft "${head}" can't be proposed because it doesn't share history with "${base}".`,
24
+ 'It was likely started from an unrelated point or outside the app.',
25
+ 'Please investigate which protected branch it should have been forked from,',
26
+ 'then either recreate the draft on top of that branch or rebase it onto the right starting point —',
27
+ "whichever preserves my edits. Then I'll share the changes again.",
28
+ ].join(' ');
29
+ };
30
+
31
+ /**
32
+ * Structured form of a git error surfaced by the backend. The "plain" variant
33
+ * is the non-actionable case — render the message as static text. Typed
34
+ * variants carry the data the UI needs to render a recovery affordance.
35
+ */
36
+ export type GitErrorInfo =
37
+ | { kind: 'plain'; message: string }
38
+ | { kind: typeof NO_SHARED_HISTORY_KIND; message: string; head: string; base: string };
39
+
40
+ /**
41
+ * Parse a backend git/PR error into its structured form. Falls back to
42
+ * `{ kind: 'plain', message }` for any error we don't have a typed mapping
43
+ * for — same conservative contract as `friendlyGitError`.
44
+ */
45
+ export function parseGitError(err: unknown): GitErrorInfo {
46
+ const message = friendlyGitError(err);
47
+ if (err instanceof GitApiError && err.body && typeof err.body === 'object') {
48
+ const body = err.body as {
49
+ kind?: unknown;
50
+ head?: unknown;
51
+ base?: unknown;
52
+ };
53
+ if (
54
+ body.kind === NO_SHARED_HISTORY_KIND &&
55
+ typeof body.head === 'string' &&
56
+ typeof body.base === 'string' &&
57
+ body.head.length > 0 &&
58
+ body.base.length > 0
59
+ ) {
60
+ return {
61
+ kind: NO_SHARED_HISTORY_KIND,
62
+ message: friendlyNoSharedHistoryMessage(body.base),
63
+ head: body.head,
64
+ base: body.base,
65
+ };
66
+ }
67
+ }
68
+ return { kind: 'plain', message };
69
+ }
70
+
71
+ /**
72
+ * Plain-language summary of the no-shared-history failure. Resolves the
73
+ * protected base name to its glossary display form so the user reads
74
+ * "Target company state" instead of `target-company-state`.
75
+ */
76
+ function friendlyNoSharedHistoryMessage(base: string): string {
77
+ const baseName = protectedBranchDisplayName(base) ?? base;
78
+ return (
79
+ `This draft doesn't share history with the ${baseName} — it was likely started ` +
80
+ `from an unrelated point or outside the app. The assistant can investigate and ` +
81
+ `move your edits onto the right starting point so you can share them.`
82
+ );
83
+ }
84
+
85
+ /**
86
+ * Map backend git/PR error messages to plain-language text for non-technical users.
87
+ *
88
+ * The backend errors are phrased in git vocabulary ("branch", "commit", "push") because
89
+ * that's what the underlying CLI produces. Users never see those terms elsewhere in the
90
+ * product, so translate at the display boundary. Unknown messages fall through to the
91
+ * original string — it's better to show a slightly technical message than a misleading
92
+ * one we matched by accident.
93
+ */
94
+ export function friendlyGitError(err: unknown): string {
95
+ // Structured typed errors carry a `kind` discriminator in the body; give
96
+ // each one its full plain-language message here so callers that only need
97
+ // a string (no recovery affordance) still get the friendly text.
98
+ if (err instanceof GitApiError && err.body && typeof err.body === 'object') {
99
+ const body = err.body as {
100
+ kind?: unknown;
101
+ head?: unknown;
102
+ base?: unknown;
103
+ };
104
+ if (
105
+ body.kind === NO_SHARED_HISTORY_KIND &&
106
+ typeof body.head === 'string' &&
107
+ typeof body.base === 'string' &&
108
+ body.head.length > 0 &&
109
+ body.base.length > 0
110
+ ) {
111
+ return friendlyNoSharedHistoryMessage(body.base);
112
+ }
113
+ }
114
+
115
+ const raw = rawMessage(err);
116
+
117
+ // Protected-branch rejections — `branch` is always quoted. Under the
118
+ // current model the agent's writes against the official versions are NOT
119
+ // hard-rejected on the name alone; path-level access control decides at
120
+ // lock-acquisition. The only remaining ProtectedBranchError causes are
121
+ // structural — you can't *create* a name that collides with an official
122
+ // version, you can't *delete* one, and a change request *from* an
123
+ // official version makes no sense (it IS the version). The legacy
124
+ // "you can't save / share / undo directly, start a draft first" cases
125
+ // are gone: those went away with the access-at-lock-time refactor, and
126
+ // their friendlyGitError translations would only mislead the user now.
127
+ const protectedMatch = raw.match(
128
+ /^Branch "([^"]+)" is protected — (creating a protected branch|deleting a protected branch|opening a PR from a protected branch) is not allowed\.?$/,
129
+ );
130
+ if (protectedMatch) {
131
+ const [, branch, action] = protectedMatch;
132
+ switch (action) {
133
+ case 'creating a protected branch':
134
+ return `The name "${branch}" is reserved — it's an official version.`;
135
+ case 'deleting a protected branch':
136
+ return `"${branch}" is an official version and can't be deleted.`;
137
+ case 'opening a PR from a protected branch':
138
+ return `You can't propose changes from "${branch}" — open the change request from a draft instead.`;
139
+ }
140
+ }
141
+
142
+ // Access-control rejections (the AccessDeniedError thrown by the backend
143
+ // when the caller lacks the `write` role on a touched path).
144
+ const accessMatch = raw.match(
145
+ /^You don't have permission to write to "([^"]+)"\. Eligible: (.+)\.?$/,
146
+ );
147
+ if (accessMatch) {
148
+ const [, path, eligibleRaw] = accessMatch;
149
+ // The greedy `(.+)` capture also eats the trailing `.` when the message
150
+ // ends with one, so `eligibleRaw === 'none.'` slips past a naive equality
151
+ // check. Strip whitespace + a single trailing period before comparing.
152
+ const eligible = eligibleRaw.trim().replace(/\.$/, '');
153
+ // The backend emits "Eligible: none" when both roles + users are empty at
154
+ // the resolved path. "Restricted to none. Ask one of them…" reads as
155
+ // nonsense, so route that case to a dedicated message that names the
156
+ // real recovery path (contact a repo admin to broaden access).
157
+ if (eligible === 'none') {
158
+ return `You don't have permission to edit "${path}". Nobody currently has edit permission for this file — contact a repo admin to grant access or broaden the rules for this folder.`;
159
+ }
160
+ return `You don't have permission to edit "${path}". Editing is restricted to ${eligible}. Ask one of them to make the change, or to broaden access for this folder.`;
161
+ }
162
+
163
+ // The legacy `DirtyWorkingTreeError` ("Uncommitted changes on X. Commit
164
+ // before switching.") translation lived here; both the error class and
165
+ // the source paths that emitted it (switchBranch, mergeFromOrigin) are
166
+ // gone under save=share + per-branch workspaces, so the regex would
167
+ // never match. Removed to keep the dispatch table honest.
168
+
169
+ const badName = raw.match(/^Invalid branch name "([^"]+)": (.+)$/);
170
+ if (badName) {
171
+ return `That name isn't allowed for a draft: ${badName[2]}.`;
172
+ }
173
+
174
+ // Branch-authorship rejection — the caller is neither the draft's author
175
+ // nor an admin (per `roles.yaml`). Backend `BranchAuthorshipError` keeps
176
+ // its engineering vocabulary (`Only the author of "<name>" can delete it.`);
177
+ // the frontend rewrites it into user-facing "draft author" + names the
178
+ // admin escape hatch so non-authors know there's another path.
179
+ const authorshipMatch = raw.match(/^Only the author of "([^"]+)" can delete it\.?$/);
180
+ if (authorshipMatch) {
181
+ return `Only the draft author or an admin can delete "${authorshipMatch[1]}". Ask them to discard it from their own picker.`;
182
+ }
183
+
184
+ if (raw === 'commit summary is required') return 'Please describe what you changed.';
185
+ if (raw === 'commit summary must be ≤ 200 characters') {
186
+ return 'Keep the description to 200 characters or less.';
187
+ }
188
+ if (raw === 'commit summary must be a single line') {
189
+ return 'Keep the description on a single line.';
190
+ }
191
+
192
+ if (raw === 'PR title is required') return 'Please give your change request a title.';
193
+ if (raw === 'PR title must be ≤ 256 characters') {
194
+ return 'Keep the change request title to 256 characters or less.';
195
+ }
196
+ if (raw === 'PR head and base must differ') {
197
+ return "Your draft and the version you're proposing into are the same — nothing to request.";
198
+ }
199
+ if (raw.startsWith('Could not resolve a base branch for')) {
200
+ return "Couldn't tell which official version this draft was started from. Share the draft first, then try again.";
201
+ }
202
+ if (/^PR not found$/i.test(raw)) {
203
+ return "That change request no longer exists.";
204
+ }
205
+
206
+ // Belt-and-suspenders fallback. The backend pre-flights this in `createPr`
207
+ // and throws a typed NoSharedHistoryError, so this regex only fires if the
208
+ // pre-flight is bypassed and the raw GraphQL error leaks through.
209
+ if (/has no history in common with/i.test(raw)) {
210
+ return "This draft doesn't share history with the version you're proposing into.";
211
+ }
212
+
213
+ // Cancel-change-request mappings. The backend throws CancelStateError /
214
+ // CancelAuthError with these literal messages; treat them as equality keys.
215
+ if (raw === 'This change request was already applied.') {
216
+ return "This change request was already applied — there's nothing to cancel.";
217
+ }
218
+ if (raw === 'This change request is already cancelled.') {
219
+ return "This change request was already cancelled.";
220
+ }
221
+ if (/^You can't cancel this change request/.test(raw)) {
222
+ // Already in user voice — pass through.
223
+ return raw;
224
+ }
225
+ if (/^Cancel failed: /.test(raw)) {
226
+ return "Couldn't cancel this change request right now. Try again in a moment.";
227
+ }
228
+
229
+ return raw;
230
+ }
231
+
232
+ function rawMessage(err: unknown): string {
233
+ if (err instanceof GitApiError) return err.message;
234
+ if (err instanceof Error) return err.message;
235
+ return 'Something went wrong.';
236
+ }
237
+
238
+ /**
239
+ * Strip URLs, tokens, credentials, and absolute paths from an error message
240
+ * before showing it to the user (and before logging it). Used by every auto-
241
+ * and manual-pull surface so a raw `git pull` error with embedded
242
+ * `https://ghp_…@host/path` or `/Users/alice/work/…` can't leak into the
243
+ * banner / chat composer / console.
244
+ *
245
+ * Lives here (next to `friendlyGitError`) so the two error-shaping helpers
246
+ * stay in one place — drift between them is the bug class this consolidation
247
+ * exists to prevent.
248
+ */
249
+ export function sanitizeErrorText(error: unknown): string {
250
+ const raw = error instanceof Error ? error.message : String(error ?? '');
251
+ return raw
252
+ .replace(/https?:\/\/\S+/gi, '[url]')
253
+ .replace(/\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|[A-Za-z0-9_-]{32,})\b/g, '[token]')
254
+ .replace(/\b(?:bearer|token|password|authorization)\s*[:=]\s*\S+/gi, '[token]')
255
+ .replace(/\b[A-Za-z]:\\[^\s]+/g, '[path]')
256
+ .replace(/\/(?:[^\s/]+\/)+[^\s/]*/g, '[path]');
257
+ }
@@ -0,0 +1,163 @@
1
+ import type {
2
+ BranchInfo,
3
+ CommitAttribution,
4
+ WorkingTreeStatus,
5
+ } from '@bevel-software/platform-shared';
6
+ import { authFetch } from '../../../lib/api';
7
+
8
+ /**
9
+ * Branch + change + working-tree API client. Talks exclusively to
10
+ * `/api/workspace/:id/workflow/*` — the legacy `/git/*` family was retired
11
+ * with the workflow-module migration (see `bevel-platform/PLAN.md`).
12
+ *
13
+ * Naming inside the frontend still uses git vocabulary (`fetchStatus`,
14
+ * `commit`, `push`) because the engineering glossary says internal symbols
15
+ * keep their precise terms; only rendered UI strings switch to "save",
16
+ * "share", etc. via `docs/glossary.md`.
17
+ */
18
+ export class GitApiError extends Error {
19
+ readonly status: number;
20
+ readonly body?: unknown;
21
+ constructor(status: number, message: string, body?: unknown) {
22
+ super(message);
23
+ this.name = 'GitApiError';
24
+ this.status = status;
25
+ this.body = body;
26
+ }
27
+ }
28
+
29
+ export async function handleApiResponse<T>(res: Response): Promise<T> {
30
+ if (res.ok) return (await res.json()) as T;
31
+ let body: unknown;
32
+ let message = `HTTP ${res.status}`;
33
+ try {
34
+ body = await res.json();
35
+ if (body && typeof body === 'object' && 'error' in body) {
36
+ message = String((body as { error: unknown }).error);
37
+ }
38
+ } catch {
39
+ // non-JSON body — keep default message
40
+ }
41
+ throw new GitApiError(res.status, message, body);
42
+ }
43
+
44
+ export async function fetchStatus(workspaceId: string): Promise<WorkingTreeStatus> {
45
+ return handleApiResponse(await authFetch(`/api/workspace/${workspaceId}/workflow/branch-status`));
46
+ }
47
+
48
+ export async function fetchBranches(
49
+ workspaceId: string,
50
+ opts: { fresh?: boolean } = {},
51
+ ): Promise<BranchInfo[]> {
52
+ // `fresh` forces a server-side `git fetch --prune` (bypassing the implicit
53
+ // TTL) so a user-initiated refresh reflects remote create/delete right away.
54
+ const qs = opts.fresh ? '?fresh=1' : '';
55
+ return handleApiResponse(await authFetch(`/api/workspace/${workspaceId}/workflow/branches${qs}`));
56
+ }
57
+
58
+ export async function createBranch(
59
+ workspaceId: string,
60
+ name: string,
61
+ fromBase?: string,
62
+ ): Promise<BranchInfo> {
63
+ return handleApiResponse(
64
+ await authFetch(`/api/workspace/${workspaceId}/workflow/branches`, {
65
+ method: 'POST',
66
+ headers: { 'Content-Type': 'application/json' },
67
+ body: JSON.stringify({ name, fromBase }),
68
+ }),
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Delete a local branch. With `onlyIfNoRemote: true` the backend refuses if
74
+ * `origin/<name>` still exists — use that variant when auto-pruning after a
75
+ * change request lands so you can't accidentally drop a branch still in use.
76
+ */
77
+ export async function deleteBranch(
78
+ workspaceId: string,
79
+ name: string,
80
+ opts: { onlyIfNoRemote?: boolean } = {},
81
+ ): Promise<void> {
82
+ const query = opts.onlyIfNoRemote ? '?onlyIfNoRemote=1' : '';
83
+ await handleApiResponse(
84
+ await authFetch(
85
+ `/api/workspace/${workspaceId}/workflow/branches/${encodeURIComponent(name)}${query}`,
86
+ { method: 'DELETE' },
87
+ ),
88
+ );
89
+ }
90
+
91
+ // `forkToDraft` removed: under save=share + per-branch workspaces, the
92
+ // dirty-edit carry-along escape hatch can't fire. `createBranch` + URL
93
+ // navigation to the new branch covers the "start a draft" intent.
94
+
95
+ export async function pull(workspaceId: string): Promise<void> {
96
+ await handleApiResponse(
97
+ await authFetch(`/api/workspace/${workspaceId}/workflow/update-from-remote`, { method: 'POST' }),
98
+ );
99
+ }
100
+
101
+ export async function fetchForkBase(
102
+ workspaceId: string,
103
+ branch: string,
104
+ ): Promise<string | null> {
105
+ const data = await handleApiResponse<{ base: string | null }>(
106
+ await authFetch(
107
+ `/api/workspace/${workspaceId}/workflow/fork-base?branch=${encodeURIComponent(branch)}`,
108
+ ),
109
+ );
110
+ return data.base;
111
+ }
112
+
113
+ export async function revert(
114
+ workspaceId: string,
115
+ sha: string,
116
+ ): Promise<CommitAttribution> {
117
+ return handleApiResponse(
118
+ await authFetch(`/api/workspace/${workspaceId}/workflow/changes/${encodeURIComponent(sha)}/revert`, {
119
+ method: 'POST',
120
+ }),
121
+ );
122
+ }
123
+
124
+ export async function fetchFileHistory(
125
+ workspaceId: string,
126
+ path: string,
127
+ limit = 20,
128
+ ): Promise<CommitAttribution[]> {
129
+ const q = new URLSearchParams({ path, limit: String(limit) });
130
+ const data = await handleApiResponse<{ changes: CommitAttribution[] }>(
131
+ await authFetch(`/api/workspace/${workspaceId}/workflow/changes?${q.toString()}`),
132
+ );
133
+ return data.changes;
134
+ }
135
+
136
+ export async function fetchFileDiff(
137
+ workspaceId: string,
138
+ path: string,
139
+ sha: string,
140
+ ): Promise<string> {
141
+ const q = new URLSearchParams({ path, sha });
142
+ const data = await handleApiResponse<{ diff: string }>(
143
+ await authFetch(`/api/workspace/${workspaceId}/workflow/show-file?${q.toString()}`),
144
+ );
145
+ return data.diff;
146
+ }
147
+
148
+ export async function fetchFileComparison(
149
+ workspaceId: string,
150
+ path: string,
151
+ fromBranch: string,
152
+ toBranch: string,
153
+ ): Promise<string> {
154
+ const q = new URLSearchParams({ path, from: fromBranch, to: toBranch });
155
+ const data = await handleApiResponse<{ diff: string }>(
156
+ await authFetch(`/api/workspace/${workspaceId}/workflow/compare-file?${q.toString()}`),
157
+ );
158
+ return data.diff;
159
+ }
160
+
161
+ // `fetchWorkingStatus` + `fetchWorkingDiff` removed: under save=share the
162
+ // working tree is never dirty, so both surfaces are always empty. Cross-
163
+ // branch comparison + commit history cover the meaningful diff cases.
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Builders for the chat prompts the UI dispatches when the user clicks an
3
+ * "open a change request" affordance. The agent picks these up and runs the
4
+ * cascade-impact + PR-creation workflow defined in `agent.instructions.ts` —
5
+ * which is why we want the agent in the loop instead of a direct
6
+ * `gh pr create` from the backend.
7
+ *
8
+ * Phrasing follows the user-facing glossary (draft, save, share, change
9
+ * request, apply) rather than git vocabulary, since these prompts appear in
10
+ * the chat as if the user typed them.
11
+ */
12
+
13
+ /**
14
+ * Sanitize a server-derived string before splicing it into an agent-facing
15
+ * prompt. The prompts are dispatched as if the user typed them, so anything
16
+ * that originated server-side (`recoveryDetail` from a workflow error,
17
+ * `conflictedPaths` from a 409 payload) is in principle untrusted with
18
+ * respect to the agent: a control character, a backtick that closes our
19
+ * code-fence, or a 50KB rebase stderr could skew the agent's reading of
20
+ * the request.
21
+ *
22
+ * Defensive transforms:
23
+ * - Drop ASCII control characters except `\n` and `\t`.
24
+ * - Replace backticks with their unicode lookalike so they can't break
25
+ * our code-fence delimiters in the seeded markdown.
26
+ * - Cap length at MAX so a verbose git stderr can't drown the
27
+ * surrounding instructions.
28
+ *
29
+ * Markdown links / asterisks aren't stripped — they may legitimately
30
+ * appear in error messages, and the agent reads markdown anyway.
31
+ */
32
+ const SANITIZE_MAX_CHARS = 600;
33
+
34
+ export function sanitizeForPrompt(input: string): string {
35
+ // Strip ASCII control chars (0x00-0x1F + 0x7F) except newline + tab.
36
+ const stripped = input.replace(/[\x00-\x08\x0B-\x1F\x7F]/g, '');
37
+ // Backtick → "modifier letter grave accent" (U+02CB) — visually similar,
38
+ // doesn't terminate fenced or inline code in our markdown.
39
+ const detoxed = stripped.replace(/`/g, 'ˋ');
40
+ if (detoxed.length <= SANITIZE_MAX_CHARS) return detoxed;
41
+ return `${detoxed.slice(0, SANITIZE_MAX_CHARS)}… [truncated, ${detoxed.length - SANITIZE_MAX_CHARS} chars cut]`;
42
+ }
43
+
44
+ /**
45
+ * Array variant: filters non-strings (defensive against malformed
46
+ * payloads) and sanitizes each element through `sanitizeForPrompt`.
47
+ */
48
+ function sanitizePathArrayForPrompt(input: readonly unknown[]): string[] {
49
+ return input
50
+ .filter((item): item is string => typeof item === 'string')
51
+ .map((item) => sanitizeForPrompt(item));
52
+ }
53
+
54
+ export interface ProposeDraftPromptInput {
55
+ /** The draft branch the change request should be opened from. */
56
+ branch: string;
57
+ /** The base (usually the protected version) the draft should land on. */
58
+ base: string;
59
+ /** Free-text summary of what changed (used as the PR title hint). */
60
+ summary?: string;
61
+ /** Optional longer description (becomes the PR body intro). */
62
+ description?: string;
63
+ /** Workspace-relative paths the user touched in this draft. */
64
+ touched?: string[];
65
+ /**
66
+ * When true, indicates the user has already saved + shared (commit + push).
67
+ * When false, the agent must push the draft itself before opening the PR.
68
+ */
69
+ alreadyShared: boolean;
70
+ }
71
+
72
+ /**
73
+ * Seed text the chat composer receives when applying a change request hits
74
+ * conflicts. The agent reads it as a user request to resolve the
75
+ * disagreement and re-apply — keeping the user out of the loop. Phrased in
76
+ * the workspace's plain-language vocabulary; the agent's system prompt
77
+ * already knows the underlying git mechanics (which branches, which paths,
78
+ * `commit_change` + `merge_change_request`).
79
+ */
80
+ export function buildResolveApplyConflictsPrompt(input: {
81
+ /** The change request number being applied. */
82
+ changeRequestNumber: number;
83
+ /** The base branch the CR is targeting (usually a protected branch). */
84
+ base: string;
85
+ /** Paths the conflict touched, if the server returned them. */
86
+ conflictedPaths?: string[];
87
+ }): string {
88
+ const { changeRequestNumber } = input;
89
+ const base = sanitizeForPrompt(input.base);
90
+ const conflictedPaths = input.conflictedPaths
91
+ ? sanitizePathArrayForPrompt(input.conflictedPaths)
92
+ : [];
93
+ const pathBlurb =
94
+ conflictedPaths.length > 0
95
+ ? ` The files that disagree are:\n${conflictedPaths.map((p) => `- \`${p}\``).join('\n')}\n`
96
+ : '';
97
+ return [
98
+ `I tried to apply change request #${changeRequestNumber} into \`${base}\` and the two sides have differences that couldn't be reconciled automatically.${pathBlurb}`,
99
+ '',
100
+ "Please look at each affected file, decide what the merged version should look like for the process to remain consistent, and apply your resolution to the change request's source branch. Then retry applying the change request. If you genuinely can't tell which version should win on a particular file, ask me about that specific case in plain language — but resolve everything you can on your own first.",
101
+ ].join('\n');
102
+ }
103
+
104
+ /**
105
+ * Seed text the chat composer receives when refreshing a change request
106
+ * from its target (re-running the auto-merge after the target moved) hits
107
+ * conflicts. Same shape as `buildResolveApplyConflictsPrompt` but framed
108
+ * around "bring the latest target in" rather than "apply this draft out".
109
+ */
110
+ export function buildResolveRefreshConflictsPrompt(input: {
111
+ /** The change request number being refreshed. */
112
+ changeRequestNumber: number;
113
+ /** The base branch the CR is targeting. */
114
+ base: string;
115
+ /** Paths the refresh-merge conflict touched, if the server returned them. */
116
+ conflictedPaths?: string[];
117
+ }): string {
118
+ const { changeRequestNumber } = input;
119
+ const base = sanitizeForPrompt(input.base);
120
+ const conflictedPaths = input.conflictedPaths
121
+ ? sanitizePathArrayForPrompt(input.conflictedPaths)
122
+ : [];
123
+ const pathBlurb =
124
+ conflictedPaths.length > 0
125
+ ? ` The files that disagree are:\n${conflictedPaths.map((p) => `- \`${p}\``).join('\n')}\n`
126
+ : '';
127
+ return [
128
+ `I tried to bring the latest \`${base}\` into change request #${changeRequestNumber} (so the diff reflects what would actually apply now) and the two sides have differences that couldn't be reconciled automatically.${pathBlurb}`,
129
+ '',
130
+ "Please decide the merged version for each affected file so the change request stays coherent with the latest target, apply your resolution to the change request's source branch, then refresh again. If you can't tell which version should win on a particular file, ask me about that one case in plain language — but resolve everything you can on your own first.",
131
+ ].join('\n');
132
+ }
133
+
134
+ export function buildProposeDraftPrompt(input: ProposeDraftPromptInput): string {
135
+ const { branch, base, summary, description, touched, alreadyShared } = input;
136
+
137
+ const opener = alreadyShared
138
+ ? `I just saved and shared my draft \`${branch}\`. Please propose it as a change request that applies to \`${base}\`.`
139
+ : `Please propose my current draft \`${branch}\` as a change request that applies to \`${base}\`. Share the draft (push) if it isn't already.`;
140
+
141
+ const lines: string[] = [opener];
142
+
143
+ if (summary?.trim()) {
144
+ lines.push('', `**What I changed:** ${summary.trim()}`);
145
+ }
146
+ if (description?.trim()) {
147
+ lines.push('', description.trim());
148
+ }
149
+ if (touched && touched.length > 0) {
150
+ lines.push('', '**Files in this draft:**', ...touched.map((p) => `- ${p}`));
151
+ }
152
+
153
+ lines.push(
154
+ '',
155
+ 'Before opening the change request, run a cascade impact analysis on the changes in this draft (per your instructions): walk the graph for any related processes, value slices, or other nodes that should also change to stay consistent, update them on this same draft, validate, and include those updates in the same change request. List the cascade in the change-request body so the reviewer can audit the ripple.',
156
+ );
157
+
158
+ return lines.join('\n');
159
+ }
@@ -0,0 +1,39 @@
1
+ import type { PullRequestSummary } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { GitApiError } from './git.api';
4
+
5
+ async function handle<T>(res: Response): Promise<T> {
6
+ if (res.ok) return (await res.json()) as T;
7
+ let body: unknown;
8
+ let message = `HTTP ${res.status}`;
9
+ try {
10
+ body = await res.json();
11
+ if (body && typeof body === 'object' && 'error' in body) {
12
+ message = String((body as { error: unknown }).error);
13
+ }
14
+ } catch {
15
+ // non-JSON body
16
+ }
17
+ throw new GitApiError(res.status, message, body);
18
+ }
19
+
20
+ /**
21
+ * `opts.fresh` bypasses the backend's 30s list cache. Use it from event-driven
22
+ * refreshes (agent turn end) where we specifically believe the underlying list
23
+ * just changed; leave it off for the background poll so we don't hammer `gh`
24
+ * every minute.
25
+ */
26
+ export async function listPullRequestsForMe(
27
+ opts: { fresh?: boolean } = {},
28
+ ): Promise<PullRequestSummary[]> {
29
+ const query = opts.fresh ? '?fresh=1' : '';
30
+ return handle(await authFetch(`/api/workflow/change-requests/for-me${query}`));
31
+ }
32
+
33
+ export async function listMyPullRequests(): Promise<PullRequestSummary[]> {
34
+ return handle(await authFetch('/api/workflow/change-requests/mine'));
35
+ }
36
+
37
+ export async function getPullRequest(num: number): Promise<PullRequestSummary> {
38
+ return handle(await authFetch(`/api/workflow/change-requests/${num}`));
39
+ }
@@ -0,0 +1,21 @@
1
+ import { createContext, useContext } from 'react';
2
+
3
+ export type AutoUpdateStatus = 'idle' | 'updating' | 'failed';
4
+
5
+ export interface AutoUpdateState {
6
+ status: AutoUpdateStatus;
7
+ branch: string | null;
8
+ reason: string | null;
9
+ }
10
+
11
+ export const IDLE_AUTO_UPDATE: AutoUpdateState = {
12
+ status: 'idle',
13
+ branch: null,
14
+ reason: null,
15
+ };
16
+
17
+ export const AutoUpdateContext = createContext<AutoUpdateState>(IDLE_AUTO_UPDATE);
18
+
19
+ export function useAutoUpdate(): AutoUpdateState {
20
+ return useContext(AutoUpdateContext);
21
+ }