@bevel-software/platform-core-frontend 0.21.0 → 0.23.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 (72) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +140 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  6. package/src/modules/access/api.ts +6 -4
  7. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  8. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  9. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  10. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  11. package/src/modules/access/requests.api.ts +121 -0
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  13. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  14. package/src/modules/auth/components/LoginScreen.tsx +8 -0
  15. package/src/modules/auth/services/account.api.ts +26 -3
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  19. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  20. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  21. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  22. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  23. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  24. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  25. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  26. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  27. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  28. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  29. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  30. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  31. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  32. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  33. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  34. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  35. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  36. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  37. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  38. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  39. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  40. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  41. package/src/modules/setup/__tests__/setup.repository.test.tsx +463 -0
  42. package/src/modules/setup/__tests__/setup.test.tsx +13 -17
  43. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  44. package/src/modules/setup/components/SetupGate.tsx +1 -0
  45. package/src/modules/setup/components/SetupScreen.tsx +608 -41
  46. package/src/modules/setup/services/setup.api.ts +171 -3
  47. package/src/modules/setup/utils/kept-draft.ts +86 -0
  48. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  49. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  50. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  51. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  52. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  53. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  54. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  55. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  56. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  57. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  58. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  59. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  60. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  61. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  62. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  63. package/src/modules/workspace/components/renderers/index.ts +6 -1
  64. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  65. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  66. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  67. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  68. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  69. package/src/modules/workspace/services/workspace.api.ts +22 -1
  70. package/src/shared/components/SlotBoundary.tsx +51 -0
  71. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  72. package/src/shared/markdown/hrefs.ts +80 -4
