@bevel-software/platform-core-frontend 0.28.0 → 0.29.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 (59) hide show
  1. package/package.json +11 -4
  2. package/src/core/CoreAppShell.tsx +29 -11
  3. package/src/core/__tests__/ShellRoutes.test.tsx +43 -1
  4. package/src/core/events.ts +4 -2
  5. package/src/core/registry.ts +25 -3
  6. package/src/modules/embed/__tests__/EmbedView.test.tsx +560 -17
  7. package/src/modules/embed/__tests__/embed-config.test.ts +77 -1
  8. package/src/modules/embed/__tests__/mcp-app-view.test.ts +203 -1
  9. package/src/modules/embed/components/EmbedView.tsx +233 -47
  10. package/src/modules/embed/embed-config.ts +126 -2
  11. package/src/modules/embed/embed-host.ts +11 -2
  12. package/src/modules/embed/mount.tsx +1 -0
  13. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +213 -4
  14. package/src/modules/library/__tests__/PluginPage.test.tsx +1 -1
  15. package/src/modules/library/__tests__/SkillPage.test.tsx +10 -0
  16. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  17. package/src/modules/library/components/PluginPage.tsx +2 -1
  18. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  19. package/src/modules/library/components/tool-page/ToolPage.tsx +1 -1
  20. package/src/modules/library/index.ts +18 -0
  21. package/src/modules/library/routes/LibraryRoutes.tsx +17 -1
  22. package/src/modules/library/routes/library-paths.ts +16 -2
  23. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +3 -3
  24. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +39 -32
  25. package/src/modules/secrets-vault/components/SecretsPage.tsx +9 -24
  26. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +111 -8
  27. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +1 -1
  28. package/src/modules/secrets-vault/index.ts +7 -0
  29. package/src/modules/settings/settings-nav-items.tsx +3 -3
  30. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -37
  31. package/src/modules/toolbar/commands/actions.tsx +62 -50
  32. package/src/modules/toolbar/commands/command-menu.ts +37 -3
  33. package/src/modules/toolbar/commands/useCommandShortcuts.ts +29 -76
  34. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +4 -2
  35. package/src/modules/toolbar/components/SearchPalette.tsx +20 -21
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +5 -2
  37. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +242 -103
  38. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +51 -1
  39. package/src/modules/toolbar/search/__tests__/rank.test.ts +7 -3
  40. package/src/modules/workflow/hooks/__tests__/useFileLock.test.tsx +475 -0
  41. package/src/modules/workflow/hooks/__tests__/useFileLock.wire.test.tsx +115 -0
  42. package/src/modules/workflow/hooks/useFileLock.ts +321 -57
  43. package/src/modules/workflow/index.ts +8 -0
  44. package/src/modules/workflow/services/__tests__/lock.api.test.ts +4 -0
  45. package/src/modules/workflow/services/lock.api.ts +28 -9
  46. package/src/modules/workspace/components/FileViewer.tsx +30 -16
  47. package/src/modules/workspace/components/KbPageHeader.tsx +8 -1
  48. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +107 -4
  49. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +12 -0
  50. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +118 -13
  51. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +189 -0
  52. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +9 -0
  53. package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +60 -0
  54. package/src/modules/workspace/components/renderers/frameResizeHandle.ts +116 -0
  55. package/src/modules/workspace/components/renderers/index.ts +6 -0
  56. package/src/modules/workspace/components/renderers/kbGraphLoader.ts +27 -0
  57. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +1 -1
  58. package/src/modules/workspace/components/renderers/rendererSurface.ts +19 -0
  59. package/src/modules/workspace/index.ts +33 -0
@@ -8,6 +8,7 @@ import {
8
8
  heartbeatLock,
9
9
  LockApiError,
10
10
  releaseLock as releaseLockApi,
11
+ SELF_HOLD_MESSAGE,
11
12
  } from '../services/lock.api';
12
13
  import { useEventBus, canonicalizeWorkspaceId } from '../state/event-bus.context';
13
14
 
@@ -23,6 +24,81 @@ const AUTOSAVE_INTERVAL_MS = 60_000;
23
24
  * to think doesn't kick the user out of Edit mode mid-work.
24
25
  */
25
26
  const IDLE_RELEASE_MS = 120_000;
