@bevel-software/platform-core-frontend 0.28.1 → 0.30.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.
- package/package.json +11 -4
- package/src/core/CoreAppShell.tsx +29 -11
- package/src/core/__tests__/ShellRoutes.test.tsx +43 -1
- package/src/core/events.ts +4 -2
- package/src/core/registry.ts +25 -3
- package/src/modules/embed/__tests__/EmbedView.test.tsx +560 -17
- package/src/modules/embed/__tests__/embed-config.test.ts +77 -1
- package/src/modules/embed/__tests__/mcp-app-view.test.ts +203 -1
- package/src/modules/embed/components/EmbedView.tsx +233 -47
- package/src/modules/embed/embed-config.ts +126 -2
- package/src/modules/embed/embed-host.ts +11 -2
- package/src/modules/embed/mount.tsx +1 -0
- package/src/modules/library/__tests__/LibraryRoutes.test.tsx +213 -4
- package/src/modules/library/__tests__/PluginPage.test.tsx +1 -1
- package/src/modules/library/__tests__/SkillPage.test.tsx +10 -0
- package/src/modules/library/components/LibraryLayout.tsx +2 -2
- package/src/modules/library/components/PluginPage.tsx +2 -1
- package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
- package/src/modules/library/components/tool-page/ToolPage.tsx +1 -1
- package/src/modules/library/index.ts +18 -0
- package/src/modules/library/routes/LibraryRoutes.tsx +17 -1
- package/src/modules/library/routes/library-paths.ts +16 -2
- package/src/modules/onboarding/__tests__/get-started-column.test.tsx +3 -3
- package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +39 -32
- package/src/modules/secrets-vault/components/SecretsPage.tsx +9 -24
- package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +111 -8
- package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +1 -1
- package/src/modules/secrets-vault/index.ts +7 -0
- package/src/modules/settings/settings-nav-items.tsx +3 -3
- package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -37
- package/src/modules/toolbar/commands/actions.tsx +62 -50
- package/src/modules/toolbar/commands/command-menu.ts +37 -3
- package/src/modules/toolbar/commands/useCommandShortcuts.ts +29 -76
- package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +4 -2
- package/src/modules/toolbar/components/SearchPalette.tsx +20 -21
- package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +5 -2
- package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +242 -103
- package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +51 -1
- package/src/modules/toolbar/search/__tests__/rank.test.ts +7 -3
- package/src/modules/workflow/hooks/__tests__/useFileLock.test.tsx +475 -0
- package/src/modules/workflow/hooks/__tests__/useFileLock.wire.test.tsx +115 -0
- package/src/modules/workflow/hooks/useFileLock.ts +321 -57
- package/src/modules/workflow/index.ts +8 -0
- package/src/modules/workflow/services/__tests__/lock.api.test.ts +4 -0
- package/src/modules/workflow/services/lock.api.ts +28 -9
- package/src/modules/workspace/components/FileViewer.tsx +30 -16
- package/src/modules/workspace/components/KbPageHeader.tsx +8 -1
- package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +107 -4
- package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +12 -0
- package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +118 -13
- package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +189 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +9 -0
- package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +60 -0
- package/src/modules/workspace/components/renderers/frameResizeHandle.ts +116 -0
- package/src/modules/workspace/components/renderers/index.ts +6 -0
- package/src/modules/workspace/components/renderers/kbGraphLoader.ts +27 -0
- package/src/modules/workspace/components/renderers/lazyRenderer.tsx +1 -1
- package/src/modules/workspace/components/renderers/rendererSurface.ts +19 -0
- package/src/modules/workspace/index.ts +33 -0
|
@@ -76,7 +76,7 @@ describe('rankByNames', () => {
|
|
|
76
76
|
const commands = [
|
|
77
77
|
{ label: 'Invite people', keywords: ['team', 'members'] },
|
|
78
78
|
{ label: 'Team settings', keywords: [] },
|
|
79
|
-
{ label: '
|
|
79
|
+
{ label: 'Create new page', keywords: ['new page', 'write'] },
|
|
80
80
|
];
|
|
81
81
|
const ranked = (query: string) =>
|
|
82
82
|
rankByNames(commands, query, (c) => [c.label, ...c.keywords], 10).map((c) => c.label);
|
|
@@ -84,10 +84,14 @@ describe('rankByNames', () => {
|
|
|
84
84
|
it('ranks an item at the best tier any of its names reaches', () => {
|
|
85
85
|
// "Invite people" reaches tier 0 through its keyword, as "Team settings" does through its label.
|
|
86
86
|
expect(ranked('team')).toEqual(['Invite people', 'Team settings']);
|
|
87
|
-
expect(ranked('wri')).toEqual(['
|
|
87
|
+
expect(ranked('wri')).toEqual(['Create new page']);
|
|
88
|
+
// The command's old name still finds it first, through its keyword.
|
|
89
|
+
expect(ranked('new page')).toEqual(['Create new page']);
|
|
90
|
+
expect(ranked('new')).toEqual(['Create new page']);
|
|
88
91
|
});
|
|
89
92
|
|
|
90
93
|
it('breaks ties on the first name, the one on screen', () => {
|
|
91
|
-
|
|
94
|
+
// "Create new page" is longer on screen than the other two, though its keyword "write" is shorter.
|
|
95
|
+
expect(ranked('e')).toEqual(['Invite people', 'Team settings', 'Create new page']);
|
|
92
96
|
});
|
|
93
97
|
});
|
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import { act, renderHook } from '@testing-library/react';
|
|
3
|
+
import type { ReactNode } from 'react';
|
|
4
|
+
import type { FileLock, WorkflowEvent } from '@bevel-software/platform-shared';
|
|
5
|
+
|
|
6
|
+
// The lock endpoints are the hook's only side effects; each test decides what
|
|
7
|
+
// they answer. The sentences stay real — they are what the person reads.
|
|
8
|
+
const api = vi.hoisted(() => ({
|
|
9
|
+
acquireLock: vi.fn(),
|
|
10
|
+
heartbeatLock: vi.fn(async () => ({})),
|
|
11
|
+
checkpointLockedFile: vi.fn(async () => null),
|
|
12
|
+
releaseLock: vi.fn(async (): Promise<void> => {}),
|
|
13
|
+
getLock: vi.fn(async (): Promise<FileLock | null> => null),
|
|
14
|
+
}));
|
|
15
|
+
vi.mock('../../services/lock.api', async (importOriginal) => ({
|
|
16
|
+
...(await importOriginal<typeof import('../../services/lock.api')>()),
|
|
17
|
+
...api,
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
// The hook and its sentence come through workflow's public entry point, as
|
|
21
|
+
// other modules see them.
|
|
22
|
+
import { useFileLock, SELF_HOLD_MESSAGE } from '../..';
|
|
23
|
+
import { EventBusContext, type EventBusContextValue } from '../../state/event-bus.context';
|
|
24
|
+
|
|
25
|
+
const ME = 'u-juan';
|
|
26
|
+
|
|
27
|
+
function lockHeldBy(holderUserId: string, holderName: string, expiresInMs = 60_000): FileLock {
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
return {
|
|
30
|
+
branch: 'main',
|
|
31
|
+
path: 'kb/Knowledge/Foo.md',
|
|
32
|
+
holderUserId,
|
|
33
|
+
holderName,
|
|
34
|
+
acquiredAt: new Date(now).toISOString(),
|
|
35
|
+
lastHeartbeatAt: new Date(now).toISOString(),
|
|
36
|
+
expiresAt: new Date(now + expiresInMs).toISOString(),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A bus the test can publish `lock-*` events on. */
|
|
41
|
+
function makeBus() {
|
|
42
|
+
const handlers = new Map<string, Set<(e: WorkflowEvent) => void>>();
|
|
43
|
+
const bus: EventBusContextValue = {
|
|
44
|
+
subscribe: (kind, handler) => {
|
|
45
|
+
const set = handlers.get(kind) ?? new Set();
|
|
46
|
+
set.add(handler as (e: WorkflowEvent) => void);
|
|
47
|
+
handlers.set(kind, set);
|
|
48
|
+
return () => set.delete(handler as (e: WorkflowEvent) => void);
|
|
49
|
+
},
|
|
50
|
+
setFocus: () => {},
|
|
51
|
+
watchWorkspace: () => () => {},
|
|
52
|
+
};
|
|
53
|
+
const publish = (e: WorkflowEvent) => handlers.get(e.kind)?.forEach((h) => h(e));
|
|
54
|
+
return { bus, publish };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function setup(opts: { pending?: string | null; bus?: EventBusContextValue } = {}) {
|
|
58
|
+
const persistToDisk = vi.fn(async () => {});
|
|
59
|
+
const wrapper = opts.bus
|
|
60
|
+
? ({ children }: { children: ReactNode }) => (
|
|
61
|
+
<EventBusContext.Provider value={opts.bus!}>{children}</EventBusContext.Provider>
|
|
62
|
+
)
|
|
63
|
+
: undefined;
|
|
64
|
+
const hook = renderHook(
|
|
65
|
+
() =>
|
|
66
|
+
useFileLock({
|
|
67
|
+
workspaceId: 'ws',
|
|
68
|
+
branch: 'main',
|
|
69
|
+
path: 'kb/Knowledge/Foo.md',
|
|
70
|
+
currentUserId: ME,
|
|
71
|
+
readPendingContent: () => (opts.pending === undefined ? 'typed since the last autosave' : opts.pending),
|
|
72
|
+
persistToDisk,
|
|
73
|
+
}),
|
|
74
|
+
{ wrapper },
|
|
75
|
+
);
|
|
76
|
+
return { ...hook, persistToDisk };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function acquireHeld(result: { current: ReturnType<typeof useFileLock> }) {
|
|
80
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: true, lock: lockHeldBy(ME, 'Juan') });
|
|
81
|
+
await act(async () => { await result.current.acquire(); });
|
|
82
|
+
expect(result.current.holdingLock).toBe(true);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
beforeEach(() => {
|
|
86
|
+
vi.clearAllMocks();
|
|
87
|
+
api.getLock.mockImplementation(async () => null);
|
|
88
|
+
api.releaseLock.mockImplementation(async () => {});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
afterEach(() => {
|
|
92
|
+
vi.useRealTimers();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('useFileLock — closing the tab gives the page back', () => {
|
|
96
|
+
it('releases at once on pagehide, keep-alive, without saving unsaved text', async () => {
|
|
97
|
+
const { result, persistToDisk } = setup();
|
|
98
|
+
await acquireHeld(result);
|
|
99
|
+
|
|
100
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
101
|
+
|
|
102
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
103
|
+
expect(api.releaseLock).toHaveBeenCalledWith('ws', 'main', 'kb/Knowledge/Foo.md', undefined, { keepalive: true });
|
|
104
|
+
// Text typed since the last automatic save is not written on close.
|
|
105
|
+
expect(persistToDisk).not.toHaveBeenCalled();
|
|
106
|
+
// A page restored from the back-forward cache must re-acquire on Edit.
|
|
107
|
+
expect(result.current.holdingLock).toBe(false);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('does not release a second time when the page then unmounts', async () => {
|
|
111
|
+
const { result, unmount } = setup();
|
|
112
|
+
await acquireHeld(result);
|
|
113
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
114
|
+
unmount();
|
|
115
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('does not release when the tab is switched away or the window minimised', async () => {
|
|
119
|
+
const { result } = setup();
|
|
120
|
+
await acquireHeld(result);
|
|
121
|
+
|
|
122
|
+
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });
|
|
123
|
+
Object.defineProperty(document, 'hidden', { configurable: true, get: () => true });
|
|
124
|
+
await act(async () => {
|
|
125
|
+
document.dispatchEvent(new Event('visibilitychange'));
|
|
126
|
+
window.dispatchEvent(new Event('blur'));
|
|
127
|
+
});
|
|
128
|
+
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' });
|
|
129
|
+
Object.defineProperty(document, 'hidden', { configurable: true, get: () => false });
|
|
130
|
+
|
|
131
|
+
expect(api.releaseLock).not.toHaveBeenCalled();
|
|
132
|
+
expect(result.current.holdingLock).toBe(true);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('sends nothing on pagehide when it does not hold the page', async () => {
|
|
136
|
+
setup();
|
|
137
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
138
|
+
expect(api.releaseLock).not.toHaveBeenCalled();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('stops listening once the editor has unmounted', async () => {
|
|
142
|
+
const { result, unmount } = setup({ pending: null });
|
|
143
|
+
await acquireHeld(result);
|
|
144
|
+
unmount();
|
|
145
|
+
// The unmount cleanup releases (in-app navigation, as before) …
|
|
146
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
147
|
+
expect(api.releaseLock).toHaveBeenLastCalledWith('ws', 'main', 'kb/Knowledge/Foo.md');
|
|
148
|
+
// … and a later pagehide finds no listener left to send another.
|
|
149
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
150
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('swallows a release that cannot be delivered; the hold is left to expire', async () => {
|
|
154
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
155
|
+
api.releaseLock.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
156
|
+
const { result } = setup();
|
|
157
|
+
await acquireHeld(result);
|
|
158
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
159
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
160
|
+
expect(result.current.holdingLock).toBe(false);
|
|
161
|
+
expect(warn).toHaveBeenCalledWith('[useFileLock] release on pagehide failed:', expect.any(TypeError));
|
|
162
|
+
warn.mockRestore();
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
describe('useFileLock — a hold that is the viewer\'s own', () => {
|
|
167
|
+
it('says the page is open elsewhere and never names the viewer', async () => {
|
|
168
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy(ME, 'Juan') });
|
|
169
|
+
const { result } = setup();
|
|
170
|
+
|
|
171
|
+
let outcome: Awaited<ReturnType<typeof result.current.acquire>> | undefined;
|
|
172
|
+
await act(async () => { outcome = await result.current.acquire(); });
|
|
173
|
+
|
|
174
|
+
expect(outcome).toEqual({ acquired: false, contended: true, error: SELF_HOLD_MESSAGE });
|
|
175
|
+
expect(SELF_HOLD_MESSAGE).toBe(
|
|
176
|
+
'You have this page open for editing somewhere else, in another tab or through your agent. You can edit it here in a moment.',
|
|
177
|
+
);
|
|
178
|
+
expect(result.current.externalLockIsMine).toBe(true);
|
|
179
|
+
expect(result.current.lockError).toBe(SELF_HOLD_MESSAGE);
|
|
180
|
+
expect(result.current.lockError).not.toMatch(/Juan/);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('names someone else as today', async () => {
|
|
184
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy('u-dana', 'Dana') });
|
|
185
|
+
const { result } = setup();
|
|
186
|
+
let outcome: Awaited<ReturnType<typeof result.current.acquire>> | undefined;
|
|
187
|
+
await act(async () => { outcome = await result.current.acquire(); });
|
|
188
|
+
|
|
189
|
+
expect(outcome?.error).toBe('Dana is editing this page');
|
|
190
|
+
expect(result.current.externalLockIsMine).toBe(false);
|
|
191
|
+
expect(result.current.externalLock?.holderName).toBe('Dana');
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
describe('useFileLock — the notice clears when the hold ends', () => {
|
|
196
|
+
it('clears on lock-released, so Edit is available without a reload', async () => {
|
|
197
|
+
const { bus, publish } = makeBus();
|
|
198
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy(ME, 'Juan') });
|
|
199
|
+
const { result } = setup({ bus });
|
|
200
|
+
await act(async () => { await result.current.acquire(); });
|
|
201
|
+
expect(result.current.externalLock).not.toBeNull();
|
|
202
|
+
|
|
203
|
+
await act(async () => {
|
|
204
|
+
publish({ kind: 'lock-released', workspaceId: 'ws', branch: 'main', path: 'kb/Knowledge/Foo.md' } as WorkflowEvent);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
expect(result.current.externalLock).toBeNull();
|
|
208
|
+
expect(result.current.externalLockIsMine).toBe(false);
|
|
209
|
+
expect(result.current.lockError).toBeNull();
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('does not let a lookup answered after an event overwrite what the event said', async () => {
|
|
213
|
+
const { bus, publish } = makeBus();
|
|
214
|
+
let answer: (lock: FileLock | null) => void = () => undefined;
|
|
215
|
+
api.getLock.mockImplementationOnce(() => new Promise<FileLock | null>((resolve) => { answer = resolve; }));
|
|
216
|
+
const { result } = setup({ bus });
|
|
217
|
+
|
|
218
|
+
// Dana takes the page while the mount-time lookup is still out.
|
|
219
|
+
await act(async () => {
|
|
220
|
+
publish({
|
|
221
|
+
kind: 'lock-acquired',
|
|
222
|
+
workspaceId: 'ws',
|
|
223
|
+
branch: 'main',
|
|
224
|
+
path: 'kb/Knowledge/Foo.md',
|
|
225
|
+
holderUserId: 'u-dana',
|
|
226
|
+
holderName: 'Dana',
|
|
227
|
+
} as WorkflowEvent);
|
|
228
|
+
});
|
|
229
|
+
expect(result.current.externalLock?.holderName).toBe('Dana');
|
|
230
|
+
|
|
231
|
+
// The lookup, asked before the event, now answers "nobody": older than
|
|
232
|
+
// the event, so not believed — Edit must not look available while the
|
|
233
|
+
// server refuses the write.
|
|
234
|
+
await act(async () => { answer(null); });
|
|
235
|
+
expect(result.current.externalLock?.holderName).toBe('Dana');
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it('clears at expiry when no release ever arrives (a closed tab whose release was lost)', async () => {
|
|
239
|
+
vi.useFakeTimers();
|
|
240
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy(ME, 'Juan', 20_000) });
|
|
241
|
+
const { result } = setup();
|
|
242
|
+
await act(async () => { await result.current.acquire(); });
|
|
243
|
+
expect(result.current.externalLockIsMine).toBe(true);
|
|
244
|
+
|
|
245
|
+
// Before the expiry nobody asks.
|
|
246
|
+
api.getLock.mockClear();
|
|
247
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });
|
|
248
|
+
expect(api.getLock).not.toHaveBeenCalled();
|
|
249
|
+
expect(result.current.externalLock).not.toBeNull();
|
|
250
|
+
|
|
251
|
+
// Just after it, the server says the page is free.
|
|
252
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(6_500); });
|
|
253
|
+
expect(api.getLock).toHaveBeenCalledTimes(1);
|
|
254
|
+
expect(result.current.externalLock).toBeNull();
|
|
255
|
+
expect(result.current.lockError).toBeNull();
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
it('keeps the notice while the holder renews, and clears once the hold lapses', async () => {
|
|
259
|
+
vi.useFakeTimers();
|
|
260
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy('u-dana', 'Dana', 10_000) });
|
|
261
|
+
const { result } = setup();
|
|
262
|
+
await act(async () => { await result.current.acquire(); });
|
|
263
|
+
|
|
264
|
+
api.getLock.mockClear();
|
|
265
|
+
api.getLock.mockImplementationOnce(async () => lockHeldBy('u-dana', 'Dana', 30_000));
|
|
266
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(11_500); });
|
|
267
|
+
expect(result.current.externalLock?.holderName).toBe('Dana');
|
|
268
|
+
expect(result.current.lockError).toBe('Dana is editing this page');
|
|
269
|
+
|
|
270
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(31_500); });
|
|
271
|
+
expect(api.getLock).toHaveBeenCalledTimes(2);
|
|
272
|
+
expect(result.current.externalLock).toBeNull();
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it('asks again after a network blip rather than giving up', async () => {
|
|
276
|
+
vi.useFakeTimers();
|
|
277
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy(ME, 'Juan', 0) });
|
|
278
|
+
const { result } = setup();
|
|
279
|
+
await act(async () => { await result.current.acquire(); });
|
|
280
|
+
|
|
281
|
+
api.getLock.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
282
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(5_500); });
|
|
283
|
+
expect(result.current.externalLock).not.toBeNull();
|
|
284
|
+
|
|
285
|
+
// The retry waits twice the shortest wait.
|
|
286
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
|
287
|
+
expect(result.current.externalLock).toBeNull();
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it('backs off while the server stays unreachable, rather than asking every few seconds', async () => {
|
|
291
|
+
vi.useFakeTimers();
|
|
292
|
+
api.acquireLock.mockResolvedValueOnce({ acquired: false, lock: lockHeldBy(ME, 'Juan', 0) });
|
|
293
|
+
const { result } = setup();
|
|
294
|
+
await act(async () => { await result.current.acquire(); });
|
|
295
|
+
|
|
296
|
+
api.getLock.mockClear();
|
|
297
|
+
api.getLock.mockImplementation(async () => { throw new TypeError('Failed to fetch'); });
|
|
298
|
+
const askedAfter = async (ms: number) => {
|
|
299
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(ms); });
|
|
300
|
+
return api.getLock.mock.calls.length;
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
expect(await askedAfter(5_100)).toBe(1); // at the expiry
|
|
304
|
+
expect(await askedAfter(9_800)).toBe(1); // not yet 10 s later
|
|
305
|
+
expect(await askedAfter(300)).toBe(2); // 10 s
|
|
306
|
+
expect(await askedAfter(19_800)).toBe(2);
|
|
307
|
+
expect(await askedAfter(300)).toBe(3); // 20 s
|
|
308
|
+
expect(await askedAfter(40_100)).toBe(4); // 40 s
|
|
309
|
+
expect(await askedAfter(64_800)).toBe(4);
|
|
310
|
+
expect(await askedAfter(300)).toBe(5); // then every 65 s at most
|
|
311
|
+
expect(await askedAfter(65_100)).toBe(6);
|
|
312
|
+
expect(result.current.externalLock).not.toBeNull();
|
|
313
|
+
|
|
314
|
+
// Once the server answers again, the notice clears.
|
|
315
|
+
api.getLock.mockImplementation(async () => null);
|
|
316
|
+
expect(await askedAfter(65_100)).toBe(7);
|
|
317
|
+
expect(result.current.externalLock).toBeNull();
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
describe('useFileLock — a live hold of the viewer\'s own is shown on open', () => {
|
|
322
|
+
it('shows the self-hold notice as soon as the page opens, before any Edit', async () => {
|
|
323
|
+
api.getLock.mockImplementation(async () => lockHeldBy(ME, 'Juan'));
|
|
324
|
+
const { result } = setup();
|
|
325
|
+
await act(async () => {});
|
|
326
|
+
|
|
327
|
+
expect(result.current.externalLock?.holderUserId).toBe(ME);
|
|
328
|
+
expect(result.current.externalLockIsMine).toBe(true);
|
|
329
|
+
expect(api.acquireLock).not.toHaveBeenCalled();
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
it('hides it while this tab\'s own release for the page is still in flight', async () => {
|
|
333
|
+
let finishRelease: () => void = () => {};
|
|
334
|
+
api.releaseLock.mockImplementationOnce(() => new Promise<void>((resolve) => { finishRelease = () => resolve(); }));
|
|
335
|
+
const first = setup({ pending: null });
|
|
336
|
+
await acquireHeld(first.result);
|
|
337
|
+
first.unmount();
|
|
338
|
+
expect(api.releaseLock).toHaveBeenCalledTimes(1);
|
|
339
|
+
|
|
340
|
+
// The server has not committed the release yet: it still answers "you".
|
|
341
|
+
api.getLock.mockImplementation(async () => lockHeldBy(ME, 'Juan'));
|
|
342
|
+
const second = setup();
|
|
343
|
+
await act(async () => {});
|
|
344
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
345
|
+
|
|
346
|
+
// The release lands; asked again, the server says the page is free.
|
|
347
|
+
api.getLock.mockImplementation(async () => null);
|
|
348
|
+
await act(async () => { finishRelease(); });
|
|
349
|
+
expect(api.getLock).toHaveBeenCalledTimes(3); // first editor, second editor, the re-ask
|
|
350
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
it('shows the self-hold notice when that release fails and the hold stays', async () => {
|
|
354
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
355
|
+
let failRelease: () => void = () => {};
|
|
356
|
+
api.releaseLock.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
|
357
|
+
failRelease = () => reject(new TypeError('Failed to fetch'));
|
|
358
|
+
}));
|
|
359
|
+
const first = setup({ pending: null });
|
|
360
|
+
await acquireHeld(first.result);
|
|
361
|
+
first.unmount();
|
|
362
|
+
|
|
363
|
+
api.getLock.mockImplementation(async () => lockHeldBy(ME, 'Juan'));
|
|
364
|
+
const second = setup();
|
|
365
|
+
await act(async () => {});
|
|
366
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
367
|
+
|
|
368
|
+
// No lock-released will come; the re-ask finds the hold with nothing in
|
|
369
|
+
// flight and says it is the viewer's own, rather than a page that looks free.
|
|
370
|
+
await act(async () => { failRelease(); });
|
|
371
|
+
expect(second.result.current.externalLockIsMine).toBe(true);
|
|
372
|
+
warn.mockRestore();
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it('keeps asking when that re-ask itself fails, until the hold shows', async () => {
|
|
376
|
+
vi.useFakeTimers();
|
|
377
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
378
|
+
let failRelease: () => void = () => {};
|
|
379
|
+
api.releaseLock.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
|
380
|
+
failRelease = () => reject(new TypeError('Failed to fetch'));
|
|
381
|
+
}));
|
|
382
|
+
const first = setup({ pending: null });
|
|
383
|
+
await acquireHeld(first.result);
|
|
384
|
+
first.unmount();
|
|
385
|
+
|
|
386
|
+
api.getLock.mockImplementation(async () => lockHeldBy(ME, 'Juan'));
|
|
387
|
+
const second = setup();
|
|
388
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
|
|
389
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
390
|
+
|
|
391
|
+
// The release fails, and so do the next two questions to the server.
|
|
392
|
+
api.getLock.mockClear();
|
|
393
|
+
api.getLock
|
|
394
|
+
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
|
395
|
+
.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
396
|
+
await act(async () => { failRelease(); await vi.advanceTimersByTimeAsync(0); });
|
|
397
|
+
expect(api.getLock).toHaveBeenCalledTimes(1);
|
|
398
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
399
|
+
|
|
400
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
|
401
|
+
expect(api.getLock).toHaveBeenCalledTimes(2);
|
|
402
|
+
expect(second.result.current.externalLock).toBeNull();
|
|
403
|
+
|
|
404
|
+
// Third time, 10 s later, the server answers: the hold is still there.
|
|
405
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
|
406
|
+
expect(api.getLock).toHaveBeenCalledTimes(3);
|
|
407
|
+
expect(second.result.current.externalLockIsMine).toBe(true);
|
|
408
|
+
warn.mockRestore();
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
it('stops asking once the editor has gone', async () => {
|
|
412
|
+
vi.useFakeTimers();
|
|
413
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
414
|
+
let failRelease: () => void = () => {};
|
|
415
|
+
api.releaseLock.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
|
416
|
+
failRelease = () => reject(new TypeError('Failed to fetch'));
|
|
417
|
+
}));
|
|
418
|
+
const first = setup({ pending: null });
|
|
419
|
+
await acquireHeld(first.result);
|
|
420
|
+
first.unmount();
|
|
421
|
+
|
|
422
|
+
api.getLock.mockImplementation(async () => lockHeldBy(ME, 'Juan'));
|
|
423
|
+
const second = setup();
|
|
424
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
|
|
425
|
+
|
|
426
|
+
api.getLock.mockClear();
|
|
427
|
+
api.getLock.mockImplementation(async () => { throw new TypeError('Failed to fetch'); });
|
|
428
|
+
await act(async () => { failRelease(); await vi.advanceTimersByTimeAsync(0); });
|
|
429
|
+
expect(api.getLock).toHaveBeenCalledTimes(1);
|
|
430
|
+
second.unmount();
|
|
431
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(200_000); });
|
|
432
|
+
expect(api.getLock).toHaveBeenCalledTimes(1);
|
|
433
|
+
warn.mockRestore();
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it('shows the viewer\'s hold taken in another tab, live', async () => {
|
|
437
|
+
const { bus, publish } = makeBus();
|
|
438
|
+
const { result } = setup({ bus });
|
|
439
|
+
await act(async () => {});
|
|
440
|
+
expect(result.current.externalLock).toBeNull();
|
|
441
|
+
|
|
442
|
+
await act(async () => {
|
|
443
|
+
publish({
|
|
444
|
+
kind: 'lock-acquired', workspaceId: 'ws', branch: 'main', path: 'kb/Knowledge/Foo.md',
|
|
445
|
+
holderUserId: ME, holderName: 'Juan',
|
|
446
|
+
} as WorkflowEvent);
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
expect(result.current.externalLockIsMine).toBe(true);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it('ignores the echo of its own acquire that beats the response', async () => {
|
|
453
|
+
const { bus, publish } = makeBus();
|
|
454
|
+
let finishAcquire: () => void = () => {};
|
|
455
|
+
api.acquireLock.mockImplementationOnce(() => new Promise((resolve) => {
|
|
456
|
+
finishAcquire = () => resolve({ acquired: true, lock: lockHeldBy(ME, 'Juan') });
|
|
457
|
+
}));
|
|
458
|
+
const { result } = setup({ bus });
|
|
459
|
+
await act(async () => {});
|
|
460
|
+
|
|
461
|
+
let acquiring: Promise<unknown> = Promise.resolve();
|
|
462
|
+
act(() => { acquiring = result.current.acquire(); });
|
|
463
|
+
await act(async () => {
|
|
464
|
+
publish({
|
|
465
|
+
kind: 'lock-acquired', workspaceId: 'ws', branch: 'main', path: 'kb/Knowledge/Foo.md',
|
|
466
|
+
holderUserId: ME, holderName: 'Juan',
|
|
467
|
+
} as WorkflowEvent);
|
|
468
|
+
});
|
|
469
|
+
expect(result.current.externalLock).toBeNull();
|
|
470
|
+
|
|
471
|
+
await act(async () => { finishAcquire(); await acquiring; });
|
|
472
|
+
expect(result.current.holdingLock).toBe(true);
|
|
473
|
+
expect(result.current.externalLock).toBeNull();
|
|
474
|
+
});
|
|
475
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import { act, renderHook } from '@testing-library/react';
|
|
3
|
+
import type { FileLock } from '@bevel-software/platform-shared';
|
|
4
|
+
// Nothing of the lock service is mocked here: these tests are about the
|
|
5
|
+
// request a release becomes on the wire, so the hook is driven through
|
|
6
|
+
// workflow's entry point, as other modules use it, down to `fetch`.
|
|
7
|
+
import { useFileLock } from '../..';
|
|
8
|
+
import { setToken } from '../../../../lib/api';
|
|
9
|
+
|
|
10
|
+
const ME = 'u-juan';
|
|
11
|
+
const PATH = 'kb/Knowledge/Foo.md';
|
|
12
|
+
|
|
13
|
+
const fetchMock = vi.fn();
|
|
14
|
+
|
|
15
|
+
function answer(body: unknown): Response {
|
|
16
|
+
return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function heldByMe(): FileLock {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
return {
|
|
22
|
+
branch: 'main',
|
|
23
|
+
path: PATH,
|
|
24
|
+
holderUserId: ME,
|
|
25
|
+
holderName: 'Juan',
|
|
26
|
+
acquiredAt: new Date(now).toISOString(),
|
|
27
|
+
lastHeartbeatAt: new Date(now).toISOString(),
|
|
28
|
+
expiresAt: new Date(now + 60_000).toISOString(),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The calls `fetch` saw with `method`, as `[url, init]`. */
|
|
33
|
+
function requests(method: string): [string, RequestInit][] {
|
|
34
|
+
return (fetchMock.mock.calls as [string, RequestInit | undefined][])
|
|
35
|
+
.filter(([, init]) => (init?.method ?? 'GET') === method)
|
|
36
|
+
.map(([url, init]) => [url, init ?? {}]);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function mount() {
|
|
40
|
+
const persistToDisk = vi.fn(async () => {});
|
|
41
|
+
const hook = renderHook(() =>
|
|
42
|
+
useFileLock({
|
|
43
|
+
workspaceId: 'ws',
|
|
44
|
+
branch: 'main',
|
|
45
|
+
path: PATH,
|
|
46
|
+
currentUserId: ME,
|
|
47
|
+
readPendingContent: () => 'typed since the last autosave',
|
|
48
|
+
persistToDisk,
|
|
49
|
+
}),
|
|
50
|
+
);
|
|
51
|
+
return { ...hook, persistToDisk };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
beforeEach(() => {
|
|
55
|
+
fetchMock.mockReset();
|
|
56
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
57
|
+
localStorage.clear();
|
|
58
|
+
setToken('t0k3n');
|
|
59
|
+
// The server as far as these tests need it: the page is free, an acquire
|
|
60
|
+
// succeeds, a release answers that the commit is queued.
|
|
61
|
+
fetchMock.mockImplementation(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
|
62
|
+
switch (init?.method ?? 'GET') {
|
|
63
|
+
case 'POST':
|
|
64
|
+
return answer({ acquired: true, lock: heldByMe() });
|
|
65
|
+
case 'DELETE':
|
|
66
|
+
return answer({ queued: true });
|
|
67
|
+
default:
|
|
68
|
+
return answer({ lock: null });
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
vi.unstubAllGlobals();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('useFileLock — the release on the wire', () => {
|
|
78
|
+
// A tab closing or reloading sends its release on `pagehide`; only a
|
|
79
|
+
// keep-alive request outlives the page, and it must still carry the
|
|
80
|
+
// bearer header (which `sendBeacon` cannot).
|
|
81
|
+
it('a closing tab sends one keep-alive release with the bearer header, and saves nothing first', async () => {
|
|
82
|
+
const { result, persistToDisk } = mount();
|
|
83
|
+
await act(async () => { await result.current.acquire(); });
|
|
84
|
+
expect(result.current.holdingLock).toBe(true);
|
|
85
|
+
|
|
86
|
+
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
|
|
87
|
+
|
|
88
|
+
const releases = requests('DELETE');
|
|
89
|
+
expect(releases).toHaveLength(1);
|
|
90
|
+
const [url, init] = releases[0]!;
|
|
91
|
+
expect(url).toBe('/api/workspace/ws/workflow/locks');
|
|
92
|
+
expect(init.keepalive).toBe(true);
|
|
93
|
+
expect(new Headers(init.headers).get('Authorization')).toBe('Bearer t0k3n');
|
|
94
|
+
expect(JSON.parse(String(init.body))).toEqual({ branch: 'main', path: PATH });
|
|
95
|
+
expect(persistToDisk).not.toHaveBeenCalled();
|
|
96
|
+
expect(result.current.holdingLock).toBe(false);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('Done sends an ordinary release, and the server\'s queued answer is all it waits for', async () => {
|
|
100
|
+
const { result, persistToDisk } = mount();
|
|
101
|
+
await act(async () => { await result.current.acquire(); });
|
|
102
|
+
|
|
103
|
+
await act(async () => {
|
|
104
|
+
await expect(result.current.saveAndRelease()).resolves.toBeUndefined();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
expect(persistToDisk).toHaveBeenCalledTimes(1);
|
|
108
|
+
const releases = requests('DELETE');
|
|
109
|
+
expect(releases).toHaveLength(1);
|
|
110
|
+
const [, init] = releases[0]!;
|
|
111
|
+
expect(init.keepalive).toBeUndefined();
|
|
112
|
+
expect(JSON.parse(String(init.body))).toEqual({ branch: 'main', path: PATH });
|
|
113
|
+
expect(result.current.holdingLock).toBe(false);
|
|
114
|
+
});
|
|
115
|
+
});
|