@bevel-software/platform-core-frontend 0.22.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 (45) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +83 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/api.ts +6 -4
  6. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  7. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  8. package/src/modules/auth/components/LoginScreen.tsx +3 -0
  9. package/src/modules/auth/services/account.api.ts +26 -3
  10. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  11. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  12. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  13. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  14. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  15. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  16. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  17. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  18. package/src/modules/setup/__tests__/setup.repository.test.tsx +114 -24
  19. package/src/modules/setup/__tests__/setup.test.tsx +5 -3
  20. package/src/modules/setup/components/SetupScreen.tsx +187 -46
  21. package/src/modules/setup/services/setup.api.ts +78 -3
  22. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  23. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  24. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  25. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  26. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  27. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  28. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  29. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  30. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  31. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  32. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  33. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  34. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  35. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  36. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  37. package/src/modules/workspace/components/renderers/index.ts +6 -1
  38. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  39. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  40. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  41. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  42. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  43. package/src/modules/workspace/services/workspace.api.ts +22 -1
  44. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  45. package/src/shared/markdown/hrefs.ts +80 -4
@@ -1,7 +1,22 @@
1
- import { describe, it, expect, vi } from 'vitest';
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { render, screen, waitFor, fireEvent } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
3
4
  import type { BranchInfo, CommitAttribution, WorkingTreeStatus } from '@bevel-software/platform-shared';
4
5
 
6
+ /**
7
+ * The version pane the panel now mounts for every non-markdown file reads
8
+ * bytes and resolves the file's `download:` verb. Both are stubbed so these
9
+ * tests stay about the PANEL — which save is selected, and which of the two
10
+ * histories it routes to.
11
+ */
12
+ const apiMock = vi.hoisted(() => ({ authFetch: vi.fn() }));
13
+ vi.mock('../../../lib/api', () => ({ authFetch: apiMock.authFetch }));
14
+ const accessMock = vi.hoisted(() => ({ fetchFileAccess: vi.fn() }));
15
+ vi.mock('../../access/api', async (importOriginal) => ({
16
+ ...(await importOriginal<object>()),
17
+ fetchFileAccess: accessMock.fetchFileAccess,
18
+ }));
19
+
5
20
  import { FileHistoryPanel } from '../components/FileHistoryPanel';
6
21
  import { GitContext, type GitContextValue } from '../state/git.context';