@@ -0,0 +1,479 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, waitFor, fireEvent } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import type {
5
+ BranchInfo,
6
+ CommitAttribution,
7
+ WorkingTreeStatus,
8
+ } from '@bevel-software/platform-shared';
9
+
10
+ /**
11
+ * A past save shown with the FILE PAGE's viewer.
12
+ *
13
+ * Every assertion here is about the BINDING: the viewer that mounts is the one
14
+ * the file page uses for that extension, and the bytes it reads are the ones
15
+ * of the selected save (`?ref=<sha>`, and `&side=before` where the save
16
+ * deleted the file) rather than the working tree's. Before this, a PNG's or a
17
+ * PDF's history showed git's one-line "Binary files differ".
18
+ */
19
+
20
+ /** The bytes every viewer here fetches go through `authFetch`. */
21
+ const apiMock = vi.hoisted(() => ({ authFetch: vi.fn() }));
22
+ vi.mock('../../../lib/api', () => ({ authFetch: apiMock.authFetch }));
23
+
24
+ /** `rawFileUrl` stays REAL, so the URLs asserted below are the served ones. */
25
+ const accessMock = vi.hoisted(() => ({ fetchFileAccess: vi.fn() }));
26
+ vi.mock('../../access/api', async (importOriginal) => ({
27
+ ...(await importOriginal<object>()),
28
+ fetchFileAccess: accessMock.fetchFileAccess,
29
+ }));
30
+
31
+ /**
32
+ * pdf.js needs a worker thread and a real 2D canvas context, neither of which
33
+ * happy-dom has — mocked at the module boundary exactly as `PdfRenderer`'s own
34
+ * test does, so what is under test stays this pane's wiring.
35
+ */
36
+ const pdfjsMock = vi.hoisted(() => {
37
+ const page = {
38
+ getViewport: vi.fn(({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale })),
39
+ render: vi.fn(() => ({ promise: Promise.resolve(), cancel: vi.fn() })),
40
+ cleanup: vi.fn(),
41
+ };
42
+ const doc = { numPages: 3, getPage: vi.fn(async () => page), destroy: vi.fn(async () => {}) };
43
+ return {
44
+ getDocument: vi.fn(() => ({ promise: Promise.resolve(doc), destroy: vi.fn(async () => {}) })),
45
+ };
46
+ });
47
+ vi.mock('pdfjs-dist', () => ({ GlobalWorkerOptions: {}, getDocument: pdfjsMock.getDocument }));
48
+
49
+ const mammothMock = vi.hoisted(() => ({
50
+ convertToHtml: vi.fn(async () => ({ value: '<p>The memo as it was</p>' })),
51
+ }));
52
+ vi.mock('mammoth/mammoth.browser.js', () => ({ default: mammothMock }));
53
+
54
+ import { HistoryVersionPreview } from '../components/HistoryVersionPreview';
55
+ import { GitContext, type GitContextValue } from '../state/git.context';
56
+ import {
57
+ WorkspaceContext,
58
+ type WorkspaceContextValue,
59
+ } from '../../workspace/state/workspace.context';
60
+
61
+ const KB = 'knowledge-base';
62
+ const WS = 'target-company-state';
63
+ const SHA = '1111111111111111111111111111111111111111';
64
+
65
+ function makeCommit(partial: Partial<CommitAttribution> = {}): CommitAttribution {
66
+ return {
67
+ sha: SHA,
68
+ authorName: 'Alice',
69
+ authorEmail: 'alice@example.com',
70
+ subject: 'replace the logo',
71
+ committedAt: '2026-04-17T10:00:00Z',
72
+ ...partial,
73
+ };
74
+ }
75
+
76
+ function makeGit(overrides: Partial<GitContextValue> = {}): GitContextValue {
77
+ const status: WorkingTreeStatus = {
78
+ // A PROTECTED branch, so `useFileAccess` really resolves `download:`
79
+ // instead of short-circuiting the way it does on a draft.
80
+ branch: WS,
81
+ hasUpstream: true,
82
+ unmergedFromUpstream: false,
83
+ };
84
+ const branches: BranchInfo[] = [];
85
+ return {
86
+ status,
87
+ branches,
88
+ availability: 'ready',
89
+ lastError: null,
90
+ refreshStatus: async () => null,
91
+ refreshBranches: async () => {},
92
+ createBranch: async () => {},
93
+ pull: async () => {},
94
+ deleteBranch: async () => {},
95
+ fetchForkBase: async () => null,
96
+ fetchFileHistory: async () => [],
97
+ fetchFileDiff: async () => '',
98
+ fetchFileAtChange: async () => ({ baseline: null, current: null }),
99
+ fetchFileComparison: async () => '',
100
+ ...overrides,
101
+ };
102
+ }
103
+
104
+ const workspace = { workspaceId: WS, kbDirName: KB } as unknown as WorkspaceContextValue;
105
+
106
+ /** `repoPath` is repo-relative; the pane takes the workspace-relative form. */
107
+ function renderPane(
108
+ repoPath: string,
109
+ git: GitContextValue,
110
+ commit: CommitAttribution = makeCommit(),
111
+ ) {
112
+ return render(
113
+ <MemoryRouter initialEntries={[`/workspace/${WS}/${KB}/${repoPath}`]}>
114
+ <WorkspaceContext.Provider value={workspace}>
115
+ <GitContext.Provider value={git}>
116
+ <HistoryVersionPreview filePath={`${KB}/${repoPath}`} commit={commit} />
117
+ </GitContext.Provider>
118
+ </WorkspaceContext.Provider>
119
+ </MemoryRouter>,
120
+ );
121
+ }
122
+
123
+ /** Every raw-file fetch the viewers (and the download) made, in order. */
124
+ const rawUrls = () => apiMock.authFetch.mock.calls.map((c) => String(c[0]));
125
+ const refUrl = (path: string, extra = '') =>
126
+ `/api/workspace/${WS}/file/raw?path=${encodeURIComponent(`${KB}/${path}`)}${extra}&ref=${SHA}`;
127
+
128
+ /** A patch shaped like the one `git show --format=` produces for a binary. */
129
+ const binaryPatch = (name: string) =>
130
+ `diff --git a/${name} b/${name}\nindex 1111111..2222222 100644\nBinary files a/${name} and b/${name} differ\n`;
131
+ const deletedBinaryPatch = (name: string) =>
132
+ `diff --git a/${name} b/${name}\ndeleted file mode 100644\nindex 1111111..0000000\nBinary files a/${name} and /dev/null differ\n`;
133
+
134
+ beforeEach(() => {
135
+ apiMock.authFetch.mockReset();
136
+ apiMock.authFetch.mockResolvedValue({
137
+ ok: true,
138
+ status: 200,
139
+ blob: async () => new Blob(['bytes']),
140
+ arrayBuffer: async () => new ArrayBuffer(8),
141
+ text: async () => '',
142
+ });
143
+ accessMock.fetchFileAccess.mockReset();
144
+ accessMock.fetchFileAccess.mockResolvedValue({
145
+ canWrite: false,
146
+ canDownload: true,
147
+ eligible: { roles: [], users: [] },
148
+ owners: { roles: [], users: [] },
149
+ });
150
+ mammothMock.convertToHtml.mockClear();
151
+ (globalThis.URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(
152
+ () => 'blob:fake-url',
153
+ );
154
+ (globalThis.URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn();
155
+ });
156
+
157
+ describe('HistoryVersionPreview — the viewer is bound to the selected save', () => {
158
+ it('heads the pane with the save\'s time and author', async () => {
159
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') }));
160
+ expect(await screen.findByText(/As saved .* by Alice/)).toBeInTheDocument();
161
+ });
162
+
163
+ it('shows a PDF save in the PDF viewer, reading that save\'s bytes', async () => {
164
+ renderPane(
165
+ 'Docs/Q3-report.pdf',
166
+ makeGit({ fetchFileDiff: async () => binaryPatch('Docs/Q3-report.pdf') }),
167
+ );
168
+ // The viewer itself, not a sentence about binary files.
169
+ expect(await screen.findByText('Page 1 of 3')).toBeInTheDocument();
170
+ expect(screen.queryByText(/Binary files/)).not.toBeInTheDocument();
171
+ await waitFor(() => expect(rawUrls()).toContain(refUrl('Docs/Q3-report.pdf')));
172
+ });
173
+
174
+ it('shows a PNG save as the picture it was', async () => {
175
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') }));
176
+ const img = await screen.findByRole('img', { name: `${KB}/Docs/logo.png` });
177
+ expect(img).toHaveAttribute('src', 'blob:fake-url');
178
+ await waitFor(() => expect(rawUrls()).toContain(refUrl('Docs/logo.png')));
179
+ // No `&v=`: a version's bytes cannot change, so the image revision — which
180
+ // bumps on every save of the file — must not key the read.
181
+ expect(rawUrls().some((u) => u.includes('&v='))).toBe(false);
182
+ });
183
+
184
+ it('shows a DOCX save through the Word viewer', async () => {
185
+ renderPane('Docs/memo.docx', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/memo.docx') }));
186
+ expect(await screen.findByText('The memo as it was')).toBeInTheDocument();
187
+ await waitFor(() => expect(rawUrls()).toContain(refUrl('Docs/memo.docx')));
188
+ });
189
+
190
+ it('renders an HTML save from that save\'s own text, and toggles to the line changes', async () => {
191
+ const patch = '--- a\n+++ b\n@@ -1 +1 @@\n-<p>old</p>\n+<p>new</p>\n';
192
+ renderPane(
193
+ 'Pages/landing.html',
194
+ makeGit({
195
+ fetchFileDiff: async () => patch,
196
+ fetchFileAtChange: async () => ({
197
+ baseline: '<p>old</p>',
198
+ current: '<h1>The page as it was</h1>',
199
+ }),
200
+ }),
201
+ );
202
+
203
+ // The sandboxed preview, built from the save's text — not the patch.
204
+ const frame = await waitFor(() => {
205
+ const el = document.querySelector('iframe');
206
+ expect(el).not.toBeNull();
207
+ return el as HTMLIFrameElement;
208
+ });
209
+ expect(frame.getAttribute('srcdoc')).toContain('The page as it was');
210
+ expect(screen.queryByText(/\+<p>new<\/p>/)).toBeNull();
211
+
212
+ fireEvent.click(screen.getByRole('button', { name: 'Source changes' }));
213
+ expect(await screen.findByText(/\+<p>new<\/p>/)).toBeInTheDocument();
214
+ expect(document.querySelector('iframe')).toBeNull();
215
+
216
+ fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
217
+ await waitFor(() => expect(document.querySelector('iframe')).not.toBeNull());
218
+ });
219
+
220
+ it('offers the source toggle for svg and csv, and NOT for a pdf or an image', async () => {
221
+ const { unmount } = renderPane(
222
+ 'Docs/chart.svg',
223
+ makeGit({ fetchFileDiff: async () => '--- a\n+++ b\n@@ -1 +1 @@\n-<svg/>\n+<svg />\n' }),
224
+ );
225
+ expect(await screen.findByRole('button', { name: 'Source changes' })).toBeInTheDocument();
226
+ unmount();
227
+
228
+ renderPane('Docs/Q3.pdf', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/Q3.pdf') }));
229
+ await screen.findByText('Page 1 of 3');
230
+ expect(screen.queryByRole('button', { name: 'Source changes' })).toBeNull();
231
+ });
232
+
233
+ it('shows the note and the version just before the save that deleted the file', async () => {
234
+ renderPane(
235
+ 'Docs/old-logo.png',
236
+ makeGit({ fetchFileDiff: async () => deletedBinaryPatch('Docs/old-logo.png') }),
237
+ );
238
+ expect(await screen.findByText('This save deleted the file.')).toBeInTheDocument();
239
+ // …and the image below it, read from the side BEFORE the save.
240
+ await waitFor(() =>
241
+ expect(rawUrls()).toContain(`${refUrl('Docs/old-logo.png')}&side=before`),
242
+ );
243
+ expect(await screen.findByRole('img', { name: `${KB}/Docs/old-logo.png` })).toBeInTheDocument();
244
+ // EVERY read of this file is that one: no viewer is mounted while the pane
245
+ // still has to learn the save deleted the file, so there is no first read
246
+ // of the after side to throw away and no re-mount when the side settles.
247
+ // Pinned rather than argued, because the `side` the pane starts with is
248
+ // provisional by design — see the comment on it — and what makes that safe
249
+ // is precisely that nothing reads it.
250
+ const reads = rawUrls().filter((u) => u.includes(encodeURIComponent('Docs/old-logo.png')));
251
+ expect(reads.length).toBeGreaterThan(0);
252
+ for (const url of reads) {
253
+ expect(url).toContain(`&ref=${SHA}&side=before`);
254
+ }
255
+ });
256
+
257
+ it('names the formats no viewer renders, and still offers the bytes', async () => {
258
+ renderPane(
259
+ 'Docs/archive.zip',
260
+ makeGit({ fetchFileDiff: async () => binaryPatch('Docs/archive.zip') }),
261
+ );
262
+ expect(await screen.findByText('No preview for this format.')).toBeInTheDocument();
263
+ const download = screen.getByRole('button', { name: 'Download this version' });
264
+ fireEvent.click(download);
265
+ await waitFor(() =>
266
+ expect(rawUrls()).toContain(
267
+ `/api/workspace/${WS}/file/raw?path=${encodeURIComponent(`${KB}/Docs/archive.zip`)}&download=1&ref=${SHA}`,
268
+ ),
269
+ );
270
+ });
271
+
272
+ it('names an unknown binary the same way, on git\'s own word for it', async () => {
273
+ // `.bin` is in no list the app keeps; the patch saying "Binary files …
274
+ // differ" is what makes "and any other binary" true.
275
+ renderPane(
276
+ 'Docs/blob.bin',
277
+ makeGit({ fetchFileDiff: async () => binaryPatch('Docs/blob.bin') }),
278
+ );
279
+ expect(await screen.findByText('No preview for this format.')).toBeInTheDocument();
280
+ });
281
+
282
+ it('keeps the line changes for a text format with no viewer', async () => {
283
+ renderPane(
284
+ 'Docs/notes.txt',
285
+ makeGit({ fetchFileDiff: async () => '--- a\n+++ b\n@@ -1 +1 @@\n-foo\n+bar\n' }),
286
+ );
287
+ expect(await screen.findByText(/\+bar/)).toBeInTheDocument();
288
+ expect(screen.queryByText('No preview for this format.')).toBeNull();
289
+ });
290
+
291
+ it('downloads the save\'s bytes, not today\'s', async () => {
292
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') }));
293
+ fireEvent.click(await screen.findByRole('button', { name: 'Download this version' }));
294
+ await waitFor(() =>
295
+ expect(rawUrls()).toContain(
296
+ `/api/workspace/${WS}/file/raw?path=${encodeURIComponent(`${KB}/Docs/logo.png`)}&download=1&ref=${SHA}`,
297
+ ),
298
+ );
299
+ });
300
+
301
+ it('disables the download for a reader without download permission, and says why', async () => {
302
+ accessMock.fetchFileAccess.mockResolvedValue({
303
+ canWrite: false,
304
+ canDownload: false,
305
+ eligible: { roles: [], users: [] },
306
+ owners: { roles: [], users: [] },
307
+ });
308
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') }));
309
+ const button = await screen.findByRole('button', { name: 'Download this version' });
310
+ await waitFor(() => expect(button).toBeDisabled());
311
+ expect(button).toHaveAttribute(
312
+ 'title',
313
+ 'You do not have download permission for this file.',
314
+ );
315
+ });
316
+
317
+ it('holds the download idle until it knows which side of the save to read', async () => {
318
+ // Until the patch comes back the pane does not know whether this save
319
+ // DELETED the file, so it does not know whether "this version" is the side
320
+ // after it or the side before it. A click in that window would ask for the
321
+ // after side of a deleting save and get a 404 for a version the reader can
322
+ // see listed.
323
+ let answer: (patch: string) => void = () => {};
324
+ const patch = new Promise<string>((resolve) => {
325
+ answer = resolve;
326
+ });
327
+ renderPane('Docs/old-logo.png', makeGit({ fetchFileDiff: () => patch }));
328
+
329
+ const button = await screen.findByRole('button', { name: 'Download this version' });
330
+ expect(button).toBeDisabled();
331
+ fireEvent.click(button);
332
+ expect(rawUrls().some((u) => u.includes('download=1'))).toBe(false);
333
+
334
+ answer(deletedBinaryPatch('Docs/old-logo.png'));
335
+ await waitFor(() => expect(button).toBeEnabled());
336
+ fireEvent.click(button);
337
+ // …and now it reads the side BEFORE the save, which is the only one with
338
+ // any bytes at all.
339
+ await waitFor(() =>
340
+ expect(rawUrls()).toContain(
341
+ `/api/workspace/${WS}/file/raw?path=${encodeURIComponent(
342
+ `${KB}/Docs/old-logo.png`,
343
+ )}&download=1&ref=${SHA}&side=before`,
344
+ ),
345
+ );
346
+ });
347
+
348
+ it('keeps the empty state for a save that did not touch the file', async () => {
349
+ // A save the file's log lists but whose patch is empty for this path (a
350
+ // pure rename elsewhere in the commit): there is no version to show, and a
351
+ // viewer bound to a ref with nothing at it would answer with a read error.
352
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => '' }));
353
+ expect(await screen.findByText('No file changes in this save.')).toBeInTheDocument();
354
+ expect(screen.queryByRole('img')).toBeNull();
355
+ expect(screen.queryByText('No preview for this format.')).toBeNull();
356
+ // …and no download either: there is no version of this file at that save
357
+ // to hand over, so the button would only ever answer with a 404.
358
+ expect(screen.queryByRole('button', { name: 'Download this version' })).toBeNull();
359
+ // The header still says WHICH save is selected.
360
+ expect(screen.getByText(/As saved .* by Alice/)).toBeInTheDocument();
361
+ });
362
+
363
+ it('hands focus to the pane when a viewer\'s own Try again unmounts it', async () => {
364
+ // Pressing "Try again" removes the button from the DOM, so focus would
365
+ // fall to document.body and the next Tab would restart at the top of the
366
+ // page. The viewport the viewer sits in is what survives the swap.
367
+ apiMock.authFetch.mockRejectedValueOnce(new Error('network down'));
368
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') }));
369
+
370
+ const retry = await screen.findByRole('button', { name: 'Try again' });
371
+ const pane = screen.getByTestId('history-preview-viewport');
372
+ fireEvent.click(retry);
373
+ expect(document.activeElement).toBe(pane);
374
+ expect(await screen.findByRole('img', { name: `${KB}/Docs/logo.png` })).toBeInTheDocument();
375
+ });
376
+
377
+ it('shows the refusal, with Try again, when the version cannot be loaded — never a blank pane', async () => {
378
+ const fetchFileDiff = vi
379
+ .fn()
380
+ .mockRejectedValueOnce(new Error("This version is not in this file's history on this branch."))
381
+ .mockResolvedValue(binaryPatch('Docs/logo.png'));
382
+ renderPane('Docs/logo.png', makeGit({ fetchFileDiff }));
383
+
384
+ expect(
385
+ await screen.findByText("This version is not in this file's history on this branch."),
386
+ ).toBeInTheDocument();
387
+ // The header stays: the pane always says which save it is about.
388
+ expect(screen.getByText(/As saved .* by Alice/)).toBeInTheDocument();
389
+
390
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
391
+ expect(await screen.findByRole('img', { name: `${KB}/Docs/logo.png` })).toBeInTheDocument();
392
+ expect(fetchFileDiff).toHaveBeenCalledTimes(2);
393
+ });
394
+
395
+ it('gives a reader who may not read the file the refusal the panel already gave', async () => {
396
+ // The refusal is the BACKEND's: `show-file` 403s a path the caller cannot
397
+ // read, and `friendlyGitError` passes that sentence through. The pane says
398
+ // the same thing the history panel has always said for the same file — and
399
+ // the bytes route refuses too, so nothing renders behind it.
400
+ const denial = 'You don\'t have permission to read "knowledge-base/Docs/logo.png".';
401
+ renderPane(
402
+ 'Docs/logo.png',
403
+ makeGit({
404
+ fetchFileDiff: async () => {
405
+ throw new Error(denial);
406
+ },
407
+ }),
408
+ );
409
+ expect(await screen.findByText(denial)).toBeInTheDocument();
410
+ expect(screen.queryByRole('img')).toBeNull();
411
+ });
412
+
413
+ it('keeps the version on screen when the panel re-renders around it', async () => {
414
+ // A save landing on the file re-renders the panel (the list gains a row)
415
+ // and hands this pane a fresh git object. The viewer must not re-read: the
416
+ // bytes of a commit cannot have changed, and a re-read would blink the
417
+ // document back to its loading state.
418
+ const pngGit = () => makeGit({ fetchFileDiff: async () => binaryPatch('Docs/logo.png') });
419
+ const commit = makeCommit();
420
+ const { rerender } = renderPane('Docs/logo.png', pngGit(), commit);
421
+ await screen.findByRole('img', { name: `${KB}/Docs/logo.png` });
422
+ const readsBefore = rawUrls().length;
423
+
424
+ // A WHOLE new git value, fresh method identities and all — which is what
425
+ // the panel really hands over. Spreading the old one would keep every
426
+ // function reference, so the pane's own load effect would not even re-run
427
+ // and the assertion below would hold with no memoization at all.
428
+ rerender(
429
+ <MemoryRouter initialEntries={[`/workspace/${WS}/Docs/logo.png`]}>
430
+ <WorkspaceContext.Provider value={workspace}>
431
+ <GitContext.Provider value={pngGit()}>
432
+ <HistoryVersionPreview filePath={`${KB}/Docs/logo.png`} commit={commit} />
433
+ </GitContext.Provider>
434
+ </WorkspaceContext.Provider>
435
+ </MemoryRouter>,
436
+ );
437
+ expect(await screen.findByRole('img', { name: `${KB}/Docs/logo.png` })).toBeInTheDocument();
438
+ expect(rawUrls().length).toBe(readsBefore);
439
+ });
440
+ });
441
+
442
+ /**
443
+ * The document parsers are code-split (`renderers/index.ts`: pdf.js ~340 KB,
444
+ * xlsx ~141 KB, mammoth ~119 KB). Version history reaches them through the
445
+ * same registry the file page uses, so it must reach them the same way — by
446
+ * the lazy wrapper, never by a static import that would drag the parser into
447
+ * whatever chunk the history panel lands in.
448
+ */
449
+ describe('the viewers stay lazily loaded', () => {
450
+ /** Read from the package root, which is vitest's working directory. */
451
+ async function sourceOf(file: string): Promise<string> {
452
+ const { readFileSync } = await import('node:fs');
453
+ return readFileSync(`src/modules/git/${file}`, 'utf8');
454
+ }
455
+
456
+ it.each([
457
+ 'components/HistoryVersionPreview.tsx',
458
+ 'components/FileHistoryPanel.tsx',
459
+ ])('%s imports no parser and no heavy viewer directly', async (file) => {
460
+ const src = await sourceOf(file);
461
+ for (const forbidden of [
462
+ 'pdfjs-dist',
463
+ 'mammoth',
464
+ 'xlsx',
465
+ '/PdfRenderer',
466
+ '/DocxRenderer',
467
+ '/XlsxRenderer',
468
+ '/PptxRenderer',
469
+ '/EmailRenderer',
470
+ ]) {
471
+ expect(src).not.toContain(`from '${forbidden}`);
472
+ expect(src).not.toContain(`import('${forbidden}`);
473
+ }
474
+ });
475
+
476
+ it('reaches a viewer through the registry, which is where the laziness lives', async () => {
477
+ expect(await sourceOf('components/HistoryVersionPreview.tsx')).toContain('getFileRenderer');
478
+ });
479
+ });
@@ -3,8 +3,8 @@ import { History, AlertTriangle, Loader2 } from 'lucide-react';
3
3
  import type { CommitAttribution, FileDiffPayload } from '@bevel-software/platform-shared';
4
4
  import { useGit } from '../state/git.context';
5
5
  import { formatRelativeTime } from '../../../lib/utils';
6
- import { UnifiedDiffView } from './UnifiedDiffView';
7
6
  import { MarkdownDiffViewer } from '../../review/components/MarkdownDiffViewer';
7
+ import { HistoryVersionPreview } from './HistoryVersionPreview';
8
8
  import { friendlyGitError } from '../services/error-messages';
9
9
  import { useEventBus, canonicalizeWorkspaceId } from '../../workflow/state/event-bus.context';
10
10
  import { useWorkspace } from '../../workspace/state/workspace.context';
@@ -32,7 +32,6 @@ export function FileHistoryPanel({ filePath }: Props) {
32
32
  const git = useGit();
33
33
  const [commits, setCommits] = useState<CommitAttribution[] | null>(null);
34
34
  const [selected, setSelected] = useState<CommitAttribution | null>(null);
35
- const [diff, setDiff] = useState<string | null>(null);
36
35
  // Markdown files render through the same viewer as "Review agent changes":
37
36
  // full before/after contents diffed client-side into a rendered-markdown
38
37
  // red/green view. `diff` (the raw patch) stays the path for everything else.
@@ -45,14 +44,13 @@ export function FileHistoryPanel({ filePath }: Props) {
45
44
  // Pull the stable callbacks out so the effect's deps don't include the whole
46
45
  // `git` object — that object is a useMemo result that changes on every status
47
46
  // poll, which would otherwise wipe local state (selection, loading) every 30s.
48
- const { fetchFileHistory, fetchFileDiff, fetchFileAtChange } = git;
47
+ const { fetchFileHistory, fetchFileAtChange } = git;
49
48
 
50
49
  useEffect(() => {
51
50
  let cancelled = false;
52
51
  setLoading(true);
53
52
  setError(null);
54
53
  setSelected(null);
55
- setDiff(null);
56
54
  setMdPayload(null);
57
55
  setCommits(null);
58
56
  latestDiffRequestRef.current = null;
@@ -115,35 +113,24 @@ export function FileHistoryPanel({ filePath }: Props) {
115
113
  // Clear any banner left over from a previous failed diff so the UI
116
114
  // reflects only the currently-selected save's state.
117
115
  setError(null);
118
- setDiff(null);
119
116
  setMdPayload(null);
120
- setDiffLoading(true);
121
117
  latestDiffRequestRef.current = commit.sha;
122
- if (isMarkdownPath(filePath)) {
123
- fetchFileAtChange(filePath, commit.sha)
124
- .then(({ baseline, current }) => {
125
- if (latestDiffRequestRef.current !== commit.sha) return;
126
- setMdPayload({
127
- path: filePath,
128
- kind: baseline === null ? 'added' : current === null ? 'deleted' : 'modified',
129
- baseline,
130
- current,
131
- isBinary: false,
132
- });
133
- })
134
- .catch((err) => {
135
- if (latestDiffRequestRef.current === commit.sha) {
136
- setError(friendlyGitError(err));
137
- }
138
- })
139
- .finally(() => {
140
- if (latestDiffRequestRef.current === commit.sha) setDiffLoading(false);
118
+ // Everything that is NOT markdown is loaded by `HistoryVersionPreview`,
119
+ // which needs the save and nothing else: it fetches the patch (and, for
120
+ // a text-fed viewer, the save's text) for itself, keyed on the sha.
121
+ // Only the markdown path still loads here, unchanged.
122
+ if (!isMarkdownPath(filePath)) return;
123
+ setDiffLoading(true);
124
+ fetchFileAtChange(filePath, commit.sha)
125
+ .then(({ baseline, current }) => {
126
+ if (latestDiffRequestRef.current !== commit.sha) return;
127
+ setMdPayload({
128
+ path: filePath,
129
+ kind: baseline === null ? 'added' : current === null ? 'deleted' : 'modified',
130
+ baseline,
131
+ current,
132
+ isBinary: false,
141
133
  });
142
- return;
143
- }
144
- fetchFileDiff(filePath, commit.sha)
145
- .then((d) => {
146
- if (latestDiffRequestRef.current === commit.sha) setDiff(d);
147
134
  })
148
135
  .catch((err) => {
149
136
  if (latestDiffRequestRef.current === commit.sha) {
@@ -154,7 +141,7 @@ export function FileHistoryPanel({ filePath }: Props) {
154
141
  if (latestDiffRequestRef.current === commit.sha) setDiffLoading(false);
155
142
  });
156
143
  },
157
- [filePath, fetchFileDiff, fetchFileAtChange],
144
+ [filePath, fetchFileAtChange],
158
145
  );
159
146
 
160
147
  return (
@@ -245,41 +232,41 @@ export function FileHistoryPanel({ filePath }: Props) {
245
232
  {shortSha(selected.sha)}
246
233
  </span>
247
234
  </div>
248
- <div className="flex-1 overflow-auto">
249
- {diffLoading && (
250
- <div className="flex items-center gap-2 px-3 py-3 text-xs text-ink-muted">
251
- <Loader2 size={13} className="animate-spin" />
252
- Loading changes…
253
- </div>
254
- )}
255
- {!diffLoading && mdPayload !== null && (
256
- mdPayload.baseline === null && mdPayload.current === null ? (
257
- // The commit exists in the file's log but the file is
258
- // absent on both sides (e.g. a pure rename elsewhere in
259
- // the commit) — mirror the raw view's empty state.
260
- <div className="px-3 py-3 text-xs text-ink-muted">
261
- No file changes in this save.
235
+ {/* Markdown keeps the rendered before/after diff it has
236
+ always had; every other format is the version pane. */}
237
+ {isMarkdownPath(filePath) ? (
238
+ <div className="flex-1 overflow-auto">
239
+ {diffLoading && (
240
+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-ink-muted">
241
+ <Loader2 size={13} className="animate-spin" />
242
+ Loading changes…
262
243
  </div>
263
- ) : (
264
- // No link resolvers: this is a diff of a PAST commit, and a
265
- // relative link in it has no meaningful "current" document
266
- // to resolve against — the target may have moved or stopped
267
- // existing since. Links render inert.
268
- //
269
- // No image resolver either: the checked-out tree holds
270
- // today's copy of a picture, not the one this commit had,
271
- // so the viewer names each workspace image instead of
272
- // fetching bytes that may not match (`?ref=` in TODOS.md).
273
- <MarkdownDiffViewer payload={mdPayload} />
274
- )
275
- )}
276
- {!diffLoading && diff !== null && (
277
- <UnifiedDiffView
278
- diff={diff}
279
- emptyMessage="No file changes in this save."
280
- />
281
- )}
282
- </div>
244
+ )}
245
+ {!diffLoading && mdPayload !== null && (
246
+ mdPayload.baseline === null && mdPayload.current === null ? (
247
+ // The commit exists in the file's log but the file is
248
+ // absent on both sides (e.g. a pure rename elsewhere in
249
+ // the commit) — mirror the raw view's empty state.
250
+ <div className="px-3 py-3 text-xs text-ink-muted">
251
+ No file changes in this save.
252
+ </div>
253
+ ) : (
254
+ // No link resolvers: this is a diff of a PAST commit, and a
255
+ // relative link in it has no meaningful "current" document
256
+ // to resolve against — the target may have moved or stopped
257
+ // existing since. Links render inert.
258
+ //
259
+ // No image resolver either: the checked-out tree holds
260
+ // today's copy of a picture, not the one this commit had,
261
+ // so the viewer names each workspace image instead of
262
+ // fetching bytes that may not match (`?ref=` in TODOS.md).
263
+ <MarkdownDiffViewer payload={mdPayload} />
264
+ )
265
+ )}
266
+ </div>
267
+ ) : (
268
+ <HistoryVersionPreview filePath={filePath} commit={selected} />
269
+ )}
283
270
  </>
284
271
  )}
285
272
  </div>