27
+ /**
28
+ * When a held notice is on screen, the hook asks again just after the hold
29
+ * would expire, so the notice clears by itself (and Edit comes back) when
30
+ * the holder's tab died without giving the page back. The margin covers
31
+ * the server answering a moment late; the bounds keep a skewed client
32
+ * clock from polling in a tight loop or waiting far past the server's
33
+ * 60-second hold. A hold with no known expiry (one learned from the event
34
+ * bus) is asked about after the longest wait.
35
+ */
36
+ const EXPIRY_RECHECK_MARGIN_MS = 1_000;
37
+ const MIN_EXPIRY_RECHECK_MS = 5_000;
38
+ const MAX_EXPIRY_RECHECK_MS = 65_000;
39
+
40
+ /**
41
+ * Lock requests this browser tab has sent and not yet heard back from,
42
+ * across every mounted editor, keyed by `lockKey`. What the viewer sees for
43
+ * a hold depends on whose it is and on these:
44
+ *
45
+ * | hold under | request of this tab in flight | shown |
46
+ * |-----------------------|-------------------------------|------------------|
47
+ * | someone else's id | either | "<name> is |
48
+ * | | | editing…" |
49
+ * | the viewer's own id | yes (release of the editor | nothing, then |
50
+ * | | that just unmounted, or the | asked again |
51
+ * | | echo of its own acquire) | once it settles |
52
+ * | the viewer's own id | no (another tab, their agent, | SELF_HOLD_MESSAGE|
53
+ * | | a closed browser whose hold | — Edit waits |
54
+ * | | has not expired) | for it to end |
55
+ *
56
+ * "Asked again once it settles" is what keeps the middle row honest: a
57
+ * release that fails leaves the hold in place, and the re-ask then finds it
58
+ * with nothing in flight and shows the self-hold notice.
59
+ */
60
+ const requestsInFlight = new Map<string, number>();
61
+ const settleWaiters = new Map<string, Array<() => void>>();
62
+
63
+ function lockKey(workspaceId: string, branch: string, path: string): string {
64
+ return `${canonicalizeWorkspaceId(workspaceId)}\n${branch}\n${path}`;
65
+ }
66
+
67
+ function inFlight(key: string): boolean {
68
+ return (requestsInFlight.get(key) ?? 0) > 0;
69
+ }
70
+
71
+ /** Resolves once nothing is in flight for `key` (at once if nothing is). */
72
+ function whenSettled(key: string): Promise<void> {
73
+ if (!inFlight(key)) return Promise.resolve();
74
+ return new Promise((resolve) => {
75
+ settleWaiters.set(key, [...(settleWaiters.get(key) ?? []), resolve]);
76
+ });
77
+ }
78
+
79
+ /** Count `request` as in flight for `key` until it settles, either way. */
80
+ function trackInFlight<T>(key: string, request: () => Promise<T>): Promise<T> {
81
+ requestsInFlight.set(key, (requestsInFlight.get(key) ?? 0) + 1);
82
+ const settle = () => {
83
+ const left = (requestsInFlight.get(key) ?? 1) - 1;
84
+ if (left > 0) {
85
+ requestsInFlight.set(key, left);
86
+ return;
87
+ }
88
+ requestsInFlight.delete(key);
89
+ const waiters = settleWaiters.get(key) ?? [];
90
+ settleWaiters.delete(key);
91
+ waiters.forEach((resolve) => resolve());
92
+ };
93
+ let pending: Promise<T>;
94
+ try {
95
+ pending = request();
96
+ } catch (err) {
97
+ settle();
98
+ throw err;
99
+ }
100
+ return pending.finally(settle);
101
+ }
26
102
 