7
22
  import {
@@ -53,14 +68,38 @@ const workspace = {
53
68
 
54
69
  function renderWith(git: GitContextValue, filePath = 'knowledge-base/Knowledge/Foo.md') {
55
70
  return render(
56
- <WorkspaceContext.Provider value={workspace}>
57
- <GitContext.Provider value={git}>
58
- <FileHistoryPanel filePath={filePath} />
59
- </GitContext.Provider>
60
- </WorkspaceContext.Provider>,
71
+ <MemoryRouter initialEntries={[`/workspace/ws-1/${filePath}`]}>
72
+ <WorkspaceContext.Provider value={workspace}>
73
+ <GitContext.Provider value={git}>
74
+ <FileHistoryPanel filePath={filePath} />
75
+ </GitContext.Provider>
76
+ </WorkspaceContext.Provider>
77
+ </MemoryRouter>,
61
78
  );
62
79
  }
63
80
 
81
+ beforeEach(() => {
82
+ apiMock.authFetch.mockReset();
83
+ apiMock.authFetch.mockResolvedValue({
84
+ ok: true,
85
+ status: 200,
86
+ blob: async () => new Blob(['bytes']),
87
+ arrayBuffer: async () => new ArrayBuffer(8),
88
+ text: async () => '',
89
+ });
90
+ accessMock.fetchFileAccess.mockReset();
91
+ accessMock.fetchFileAccess.mockResolvedValue({
92
+ canWrite: false,
93
+ canDownload: true,
94
+ eligible: { roles: [], users: [] },
95
+ owners: { roles: [], users: [] },
96
+ });
97
+ (globalThis.URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(
98
+ () => 'blob:fake-url',
99
+ );
100
+ (globalThis.URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn();
101
+ });
102
+
64
103
  describe('FileHistoryPanel', () => {
65
104
  it('renders the timeline returned from fetchFileHistory', async () => {
66
105
  const history = [
@@ -105,7 +144,7 @@ describe('FileHistoryPanel', () => {
105
144
  expect(screen.getByText('shared paragraph')).toBeInTheDocument();
106
145
  });
107
146
 
108
- it('loads the raw diff when a non-markdown file\'s commit is selected', async () => {
147
+ it('loads the line changes for a text file no viewer renders', async () => {
109
148
  const fetchFileDiff = vi.fn(async () => '--- a\n+++ b\n@@ -1 +1 @@\n-foo\n+bar\n');
110
149
  const history = [makeAttr({ sha: 'aaaaaaa0000000000', subject: 'edit' })];
111
150
  renderWith(
@@ -113,13 +152,13 @@ describe('FileHistoryPanel', () => {
113
152
  fetchFileHistory: async () => history,
114
153
  fetchFileDiff,
115
154
  }),
116
- 'knowledge-base/Knowledge/data.csv',
155
+ 'knowledge-base/Knowledge/notes.txt',
117
156
  );
118
157
  const row = await screen.findByText('edit');
119
158
  fireEvent.click(row);
120
159
  await waitFor(() =>
121
160
  expect(fetchFileDiff).toHaveBeenCalledWith(
122
- 'knowledge-base/Knowledge/data.csv',
161
+ 'knowledge-base/Knowledge/notes.txt',
123
162
  'aaaaaaa0000000000',
124
163
  ),
125
164
  );
@@ -133,12 +172,52 @@ describe('FileHistoryPanel', () => {
133
172
  fetchFileHistory: async () => history,
134
173
  fetchFileDiff: async () => '',
135
174
  }),
136
- 'knowledge-base/Knowledge/data.csv',
175
+ 'knowledge-base/Knowledge/notes.txt',
137
176
  );
138
177
  fireEvent.click(await screen.findByText('edit'));
139
178
  expect(await screen.findByText(/No file changes in this save/i)).toBeInTheDocument();
140
179
  });
141
180
 
181
+ it('routes a previewable file\'s save to the version pane, not the patch', async () => {
182
+ // A CSV is previewable, so the pane shows the table of that save with the
183
+ // line changes a click away — where it used to show the patch and nothing
184
+ // else.
185
+ const history = [makeAttr({ sha: 'aaaaaaa0000000000', subject: 'edit' })];
186
+ renderWith(
187
+ makeGit({
188
+ fetchFileHistory: async () => history,
189
+ fetchFileDiff: async () => '--- a\n+++ b\n@@ -1 +1 @@\n-a,b\n+a,c\n',
190
+ fetchFileAtChange: async () => ({ baseline: 'a,b', current: 'region,total\n EMEA,7' }),
191
+ }),
192
+ 'knowledge-base/Knowledge/data.csv',
193
+ );
194
+ fireEvent.click(await screen.findByText('edit'));
195
+ expect(await screen.findByText('region')).toBeInTheDocument();
196
+ expect(await screen.findByRole('button', { name: 'Download this version' })).toBeInTheDocument();
197
+ fireEvent.click(screen.getByRole('button', { name: 'Source changes' }));
198
+ expect(await screen.findByText(/\+a,c/)).toBeInTheDocument();
199
+ });
200
+
201
+ it('leaves a markdown history untouched: no version pane, no download', async () => {
202
+ const fetchFileDiff = vi.fn(async () => 'unused');
203
+ const history = [makeAttr({ sha: 'aaaaaaa0000000000', subject: 'edit' })];
204
+ renderWith(
205
+ makeGit({
206
+ fetchFileHistory: async () => history,
207
+ fetchFileDiff,
208
+ fetchFileAtChange: async () => ({ baseline: '# Old\n', current: '# New\n' }),
209
+ }),
210
+ );
211
+ fireEvent.click(await screen.findByText('edit'));
212
+ expect(await screen.findByRole('heading', { name: 'New' })).toBeInTheDocument();
213
+ // The markdown path reads before/after contents and nothing else — no
214
+ // patch, no version pane, no bytes.
215
+ expect(fetchFileDiff).not.toHaveBeenCalled();
216
+ expect(screen.queryByRole('button', { name: 'Download this version' })).toBeNull();
217
+ expect(screen.queryByText(/As saved/)).toBeNull();
218
+ expect(apiMock.authFetch).not.toHaveBeenCalled();
219
+ });
220
+
142
221
  it('renders the empty state for a markdown save where the file is absent on both sides', async () => {
143
222
  const history = [makeAttr({ sha: 'aaaaaaa0000000000', subject: 'edit' })];
144
223
  renderWith(
@@ -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
+ });