@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,430 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import type { Change, FileLock } from '@bevel-software/platform-shared';
3
+ import {
4
+ acquireLock as acquireLockApi,
5
+ checkpointLockedFile,
6
+ getLock as getLockApi,
7
+ heartbeatLock,
8
+ LockApiError,
9
+ releaseLock as releaseLockApi,
10
+ } from '../services/lock.api';
11
+ import { useEventBus, canonicalizeWorkspaceId } from '../state/event-bus.context';
12
+
13
+ const HEARTBEAT_INTERVAL_MS = 30_000;
14
+ const AUTOSAVE_INTERVAL_MS = 60_000;
15
+ /**
16
+ * Idle threshold (no typing, no scrolling) after which the held lock is
17
+ * auto-released. Other users can then enter Edit mode on the file without
18
+ * waiting for the current editor to explicitly leave. The heartbeat keeps
19
+ * the backend TTL refreshed for as long as we hold the lock, so this can
20
+ * exceed the server-side TTL; it is the *frontend's* policy for "user
21
+ * wandered off, give the file back to the team". Long enough that pausing
22
+ * to think doesn't kick the user out of Edit mode mid-work.
23
+ */
24
+ const IDLE_RELEASE_MS = 120_000;
25
+
26
+ interface UseFileLockArgs {
27
+ /** The workspace id of the branch we're editing on. Null disables the hook. */
28
+ workspaceId: string | null;
29
+ /** The branch name. Null disables the hook. */
30
+ branch: string | null;
31
+ /** Workspace-relative path of the file under edit. Null disables the hook. */
32
+ path: string | null;
33
+ /**
34
+ * Current authenticated user's id. Used to recognise "this lock is held
35
+ * by me" responses from the server during the brief window between a
36
+ * tab-switch cleanup releasing the lock and the backend actually
37
+ * committing the release — without this, switching away and back to a
38
+ * file you were just editing would flicker an amber "Locked by [your
39
+ * own name]" banner. Optional so test harnesses without auth context
40
+ * still work; in that case nothing is filtered.
41
+ */
42
+ currentUserId?: string | null;
43
+ /**
44
+ * `() => string | null` — pulls the latest in-memory file contents so the
45
+ * autosave checkpoint can persist them to disk before committing. Returning
46
+ * null skips the disk write. Implemented as a getter so the hook reads the
47
+ * current tab buffer without re-subscribing on every keystroke.
48
+ */
49
+ readPendingContent: () => string | null;
50
+ /**
51
+ * Persist `content` to disk via the existing workspace file-write API.
52
+ * Separated from the hook so the hook stays unaware of HTTP routing /
53
+ * tab bookkeeping; the FileViewer wires this to its `saveFile` helper.
54
+ */
55
+ persistToDisk: (content: string) => Promise<void>;
56
+ }
57
+
58
+ /**
59
+ * Result of an `acquire()` attempt. `acquired` is the success flag;
60
+ * `contended` is true only when the failure is another user's lock (the
61
+ * externalLock banner covers that case); `error` carries the message for
62
+ * every non-contention failure (access-denied 403, network, etc.).
63
+ */
64
+ export interface AcquireOutcome {
65
+ acquired: boolean;
66
+ contended: boolean;
67
+ error: string | null;
68
+ }
69
+
70
+ interface UseFileLockReturn {
71
+ /** True iff this client currently holds the lock. */
72
+ holdingLock: boolean;
73
+ /** Lock currently held by someone else (or null if we hold it / nobody does). */
74
+ externalLock: FileLock | null;
75
+ /** Latest acquire / heartbeat error, surfaced in the UI as a banner. */
76
+ lockError: string | null;
77
+ /**
78
+ * Acquire the lock. Idempotent — re-acquiring a lock you already hold
79
+ * refreshes the TTL. Resolves to an outcome the caller can act on
80
+ * WITHOUT reading `lockError`/`externalLock` off the hook return —
81
+ * those are React state and are stale in the caller's closure right
82
+ * after the `await`. `contended` distinguishes "held by someone else"
83
+ * (surfaced by the externalLock banner) from an access-denied / network
84
+ * failure (`error` set, `contended` false) that the caller must surface
85
+ * itself.
86
+ */
87
+ acquire: () => Promise<AcquireOutcome>;
88
+ /**
89
+ * Persist + checkpoint: write the current buffer to disk and commit it
90
+ * as a change without releasing the lock. Used by both the autosave
91
+ * timer and the explicit Save button.
92
+ */
93
+ saveCheckpoint: (summary?: string) => Promise<Change | null>;
94
+ /**
95
+ * Final save: write the current buffer to disk, commit it, and release
96
+ * the lock. Used on file-close / navigate-away / explicit "done editing".
97
+ */
98
+ saveAndRelease: (summary?: string) => Promise<Change | null>;
99
+ /**
100
+ * Reset the idle-release timer. Callers (the editor) wire this to every
101
+ * interaction with the file — keystrokes, scroll events. After
102
+ * `IDLE_RELEASE_MS` without a call, the held lock auto-releases and
103
+ * the editor flips to read-only.
104
+ */
105
+ recordActivity: () => void;
106
+ }
107
+
108
+ /**
109
+ * Per-file lock lifecycle (PLAN §2). One instance per (branch, file) the
110
+ * editor has open. Concerns:
111
+ *
112
+ * - Acquisition on demand. Lock is acquired on the caller's terms
113
+ * (`acquire()`) — typically on first dirty edit. We don't auto-acquire
114
+ * on mount because read-only views shouldn't claim the lock.
115
+ * - Heartbeat while held. A `setInterval` extends the TTL every 30s; if
116
+ * a heartbeat fails (lock expired, stolen, branch deleted) we drop
117
+ * `holdingLock` so the UI can re-arm.
118
+ * - External holder polling when we don't hold the lock. The editor
119
+ * surface shows "Locked by X" via `externalLock`.
120
+ * - Autosave checkpoints. Every minute while holding the lock, persist
121
+ * the latest buffer + commit. The lock stays held — releasing here
122
+ * would race against the next keystroke.
123
+ * - Release on unmount / branch-or-path change. The cleanup callback
124
+ * commits the final pending content and drops the lock so the next
125
+ * editor can take over.
126
+ */
127
+ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
128
+ const { workspaceId, branch, path, currentUserId } = args;
129
+ const [holdingLock, setHoldingLock] = useState(false);
130
+ const [externalLock, setExternalLock] = useState<FileLock | null>(null);
131
+ const [lockError, setLockError] = useState<string | null>(null);
132
+
133
+ // Refs so the long-lived intervals (heartbeat, autosave) see the latest
134
+ // getters without re-subscribing on every prop change.
135
+ const readPendingContentRef = useRef(args.readPendingContent);
136
+ const persistToDiskRef = useRef(args.persistToDisk);
137
+ const holdingLockRef = useRef(false);
138
+ useEffect(() => { readPendingContentRef.current = args.readPendingContent; }, [args.readPendingContent]);
139
+ useEffect(() => { persistToDiskRef.current = args.persistToDisk; }, [args.persistToDisk]);
140
+ useEffect(() => { holdingLockRef.current = holdingLock; }, [holdingLock]);
141
+
142
+ // Reset state when the (workspace, branch, path) tuple changes — opening
143
+ // a different file is a fresh lock context, not a continuation.
144
+ useEffect(() => {
145
+ setHoldingLock(false);
146
+ setExternalLock(null);
147
+ setLockError(null);
148
+ }, [workspaceId, branch, path]);
149
+
150
+ const acquire = useCallback(async (): Promise<AcquireOutcome> => {
151
+ if (!workspaceId || !branch || !path) return { acquired: false, contended: false, error: null };
152
+ console.debug('[useFileLock] acquire start', { workspaceId, branch, path });
153
+ try {
154
+ const result = await acquireLockApi(workspaceId, branch, path);
155
+ if (result.acquired) {
156
+ console.debug('[useFileLock] acquire ok', { workspaceId, branch, path });
157
+ setHoldingLock(true);
158
+ setExternalLock(null);
159
+ setLockError(null);
160
+ return { acquired: true, contended: false, error: null };
161
+ }
162
+ console.debug('[useFileLock] acquire contended', {
163
+ workspaceId, branch, path,
164
+ holder: result.lock.holderName,
165
+ holderUserId: result.lock.holderUserId,
166
+ });
167
+ const msg = `Locked by ${result.lock.holderName}`;
168
+ setHoldingLock(false);
169
+ setExternalLock(result.lock);
170
+ setLockError(msg);
171
+ return { acquired: false, contended: true, error: msg };
172
+ } catch (err) {
173
+ const msg = err instanceof Error ? err.message : String(err);
174
+ console.warn('[useFileLock] acquire failed', { workspaceId, branch, path, error: msg });
175
+ setLockError(msg);
176
+ setHoldingLock(false);
177
+ return { acquired: false, contended: false, error: msg };
178
+ }
179
+ }, [workspaceId, branch, path]);
180
+
181
+ const persistAndCommit = useCallback(
182
+ async (mode: 'checkpoint' | 'release', summary?: string): Promise<Change | null> => {
183
+ if (!workspaceId || !branch || !path) return null;
184
+ console.debug(`[useFileLock] ${mode} start`, { workspaceId, branch, path });
185
+ const pending = readPendingContentRef.current();
186
+ if (pending !== null) {
187
+ try {
188
+ await persistToDiskRef.current(pending);
189
+ } catch (err) {
190
+ const msg = err instanceof Error ? err.message : String(err);
191
+ console.warn(`[useFileLock] ${mode} persist failed`, { workspaceId, branch, path, error: msg });
192
+ setLockError(`Save failed: ${msg}`);
193
+ throw err;
194
+ }
195
+ }
196
+ try {
197
+ if (mode === 'checkpoint') {
198
+ const change = await checkpointLockedFile(workspaceId, branch, path, summary);
199
+ console.debug('[useFileLock] checkpoint ok', { workspaceId, branch, path, sha: change?.sha ?? null });
200
+ return change;
201
+ }
202
+ const change = await releaseLockApi(workspaceId, branch, path, summary);
203
+ console.debug('[useFileLock] release ok', { workspaceId, branch, path, sha: change?.sha ?? null });
204
+ setHoldingLock(false);
205
+ return change;
206
+ } catch (err) {
207
+ const msg = err instanceof Error ? err.message : String(err);
208
+ console.warn(`[useFileLock] ${mode} failed`, {
209
+ workspaceId, branch, path,
210
+ status: err instanceof LockApiError ? err.status : undefined,
211
+ error: msg,
212
+ });
213
+ // 409 from the backend means the lock was stolen / expired —
214
+ // surface the state so the editor can re-arm.
215
+ if (err instanceof LockApiError && err.status === 409) {
216
+ setHoldingLock(false);
217
+ }
218
+ setLockError(`Save failed: ${msg}`);
219
+ throw err;
220
+ }
221
+ },
222
+ [workspaceId, branch, path],
223
+ );
224
+
225
+ const saveCheckpoint = useCallback(
226
+ (summary?: string) => persistAndCommit('checkpoint', summary),
227
+ [persistAndCommit],
228
+ );
229
+
230
+ const saveAndRelease = useCallback(
231
+ (summary?: string) => persistAndCommit('release', summary),
232
+ [persistAndCommit],
233
+ );
234
+
235
+ // Heartbeat while we hold the lock. Refreshes the TTL so a long edit
236
+ // session doesn't lose the lock to a brief network blip.
237
+ useEffect(() => {
238
+ if (!holdingLock || !workspaceId || !branch || !path) return;
239
+ const id = window.setInterval(async () => {
240
+ try {
241
+ await heartbeatLock(workspaceId, branch, path);
242
+ console.debug('[useFileLock] heartbeat ok', { workspaceId, branch, path });
243
+ } catch (err) {
244
+ // Lost the lock — back off the holding state so the UI re-acquires
245
+ // on the next dirty edit.
246
+ const msg = err instanceof Error ? err.message : String(err);
247
+ console.warn('[useFileLock] heartbeat lost', { workspaceId, branch, path, error: msg });
248
+ setLockError(`Lost lock: ${msg}`);
249
+ setHoldingLock(false);
250
+ }
251
+ }, HEARTBEAT_INTERVAL_MS);
252
+ return () => window.clearInterval(id);
253
+ }, [holdingLock, workspaceId, branch, path]);
254
+
255
+ // Live lock state when we don't hold it. Two paths feed `externalLock`:
256
+ //
257
+ // 1. **Initial fetch on (workspace, branch, path) change** — we need
258
+ // to know who currently holds the lock (if anyone) at the moment
259
+ // the editor opens this file. The SSE stream only delivers events
260
+ // that fire AFTER subscribe, so without this query a tab opened on
261
+ // an already-locked file would render "free" until the next
262
+ // release.
263
+ //
264
+ // 2. **`lock-acquired` / `lock-released` events** from the workflow
265
+ // event bus — replace the 15s poll the hook used to do. The bus
266
+ // fans these out within milliseconds of the acquire/release on
267
+ // the backend, so the banner appears / disappears in near real
268
+ // time without per-tab polling traffic.
269
+ //
270
+ // We bail on the subscription path when the bus isn't mounted (tests),
271
+ // and the initial fetch is enough to render a static "Locked by X" if
272
+ // anyone holds it at mount time.
273
+ const bus = useEventBus();
274
+ useEffect(() => {
275
+ if (holdingLock || !workspaceId || !branch || !path) return;
276
+ let cancelled = false;
277
+ // "Lock held by me" means the previous tab's cleanup hasn't finished
278
+ // committing the release on the backend yet — we just switched away
279
+ // and back fast enough that the persist+release is still in flight.
280
+ // We don't want to render an amber "Locked by [yourself]" banner
281
+ // for that fraction of a second; the SSE `lock-released` event
282
+ // will arrive shortly and we'll be back to a clean state.
283
+ const isSelfLock = (lock: FileLock | null): boolean =>
284
+ !!lock && !!currentUserId && lock.holderUserId === currentUserId;
285
+ getLockApi(workspaceId, branch, path)
286
+ .then((lock) => {
287
+ if (cancelled) return;
288
+ setExternalLock(isSelfLock(lock) ? null : lock);
289
+ })
290
+ .catch(() => { /* network blip — events will catch us up */ });
291
+ if (!bus) return () => { cancelled = true; };
292
+ // Canonicalise once; event.workspaceId from the backend is decoded
293
+ // (`razvan-radulescu/sc`) while the `workspaceId` prop is encoded
294
+ // (`razvan-radulescu%2Fsc`). See `canonicalizeWorkspaceId` doc.
295
+ const workspaceCanon = canonicalizeWorkspaceId(workspaceId);
296
+ const offAcquired = bus.subscribe('lock-acquired', (e) => {
297
+ if (e.branch !== branch || e.path !== path || canonicalizeWorkspaceId(e.workspaceId) !== workspaceCanon) return;
298
+ // SSE echoes our own acquire too. If the event is about a lock
299
+ // we just took on this client (rare — we'd already be in the
300
+ // `holdingLock=true` branch and not subscribed — but cover it
301
+ // for safety against state races), ignore it.
302
+ if (currentUserId && e.holderUserId === currentUserId) return;
303
+ setExternalLock({
304
+ branch: e.branch,
305
+ path: e.path,
306
+ holderUserId: e.holderUserId,
307
+ holderName: e.holderName,
308
+ // SSE doesn't carry the lock TTL fields; the banner only renders
309
+ // holder name, so leaving them blank is harmless. A subsequent
310
+ // get-lock fetch on file open would refresh them if needed.
311
+ acquiredAt: '',
312
+ lastHeartbeatAt: '',
313
+ expiresAt: '',
314
+ });
315
+ });
316
+ const offReleased = bus.subscribe('lock-released', (e) => {
317
+ if (e.branch !== branch || e.path !== path || canonicalizeWorkspaceId(e.workspaceId) !== workspaceCanon) return;
318
+ setExternalLock(null);
319
+ });
320
+ return () => {
321
+ cancelled = true;
322
+ offAcquired();
323
+ offReleased();
324
+ };
325
+ }, [holdingLock, workspaceId, branch, path, bus, currentUserId]);
326
+
327
+ // Autosave checkpoint timer. Runs every minute while holding the lock
328
+ // *and* the buffer is non-null. The lock stays held across checkpoints
329
+ // — release happens explicitly on save+close.
330
+ useEffect(() => {
331
+ if (!holdingLock || !workspaceId || !branch || !path) return;
332
+ const id = window.setInterval(() => {
333
+ if (!holdingLockRef.current) return;
334
+ const pending = readPendingContentRef.current();
335
+ if (pending === null) return;
336
+ saveCheckpoint().catch((err) => {
337
+ // saveCheckpoint already wrote `lockError`; the periodic retry
338
+ // will resync on the next interval.
339
+ console.warn('[useFileLock] autosave checkpoint failed:', err);
340
+ });
341
+ }, AUTOSAVE_INTERVAL_MS);
342
+ return () => window.clearInterval(id);
343
+ }, [holdingLock, workspaceId, branch, path, saveCheckpoint]);
344
+
345
+ // Idle-release timer. While we hold the lock, the editor wires its
346
+ // keystroke + scroll handlers into `recordActivity()` below; each call
347
+ // resets the timer. If the timer fires (no activity for
348
+ // IDLE_RELEASE_MS) we save and release — the user has stepped away,
349
+ // and the file should be available to others without anyone having to
350
+ // explicitly hand it back.
351
+ //
352
+ // We store the timeout id in a ref so `recordActivity` can clear and
353
+ // restart it cheaply without re-running this effect.
354
+ const idleTimerRef = useRef<number | null>(null);
355
+ const clearIdleTimer = useCallback(() => {
356
+ if (idleTimerRef.current !== null) {
357
+ window.clearTimeout(idleTimerRef.current);
358
+ idleTimerRef.current = null;
359
+ }
360
+ }, []);
361
+ const startIdleTimer = useCallback(() => {
362
+ clearIdleTimer();
363
+ if (!holdingLockRef.current) return;
364
+ idleTimerRef.current = window.setTimeout(() => {
365
+ idleTimerRef.current = null;
366
+ if (!holdingLockRef.current) return;
367
+ // saveAndRelease writes the current buffer (if any), commits, and
368
+ // releases the lock. On success the `holdingLock` state flips to
369
+ // false; the editor's `readOnly` check reacts on the next render.
370
+ // On failure we leave the timer cleared — the user's next
371
+ // activity will start a fresh one. Errors are logged here because
372
+ // the hook user has already moved on by definition (they were
373
+ // idle).
374
+ saveAndRelease().catch((err) => {
375
+ console.warn('[useFileLock] idle release failed:', err);
376
+ });
377
+ }, IDLE_RELEASE_MS);
378
+ }, [clearIdleTimer, saveAndRelease]);
379
+
380
+ // Wire the timer to the holding-lock lifecycle: arm when we acquire,
381
+ // tear down when we no longer hold it (manual release, lost lock,
382
+ // file switch).
383
+ useEffect(() => {
384
+ if (!holdingLock) {
385
+ clearIdleTimer();
386
+ return;
387
+ }
388
+ startIdleTimer();
389
+ return clearIdleTimer;
390
+ }, [holdingLock, startIdleTimer, clearIdleTimer]);
391
+
392
+ const recordActivity = useCallback(() => {
393
+ // No-op when we don't hold the lock — there's no timer to reset.
394
+ // (The editor still fires activity events from any rendered file,
395
+ // including those we're viewing read-only; we just ignore them.)
396
+ if (!holdingLockRef.current) return;
397
+ startIdleTimer();
398
+ }, [startIdleTimer]);
399
+
400
+ // Release the lock when the editor unmounts or switches files. Best-
401
+ // effort — a failure here is logged but doesn't surface to the user,
402
+ // they've already moved on. Before releasing, persist the latest
403
+ // in-memory buffer to disk so the final keystrokes don't get
404
+ // discarded — without this, closing a tab mid-edit would commit
405
+ // whatever was last saved to disk and lose the unsaved tail (the
406
+ // backend's `commitFile` reads the on-disk state, not our buffer).
407
+ useEffect(() => {
408
+ return () => {
409
+ if (!holdingLockRef.current || !workspaceId || !branch || !path) return;
410
+ const pending = readPendingContentRef.current();
411
+ const release = () =>
412
+ releaseLockApi(workspaceId, branch, path).catch((err) => {
413
+ console.warn('[useFileLock] release on unmount failed:', err);
414
+ });
415
+ if (pending !== null) {
416
+ persistToDiskRef.current(pending).then(release, (err) => {
417
+ console.warn('[useFileLock] persist on unmount failed:', err);
418
+ // Release anyway so the lock doesn't get stuck; whatever was
419
+ // last successfully written to disk will be what the release-
420
+ // time commit captures.
421
+ void release();
422
+ });
423
+ } else {
424
+ void release();
425
+ }
426
+ };
427
+ }, [workspaceId, branch, path]);
428
+
429
+ return { holdingLock, externalLock, lockError, acquire, saveCheckpoint, saveAndRelease, recordActivity };
430
+ }
@@ -0,0 +1,139 @@
1
+ import type {
2
+ AcquireLockResult,
3
+ Change,
4
+ FileLock,
5
+ } from '@bevel-software/platform-shared';
6
+ import { authFetch } from '../../../lib/api';
7
+
8
+ /**
9
+ * Client for `/workspace/:id/workflow/locks/*` — the file-lock primitives
10
+ * the editor uses to coordinate concurrent edits across users on the same
11
+ * branch's shared workspace (PLAN §2). All four backend endpoints map 1:1.
12
+ *
13
+ * On non-2xx responses these functions throw a `LockApiError` carrying the
14
+ * HTTP status + parsed payload so the editor can distinguish "someone else
15
+ * holds the lock" (`acquired: false` in the body) from "lock expired"
16
+ * (409 from heartbeat) from real infra failures.
17
+ */
18
+ export class LockApiError extends Error {
19
+ readonly status: number;
20
+ readonly body?: unknown;
21
+ constructor(status: number, message: string, body?: unknown) {
22
+ super(message);
23
+ this.name = 'LockApiError';
24
+ this.status = status;
25
+ this.body = body;
26
+ }
27
+ }
28
+
29
+ async function unwrap<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 — fall through with default message
40
+ }
41
+ throw new LockApiError(res.status, message, body);
42
+ }
43
+
44
+ /**
45
+ * Try to acquire the lock for `(branch, path)`. Resolves with the
46
+ * `AcquireLockResult` payload — `acquired: true` when the caller now
47
+ * holds the lock, `acquired: false` when someone else does (the
48
+ * holder's lock state is included so the UI can render "Locked by X"
49
+ * without a follow-up call).
50
+ */
51
+ export async function acquireLock(
52
+ workspaceId: string,
53
+ branch: string,
54
+ path: string,
55
+ ): Promise<AcquireLockResult> {
56
+ return unwrap(
57
+ await authFetch(`/api/workspace/${workspaceId}/workflow/locks`, {
58
+ method: 'POST',
59
+ headers: { 'Content-Type': 'application/json' },
60
+ body: JSON.stringify({ branch, path }),
61
+ }),
62
+ );
63
+ }
64
+
65
+ /** Extend the lock's TTL. Throws if the caller no longer holds the lock. */
66
+ export async function heartbeatLock(
67
+ workspaceId: string,
68
+ branch: string,
69
+ path: string,
70
+ ): Promise<FileLock> {
71
+ return unwrap(
72
+ await authFetch(`/api/workspace/${workspaceId}/workflow/locks/heartbeat`, {
73
+ method: 'POST',
74
+ headers: { 'Content-Type': 'application/json' },
75
+ body: JSON.stringify({ branch, path }),
76
+ }),
77
+ );
78
+ }
79
+
80
+ /**
81
+ * Autosave checkpoint — commits the file's accumulated edits without
82
+ * releasing the lock. Returns the new change or null when the file
83
+ * had no pending edits. The frontend's editor calls this on its
84
+ * periodic save tick so the lock stays held across many interim
85
+ * commits.
86
+ */
87
+ export async function checkpointLockedFile(
88
+ workspaceId: string,
89
+ branch: string,
90
+ path: string,
91
+ summary?: string,
92
+ ): Promise<Change | null> {
93
+ const { change } = await unwrap<{ change: Change | null }>(
94
+ await authFetch(`/api/workspace/${workspaceId}/workflow/locks/checkpoint`, {
95
+ method: 'POST',
96
+ headers: { 'Content-Type': 'application/json' },
97
+ body: JSON.stringify({ branch, path, summary }),
98
+ }),
99
+ );
100
+ return change;
101
+ }
102
+
103
+ /**
104
+ * Release the lock AND commit any pending edits as a final change.
105
+ * Returns `null` when the file had no pending edits (idempotent on a
106
+ * clean release).
107
+ */
108
+ export async function releaseLock(
109
+ workspaceId: string,
110
+ branch: string,
111
+ path: string,
112
+ summary?: string,
113
+ ): Promise<Change | null> {
114
+ const { change } = await unwrap<{ change: Change | null }>(
115
+ await authFetch(`/api/workspace/${workspaceId}/workflow/locks`, {
116
+ method: 'DELETE',
117
+ headers: { 'Content-Type': 'application/json' },
118
+ body: JSON.stringify({ branch, path, summary }),
119
+ }),
120
+ );
121
+ return change;
122
+ }
123
+
124
+ /**
125
+ * Read the current lock holder for `(branch, path)`. Returns null when
126
+ * nobody holds it. The editor polls this when it doesn't hold the lock
127
+ * to detect when another user starts / stops editing.
128
+ */
129
+ export async function getLock(
130
+ workspaceId: string,
131
+ branch: string,
132
+ path: string,
133
+ ): Promise<FileLock | null> {
134
+ const qs = new URLSearchParams({ branch, path }).toString();
135
+ const { lock } = await unwrap<{ lock: FileLock | null }>(
136
+ await authFetch(`/api/workspace/${workspaceId}/workflow/locks?${qs}`),
137
+ );
138
+ return lock;
139
+ }
@@ -0,0 +1,25 @@
1
+ import { useEffect } from 'react';
2
+ import { useWorkspace } from '../../workspace/state/workspace.context';
3
+ import { useEventBus } from './event-bus.context';
4
+
5
+ /**
6
+ * Bridges the WorkspaceContext's active `workspaceId` to the EventBus's
7
+ * server-side focus filter. Whenever the user switches branch (a pure URL
8
+ * navigation under the per-branch workspace model), the workspace bootstrap
9
+ * updates `workspaceId` and this component POSTs the new id to the events
10
+ * route so the SSE stream starts delivering broadcast events for the new
11
+ * branch's workspace.
12
+ *
13
+ * Renders nothing — it's a pure side-effect bridge. Lives between the
14
+ * EventBus and Workspace providers so it has access to both contexts.
15
+ */
16
+ export function EventBusFocusBinder() {
17
+ const workspace = useWorkspace();
18
+ const bus = useEventBus();
19
+ const workspaceId = workspace?.workspaceId ?? null;
20
+ useEffect(() => {
21
+ if (!bus) return;
22
+ bus.setFocus(workspaceId);
23
+ }, [bus, workspaceId]);
24
+ return null;
25
+ }