27
103
  interface UseFileLockArgs {
28
104
  /** The workspace id of the branch we're editing on. Null disables the hook. */
@@ -33,12 +109,12 @@ interface UseFileLockArgs {
33
109
  path: string | null;
34
110
  /**
35
111
  * Current authenticated user's id. Used to recognise "this lock is held
36
- * by me" responses from the server during the brief window between a
37
- * tab-switch cleanup releasing the lock and the backend actually
38
- * committing the release — without this, switching away and back to a
39
- * file you were just editing would flicker an amber "[your own name]
40
- * is editing this page" banner. Optional so test harnesses without auth context
41
- * still work; in that case nothing is filtered.
112
+ * by me" responses from the server while a tab-switch cleanup's save or
113
+ * release request for the page is still in flight (both count, see
114
+ * `requestsInFlight`) — without this, switching away and back to a file
115
+ * you were just editing would flicker an amber "[your own name] is
116
+ * editing this page" banner. Optional so test harnesses without auth
117
+ * context still work; in that case nothing is filtered.
42
118
  */
43
119
  currentUserId?: string | null;
44
120
  /**
@@ -58,7 +134,8 @@ interface UseFileLockArgs {
58
134
 
59
135
  /**
60
136
  * Result of an `acquire()` attempt. `acquired` is the success flag;
61
- * `contended` is true only when the failure is another user's lock (the
137
+ * `contended` is true only when the failure is a live hold held elsewhere —
138
+ * someone else's, or the viewer's own from another tab or their agent (the
62
139
  * externalLock banner covers that case); `error` carries the message for
63
140
  * every non-contention failure (access-denied 403, network, etc.).
64
141
  */
@@ -71,19 +148,32 @@ export interface AcquireOutcome {
71
148
  interface UseFileLockReturn {
72
149
  /** True iff this client currently holds the lock. */
73
150
  holdingLock: boolean;
74
- /** Lock currently held by someone else (or null if we hold it / nobody does). */
151
+ /**
152
+ * Lock this client does not hold (or null if we hold it / nobody does).
153
+ * It can still be the viewer's own: another of their tabs, a closed
154
+ * browser whose hold has not expired, or their agent saving — see
155
+ * `externalLockIsMine`.
156
+ */
75
157
  externalLock: FileLock | null;
158
+ /**
159
+ * True when `externalLock` is held under the viewer's own user id. The
160
+ * UI then says "You have this page open for editing somewhere else…"
161
+ * (`SELF_HOLD_MESSAGE`) and never names the viewer as someone else.
162
+ */
163
+ externalLockIsMine: boolean;
76
164
  /** Latest acquire / heartbeat error, surfaced in the UI as a banner. */
77
165
  lockError: string | null;
78
166
  /**
79
- * Acquire the lock. Idempotent — re-acquiring a lock you already hold
80
- * refreshes the TTL. Resolves to an outcome the caller can act on
167
+ * Acquire the lock. Not a refresh: the server refuses any live hold,
168
+ * the caller's own included (another tab, their agent), and only takes
169
+ * over an expired one; the heartbeat is what extends a hold this client
170
+ * already has. Resolves to an outcome the caller can act on
81
171
  * WITHOUT reading `lockError`/`externalLock` off the hook return —
82
172
  * those are React state and are stale in the caller's closure right
83
- * after the `await`. `contended` distinguishes "held by someone else"
84
- * (surfaced by the externalLock banner) from an access-denied / network
85
- * failure (`error` set, `contended` false) that the caller must surface
86
- * itself.
173
+ * after the `await`. `contended` distinguishes "held elsewhere"
174
+ * (surfaced by the externalLock banner, as the self-hold notice when the
175
+ * hold is the viewer's own) from an access-denied / network failure
176
+ * (`error` set, `contended` false) that the caller must surface itself.
87
177
  */
88
178
  acquire: () => Promise<AcquireOutcome>;
89
179
  /**
@@ -93,10 +183,12 @@ interface UseFileLockReturn {
93
183
  */
94
184
  saveCheckpoint: (summary?: string) => Promise<Change | null>;
95
185
  /**
96
- * Final save: write the current buffer to disk, commit it, and release
97
- * the lock. Used on file-close / navigate-away / explicit "done editing".
186
+ * Final save: write the current buffer to disk and release the lock;
187
+ * the server queues the commit of what is on disk, so there is no
188
+ * change to return. Used on file-close / navigate-away / explicit
189
+ * "done editing".
98
190
  */
99
- saveAndRelease: (summary?: string) => Promise<Change | null>;
191
+ saveAndRelease: (summary?: string) => Promise<void>;
100
192
  /**
101
193
  * Reset the idle-release timer. Callers (the editor) wire this to every
102
194
  * interaction with the file — keystrokes, scroll events. After
@@ -122,8 +214,9 @@ interface UseFileLockReturn {
122
214
  * the latest buffer + commit. The lock stays held — releasing here
123
215
  * would race against the next keystroke.
124
216
  * - Release on unmount / branch-or-path change. The cleanup callback
125
- * commits the final pending content and drops the lock so the next
126
- * editor can take over.
217
+ * writes the final pending content to disk and drops the lock so the
218
+ * next editor can take over; the server queues the commit of what is
219
+ * on disk.
127
220
  */
128
221
  export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
129
222
  const { workspaceId, branch, path, currentUserId } = args;
@@ -141,18 +234,35 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
141
234
  useEffect(() => { holdingLockRef.current = holdingLock; }, [holdingLock]);
142
235
 
143
236
  // Reset state when the (workspace, branch, path) tuple changes — opening
144
- // a different file is a fresh lock context, not a continuation.
145
- useEffect(() => {
237
+ // a different file is a fresh lock context, not a continuation. Done while
238
+ // rendering (React's "adjusting state when a prop changes"), not in an
239
+ // effect, so no effect of the new file ever runs with the old file's
240
+ // state. `holdingLockRef` still follows in its effect, after the old
241
+ // file's unmount cleanup has read it and released.
242
+ const lockContext = `${workspaceId ?? ''}\n${branch ?? ''}\n${path ?? ''}`;
243
+ const [stateContext, setStateContext] = useState(lockContext);
244
+ if (stateContext !== lockContext) {
245
+ setStateContext(lockContext);
146
246
  setHoldingLock(false);
147
247
  setExternalLock(null);
148
248
  setLockError(null);
149
- }, [workspaceId, branch, path]);
249
+ }
250
+
251
+ const isMine = useCallback(
252
+ (lock: FileLock | null): boolean => !!lock && !!currentUserId && lock.holderUserId === currentUserId,
253
+ [currentUserId],
254
+ );
255
+ const heldMessage = useCallback(
256
+ (lock: FileLock): string => (isMine(lock) ? SELF_HOLD_MESSAGE : `${lock.holderName} is editing this page`),
257
+ [isMine],
258
+ );
150
259
 
151
260
  const acquire = useCallback(async (): Promise<AcquireOutcome> => {
152
261
  if (!workspaceId || !branch || !path) return { acquired: false, contended: false, error: null };
153
262
  console.debug('[useFileLock] acquire start', { workspaceId, branch, path });
154
263
  try {
155
- const result = await acquireLockApi(workspaceId, branch, path);
264
+ const result = await trackInFlight(lockKey(workspaceId, branch, path), () =>
265
+ acquireLockApi(workspaceId, branch, path));
156
266
  if (result.acquired) {
157
267
  console.debug('[useFileLock] acquire ok', { workspaceId, branch, path });
158
268
  setHoldingLock(true);
@@ -165,7 +275,7 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
165
275
  holder: result.lock.holderName,
166
276
  holderUserId: result.lock.holderUserId,
167
277
  });
168
- const msg = `${result.lock.holderName} is editing this page`;
278
+ const msg = heldMessage(result.lock);
169
279
  setHoldingLock(false);
170
280
  setExternalLock(result.lock);
171
281
  setLockError(msg);
@@ -177,7 +287,7 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
177
287
  setHoldingLock(false);
178
288
  return { acquired: false, contended: false, error: msg };
179
289
  }
180
- }, [workspaceId, branch, path]);
290
+ }, [workspaceId, branch, path, heldMessage]);
181
291
 
182
292
  const persistAndCommit = useCallback(
183
293
  async (mode: 'checkpoint' | 'release', summary?: string): Promise<Change | null> => {
@@ -200,10 +310,11 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
200
310
  console.debug('[useFileLock] checkpoint ok', { workspaceId, branch, path, sha: change?.sha ?? null });
201
311
  return change;
202
312
  }
203
- const change = await releaseLockApi(workspaceId, branch, path, summary);
204
- console.debug('[useFileLock] release ok', { workspaceId, branch, path, sha: change?.sha ?? null });
313
+ await trackInFlight(lockKey(workspaceId, branch, path), () =>
314
+ releaseLockApi(workspaceId, branch, path, summary));
315
+ console.debug('[useFileLock] release ok', { workspaceId, branch, path });
205
316
  setHoldingLock(false);
206
- return change;
317
+ return null;
207
318
  } catch (err) {
208
319
  const msg = err instanceof Error ? err.message : String(err);
209
320
  console.warn(`[useFileLock] ${mode} failed`, {
@@ -229,7 +340,7 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
229
340
  );
230
341
 
231
342
  const saveAndRelease = useCallback(
232
- (summary?: string) => persistAndCommit('release', summary),
343
+ async (summary?: string): Promise<void> => { await persistAndCommit('release', summary); },
233
344
  [persistAndCommit],
234
345
  );
235
346
 
@@ -277,32 +388,85 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
277
388
  useEffect(() => {
278
389
  if (holdingLock || !workspaceId || !branch || !path) return;
279
390
  let cancelled = false;
280
- // "Lock held by me" means the previous tab's cleanup hasn't finished
281
- // committing the release on the backend yet — we just switched away
282
- // and back fast enough that the persist+release is still in flight.
283
- // We don't want to render an amber "[you] is editing this page" banner
284
- // for that fraction of a second; the SSE `lock-released` event
285
- // will arrive shortly and we'll be back to a clean state.
286
- const isSelfLock = (lock: FileLock | null): boolean =>
287
- !!lock && !!currentUserId && lock.holderUserId === currentUserId;
288
- getLockApi(workspaceId, branch, path)
289
- .then((lock) => {
290
- if (cancelled) return;
291
- setExternalLock(isSelfLock(lock) ? null : lock);
292
- })
293
- .catch(() => { /* network blip — events will catch us up */ });
294
- if (!bus) return () => { cancelled = true; };
391
+ const key = lockKey(workspaceId, branch, path);
392
+ // A hold under the viewer's own id while this tab still has a request
393
+ // in flight for the page is the previous editor's save+release not yet
394
+ // committed (we switched away and back fast enough). A notice for that
395
+ // fraction of a second would be wrong; the SSE `lock-released` event
396
+ // arrives shortly. Any other hold of theirs is live — another tab,
397
+ // their agent — and gets the self-hold notice now, so the page does
398
+ // not look editable until Edit fails. Hidden is never final: once the
399
+ // request settles we ask again, so a release that failed (and left the
400
+ // hold in place, with no `lock-released` to come) shows as the
401
+ // self-hold notice instead of a page that looks free. That re-ask is
402
+ // retried until it gets an answer (5 s, 10 s, 20 s, 40 s, then every
403
+ // 65 s): a hold was seen and hidden, and if the release failed no event
404
+ // will ever correct the page. See the table on `requestsInFlight`.
405
+ let retryTimer: number | undefined;
406
+ // Every `lock-acquired` / `lock-released` event moves this on. An answer
407
+ // to a lookup asked BEFORE the event is older than the event and must
408
+ // not be applied over it: a stale `null` would clear a hold that was
409
+ // just acquired and make Edit look available while the server refuses
410
+ // the write; a stale holder would bring back a notice for a hold that
411
+ // was just released.
412
+ let generation = 0;
413
+ const ask = () => {
414
+ const asked = generation;
415
+ return getLockApi(workspaceId, branch, path).then((lock) => {
416
+ if (asked !== generation) return undefined;
417
+ return lock;
418
+ });
419
+ };
420
+ const reask = (failures = 0) => {
421
+ if (cancelled) return;
422
+ ask()
423
+ .then(onAnswer)
424
+ .catch(() => {
425
+ if (cancelled) return;
426
+ retryTimer = window.setTimeout(
427
+ () => reask(failures + 1),
428
+ Math.min(MIN_EXPIRY_RECHECK_MS * 2 ** failures, MAX_EXPIRY_RECHECK_MS),
429
+ );
430
+ });
431
+ };
432
+ const reaskOnceSettled = () => {
433
+ void whenSettled(key).then(() => { if (!cancelled) reask(); });
434
+ };
435
+ /** `undefined` is an answer overtaken by an event: nothing to apply. */
436
+ const onAnswer = (lock: FileLock | null | undefined) => {
437
+ if (cancelled || lock === undefined) return;
438
+ if (isMine(lock) && inFlight(key)) {
439
+ setExternalLock(null);
440
+ reaskOnceSettled();
441
+ return;
442
+ }
443
+ setExternalLock(lock);
444
+ };
445
+ ask()
446
+ .then(onAnswer)
447
+ .catch(() => { /* network blip, nothing seen yet — events will catch us up */ });
448
+ const stop = () => {
449
+ cancelled = true;
450
+ window.clearTimeout(retryTimer);
451
+ };
452
+ if (!bus) return stop;
295
453
  // Canonicalise once; event.workspaceId from the backend is decoded
296
454
  // (`razvan-radulescu/sc`) while the `workspaceId` prop is encoded
297
455
  // (`razvan-radulescu%2Fsc`). See `canonicalizeWorkspaceId` doc.
298
456
  const workspaceCanon = canonicalizeWorkspaceId(workspaceId);
299
457
  const offAcquired = bus.subscribe('lock-acquired', (e) => {
300
458
  if (e.branch !== branch || e.path !== path || canonicalizeWorkspaceId(e.workspaceId) !== workspaceCanon) return;
301
- // SSE echoes our own acquire too. If the event is about a lock
302
- // we just took on this client (rare — we'd already be in the
303
- // `holdingLock=true` branch and not subscribed — but cover it
304
- // for safety against state races), ignore it.
305
- if (currentUserId && e.holderUserId === currentUserId) return;
459
+ generation += 1;
460
+ // SSE echoes our own acquire too. If the event is about a lock this
461
+ // tab is taking right now (the echo can beat the response that flips
462
+ // `holdingLock`), ignore it — and ask again once that acquire
463
+ // settles, in case it did not end with this tab holding the page.
464
+ // The viewer's hold from another tab or their agent is shown, as the
465
+ // self-hold notice.
466
+ if (currentUserId && e.holderUserId === currentUserId && inFlight(key)) {
467
+ reaskOnceSettled();
468
+ return;
469
+ }
306
470
  setExternalLock({
307
471
  branch: e.branch,
308
472
  path: e.path,
@@ -318,14 +482,71 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
318
482
  });
319
483
  const offReleased = bus.subscribe('lock-released', (e) => {
320
484
  if (e.branch !== branch || e.path !== path || canonicalizeWorkspaceId(e.workspaceId) !== workspaceCanon) return;
485
+ generation += 1;
486
+ // The hold ended while its notice was on screen: the notice goes and
487
+ // Edit is available again, without a reload.
321
488
  setExternalLock(null);
489
+ setLockError(null);
322
490
  });
323
491
  return () => {
324
- cancelled = true;
492
+ stop();
325
493
  offAcquired();
326
494
  offReleased();
327
495
  };
328
- }, [holdingLock, workspaceId, branch, path, bus, currentUserId]);
496
+ }, [holdingLock, workspaceId, branch, path, bus, currentUserId, isMine]);
497
+
498
+ // Consecutive failed expiry re-checks. Each doubles the next wait, so an
499
+ // unreachable server is not asked every few seconds for as long as a
500
+ // notice stays on screen.
501
+ const recheckFailuresRef = useRef(0);
502
+ useEffect(() => { recheckFailuresRef.current = 0; }, [workspaceId, branch, path]);
503
+
504
+ // Re-check at expiry. A hold whose tab crashed, slept or lost the
505
+ // network as it closed sends no `lock-released`; it simply expires on the
506
+ // server. While its notice is on screen, ask again just after the expiry:
507
+ // gone → clear the notice so Edit works without a reload; renewed (the
508
+ // holder is still there) → keep it, with the new expiry scheduling the
509
+ // next ask.
510
+ useEffect(() => {
511
+ if (holdingLock || !externalLock || !workspaceId || !branch || !path) return;
512
+ const expiresAtMs = Date.parse(externalLock.expiresAt);
513
+ const failures = recheckFailuresRef.current;
514
+ const delay = failures > 0
515
+ ? Math.min(MIN_EXPIRY_RECHECK_MS * 2 ** failures, MAX_EXPIRY_RECHECK_MS)
516
+ : Number.isNaN(expiresAtMs)
517
+ ? MAX_EXPIRY_RECHECK_MS
518
+ : Math.min(
519
+ Math.max(expiresAtMs - Date.now() + EXPIRY_RECHECK_MARGIN_MS, MIN_EXPIRY_RECHECK_MS),
520
+ MAX_EXPIRY_RECHECK_MS,
521
+ );
522
+ let cancelled = false;
523
+ const id = window.setTimeout(() => {
524
+ getLockApi(workspaceId, branch, path)
525
+ .then((lock) => {
526
+ if (cancelled) return;
527
+ recheckFailuresRef.current = 0;
528
+ if (lock) {
529
+ setExternalLock(lock);
530
+ setLockError(heldMessage(lock));
531
+ return;
532
+ }
533
+ setExternalLock(null);
534
+ setLockError(null);
535
+ })
536
+ .catch(() => {
537
+ // Network blip: ask again, waiting twice as long as last time
538
+ // (10 s, 20 s, 40 s, then every 65 s). A fresh object re-runs
539
+ // this effect with the longer wait.
540
+ if (cancelled) return;
541
+ recheckFailuresRef.current += 1;
542
+ setExternalLock((current) => (current ? { ...current } : current));
543
+ });
544
+ }, delay);
545
+ return () => {
546
+ cancelled = true;
547
+ window.clearTimeout(id);
548
+ };
549
+ }, [holdingLock, externalLock, workspaceId, branch, path, heldMessage]);
329
550
 
330
551
  // Autosave checkpoint timer. Runs every minute while holding the lock
331
552
  // *and* the buffer is non-null. The lock stays held across checkpoints
@@ -367,9 +588,10 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
367
588
  idleTimerRef.current = window.setTimeout(() => {
368
589
  idleTimerRef.current = null;
369
590
  if (!holdingLockRef.current) return;
370
- // saveAndRelease writes the current buffer (if any), commits, and
371
- // releases the lock. On success the `holdingLock` state flips to
372
- // false; the editor's `readOnly` check reacts on the next render.
591
+ // saveAndRelease writes the current buffer (if any) and releases
592
+ // the lock; the server queues the commit of what is on disk. On
593
+ // success the `holdingLock` state flips to false; the editor's
594
+ // `readOnly` check reacts on the next render.
373
595
  // On failure we leave the timer cleared — the user's next
374
596
  // activity will start a fresh one. Errors are logged here because
375
597
  // the hook user has already moved on by definition (they were
@@ -400,6 +622,34 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
400
622
  startIdleTimer();
401
623
  }, [startIdleTimer]);
402
624
 
625
+ // Release on close, reload or leaving for another site. None of those
626
+ // unmounts React, so the cleanup below never runs for them, and the hold
627
+ // used to linger until its expiry. `pagehide` fires only once the page is
628
+ // really going (after the person accepts the unsaved-changes warning, and
629
+ // never for a tab switch or a minimised window — those are
630
+ // `visibilitychange`, which deliberately releases nothing). The request is
631
+ // keep-alive so it outlives the page; if it never arrives, the server's
632
+ // expiry ends the hold as before. Nothing is persisted first: text typed
633
+ // since the last automatic save is not saved on close, as before — the
634
+ // server's release commits only what is already on disk.
635
+ useEffect(() => {
636
+ if (!holdingLock || !workspaceId || !branch || !path) return;
637
+ const onPageHide = () => {
638
+ if (!holdingLockRef.current) return;
639
+ // Not holding any more, so the unmount cleanup does not release a
640
+ // second time, and a page restored from the back-forward cache
641
+ // re-acquires on Edit rather than believing it still holds.
642
+ holdingLockRef.current = false;
643
+ setHoldingLock(false);
644
+ trackInFlight(lockKey(workspaceId, branch, path), () =>
645
+ releaseLockApi(workspaceId, branch, path, undefined, { keepalive: true })).catch((err) => {
646
+ console.warn('[useFileLock] release on pagehide failed:', err);
647
+ });
648
+ };
649
+ window.addEventListener('pagehide', onPageHide);
650
+ return () => window.removeEventListener('pagehide', onPageHide);
651
+ }, [holdingLock, workspaceId, branch, path]);
652
+
403
653
  // Release the lock when the editor unmounts or switches files. Best-
404
654
  // effort — a failure here is logged but doesn't surface to the user,
405
655
  // they've already moved on. Before releasing, persist the latest
@@ -411,12 +661,15 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
411
661
  return () => {
412
662
  if (!holdingLockRef.current || !workspaceId || !branch || !path) return;
413
663
  const pending = readPendingContentRef.current();
664
+ const key = lockKey(workspaceId, branch, path);
414
665
  const release = () =>
415
- releaseLockApi(workspaceId, branch, path).catch((err) => {
666
+ trackInFlight(key, () => releaseLockApi(workspaceId, branch, path)).catch((err) => {
416
667
  console.warn('[useFileLock] release on unmount failed:', err);
417
668
  });
418
669
  if (pending !== null) {
419
- persistToDiskRef.current(pending).then(release, (err) => {
670
+ // Counted from the save, not the release: the editor that mounts
671
+ // next asks who holds the page while the save is still running.
672
+ trackInFlight(key, () => persistToDiskRef.current(pending)).then(release, (err) => {
420
673
  console.warn('[useFileLock] persist on unmount failed:', err);
421
674
  // Release anyway so the lock doesn't get stuck; whatever was
422
675
  // last successfully written to disk will be what the release-
@@ -429,5 +682,16 @@ export function useFileLock(args: UseFileLockArgs): UseFileLockReturn {
429
682
  };
430
683
  }, [workspaceId, branch, path]);
431
684
 
432
- return { holdingLock, externalLock, lockError, acquire, saveCheckpoint, saveAndRelease, recordActivity };
685
+ const externalLockIsMine = isMine(externalLock);
686
+
687
+ return {
688
+ holdingLock,
689
+ externalLock,
690
+ externalLockIsMine,
691
+ lockError,
692
+ acquire,
693
+ saveCheckpoint,
694
+ saveAndRelease,
695
+ recordActivity,
696
+ };
433
697
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Workflow's public surface for other modules: the per-file edit hold the
3
+ * editor takes, and the sentences and error type that come with it. Other
4
+ * modules import these from here rather than reaching into workflow's
5
+ * hooks and services.
6
+ */
7
+ export { useFileLock, type AcquireOutcome } from './hooks/useFileLock';
8
+ export { LockApiError, SELF_HOLD_MESSAGE } from './services/lock.api';
@@ -39,3 +39,7 @@ describe('lock.api', () => {
39
39
  expect((err as LockApiError).message).toBe('"Foo.md" is being edited by Dana. Try again in a moment.');
40
40
  });
41
41
  });
42
+
43
+ // What a release looks like on the wire (keep-alive on `pagehide`, the
44
+ // bearer header, the queued answer) is tested through workflow's entry
45
+ // point in `hooks/__tests__/useFileLock.wire.test.tsx`, not here.
@@ -38,6 +38,17 @@ export class LockApiError extends Error {
38
38
  export const EDITING_ENDED_MESSAGE =
39
39
  'Your editing session ended. Check the page and edit it again if anything is missing.';
40
40
 
41
+ /**
42
+ * What a person reads when the page is held under their own user id —
43
+ * another of their tabs, a browser that closed without giving it back, or
44
+ * their agent saving. Never "<their own name> is editing this page": the
45
+ * server refuses their own live hold on purpose (an agent writes as the
46
+ * person who connected it), so the honest answer is that it is theirs and
47
+ * will free up.
48
+ */
49
+ export const SELF_HOLD_MESSAGE =
50
+ 'You have this page open for editing somewhere else, in another tab or through your agent. You can edit it here in a moment.';
51
+
41
52
  async function unwrap<T>(res: Response): Promise<T> {
42
53
  if (res.ok) return (await res.json()) as T;
43
54
  let body: unknown;
@@ -59,9 +70,11 @@ async function unwrap<T>(res: Response): Promise<T> {
59
70
  /**
60
71
  * Try to acquire the lock for `(branch, path)`. Resolves with the
61
72
  * `AcquireLockResult` payload — `acquired: true` when the caller now
62
- * holds the lock, `acquired: false` when someone else does (the
63
- * holder's lock state is included so the UI can render "X is editing
64
- * this page" without a follow-up call).
73
+ * holds the lock, `acquired: false` when a live hold is held elsewhere:
74
+ * someone else's, or the caller's own from another tab or their agent
75
+ * (the server refuses a live hold whoever holds it). The hold is included
76
+ * so the UI can say "X is editing this page", or `SELF_HOLD_MESSAGE` for
77
+ * the caller's own, without a follow-up call.
65
78
  */
66
79
  export async function acquireLock(
67
80
  workspaceId: string,
@@ -116,24 +129,30 @@ export async function checkpointLockedFile(
116
129
  }
117
130
 
118
131
  /**
119
- * Release the lock AND commit any pending edits as a final change.
120
- * Returns `null` when the file had no pending edits (idempotent on a
121
- * clean release).
132
+ * Release the lock. The server drops the hold at once and queues the
133
+ * commit of whatever is on disk for its background worker, answering
134
+ * `{ queued: true }` — there is no change to return yet, so this resolves
135
+ * with nothing once the hold is released.
136
+ *
137
+ * `keepalive` lets the request outlive the page that sends it: the release
138
+ * a closing or reloading tab sends on `pagehide`. Unlike `sendBeacon`, a
139
+ * keep-alive `fetch` still carries the bearer header.
122
140
  */
123
141
  export async function releaseLock(
124
142
  workspaceId: string,
125
143
  branch: string,
126
144
  path: string,
127
145
  summary?: string,
128
- ): Promise<Change | null> {
129
- const { change } = await unwrap<{ change: Change | null }>(
146
+ options: { keepalive?: boolean } = {},
147
+ ): Promise<void> {
148
+ await unwrap<{ queued: true }>(
130
149
  await authFetch(`/api/workspace/${workspaceId}/workflow/locks`, {
131
150
  method: 'DELETE',
132
151
  headers: { 'Content-Type': 'application/json' },
133
152
  body: JSON.stringify({ branch, path, summary }),
153
+ ...(options.keepalive ? { keepalive: true } : {}),
134
154
  }),
135
155
  );
136
- return change;
137
156
  }
138
157
 
139
158
  /**