@bevel-software/platform-core-frontend 0.22.0 → 0.24.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
@@ -45,10 +45,9 @@ describe('sanitizeAgentHtml', () => {
45
45
  expect(out).not.toContain('attacker.com');
46
46
  });
47
47
 
48
- it('strips external src/href/action/poster/srcset/ping', () => {
48
+ it('strips external src/action/poster/srcset', () => {
49
49
  const html = `
50
50
  <img src="https://attacker.com/pixel.png" srcset="https://attacker.com/2x.png 2x">
51
- <a href="https://attacker.com/landing" ping="https://attacker.com/track">x</a>
52
51
  <form action="https://attacker.com/submit"></form>
53
52
  <video poster="https://attacker.com/thumb.jpg"></video>
54
53
  <body background="https://attacker.com/bg.jpg">
@@ -57,6 +56,18 @@ describe('sanitizeAgentHtml', () => {
57
56
  expect(out).not.toContain('attacker.com');
58
57
  });
59
58
 
59
+ // `href` is the anchor's one exception. `ping` is a beacon the browser
60
+ // fires on click without the reader ever seeing where it went, so it goes
61
+ // even on an anchor whose href stays.
62
+ it('strips an anchor ping while keeping its href', () => {
63
+ const out = sanitizeAgentHtml(
64
+ '<a href="https://example.com/landing" ping="https://tracker.example/t">x</a>',
65
+ );
66
+ expect(out).toContain('https://example.com/landing');
67
+ expect(out).not.toContain('tracker.example');
68
+ expect(out).not.toContain('ping=');
69
+ });
70
+
60
71
  it('strips javascript: URLs', () => {
61
72
  const out = sanitizeAgentHtml(
62
73
  '<a href="javascript:alert(1)">click</a><img src="javascript:alert(2)">',
@@ -93,11 +104,8 @@ describe('sanitizeAgentHtml', () => {
93
104
  expect(out).not.toContain('Process.md');
94
105
  });
95
106
 
96
- it('still strips external and javascript anchors even if they contain .md', () => {
97
- const out = sanitizeAgentHtml(
98
- '<a href="https://attacker.com/x.md">x</a><a href="javascript:alert(1)//x.md">y</a>',
99
- );
100
- expect(out).not.toContain('attacker.com');
107
+ it('still strips a javascript: anchor even when it contains .md', () => {
108
+ const out = sanitizeAgentHtml('<a href="javascript:alert(1)//x.md">y</a>');
101
109
  expect(out).not.toContain('javascript:');
102
110
  });
103
111
 
@@ -174,6 +182,136 @@ describe('sanitizeAgentHtml', () => {
174
182
  });
175
183
  });
176
184
 
185
+ /**
186
+ * The Scenarios of "Pages keep static links". A link written in a page's
187
+ * markup keeps its address when it names another document of the knowledge
188
+ * base or an `http:`, `https:` or `mailto:` destination; every other address
189
+ * still loses its href. The click itself is the parent's job — see the
190
+ * `useFileNav.openLink` suite in `routing/__tests__/kb-routes.test.tsx` for
191
+ * where a kept address goes once the reader clicks it.
192
+ */
193
+ describe('sanitizeAgentHtml: links written in the page', () => {
194
+ /** The href the sanitizer left on the first anchor, or null if it took it. */
195
+ function hrefOf(html: string): string | null {
196
+ const doc = new DOMParser().parseFromString(sanitizeAgentHtml(html), 'text/html');
197
+ const a = doc.querySelector('a');
198
+ expect(a, 'the anchor itself is never removed, only its href').not.toBeNull();
199
+ return a!.getAttribute('href');
200
+ }
201
+
202
+ it('keeps a relative link to another page', () => {
203
+ expect(hrefOf('<a href="Board.html">Board</a>')).toBe('Board.html');
204
+ });
205
+
206
+ it('keeps a relative link that walks up a folder, with its fragment', () => {
207
+ expect(hrefOf('<a href="../Reports/Q3.html#totals">Q3</a>')).toBe('../Reports/Q3.html#totals');
208
+ });
209
+
210
+ it('keeps a .htm page too', () => {
211
+ expect(hrefOf('<a href="legacy/Index.htm">legacy</a>')).toBe('legacy/Index.htm');
212
+ });
213
+
214
+ it('keeps a page named by an absolute /workspace/ address', () => {
215
+ const url = '/workspace/main/knowledge-base/Dashboards/Board.html';
216
+ expect(hrefOf(`<a href="${url}">Board</a>`)).toBe(url);
217
+ });
218
+
219
+ it('keeps a .md node link and its heading, as it did before', () => {
220
+ expect(hrefOf('<a href="Sub/Node.md#goal">Goal</a>')).toBe('Sub/Node.md#goal');
221
+ expect(hrefOf('<a href="notes.md">notes</a>')).toBe('notes.md');
222
+ });
223
+
224
+ it('keeps an http: and an https: address', () => {
225
+ expect(hrefOf('<a href="https://example.com/docs">docs</a>')).toBe('https://example.com/docs');
226
+ expect(hrefOf('<a href="http://example.com/docs">docs</a>')).toBe('http://example.com/docs');
227
+ });
228
+
229
+ it('keeps a mailto: address', () => {
230
+ expect(hrefOf('<a href="mailto:team@example.com">mail us</a>')).toBe(
231
+ 'mailto:team@example.com',
232
+ );
233
+ });
234
+
235
+ it('keeps the scheme as written, whatever its case', () => {
236
+ expect(hrefOf('<a href="HTTPS://Example.com/Docs">docs</a>')).toBe('HTTPS://Example.com/Docs');
237
+ });
238
+
239
+ it.each([
240
+ ['javascript:', 'javascript:alert(1)'],
241
+ ['disguised by case', ' JaVaScRiPt:alert(1)'],
242
+ ['disguised by a tab inside the scheme', 'java\tscript:alert(1)'],
243
+ ['disguised by a newline inside the scheme', 'java\nscript:alert(1)'],
244
+ ['disguised by a leading control character', '\u0001javascript:alert(1)'],
245
+ ['data:', 'data:text/html,<b>evil</b>'],
246
+ ['data:image, which only an <img> may carry', 'data:image/png;base64,AAAA'],
247
+ ['file:', 'file:///etc/passwd'],
248
+ ['vbscript:', 'vbscript:msgbox(1)'],
249
+ ['an app scheme nobody named', 'x-devonthink-item:4F2A'],
250
+ ['tel:, openable elsewhere but not mintable by a page', 'tel:+15551234'],
251
+ ['protocol-relative', '//cdn.example.com/x.html'],
252
+ ['a relative path that is not a document', 'assets/report.pdf'],
253
+ ['a bare directory', '../Reports/'],
254
+ ])('takes the href of %s', (_label, url) => {
255
+ expect(hrefOf(`<a href="${url}">x</a>`)).toBeNull();
256
+ });
257
+
258
+ // The parser decodes entities before we ever see the value, so a scheme
259
+ // spelled in entities is the same string as one spelled in letters.
260
+ it('takes the href of a javascript: address written in HTML entities', () => {
261
+ expect(hrefOf('<a href="&#106;avascript&#58;alert(1)">x</a>')).toBeNull();
262
+ expect(hrefOf('<a href="java&#9;script:alert(1)">x</a>')).toBeNull();
263
+ });
264
+
265
+ // Whitespace is stripped for the CHECK, not from the value: the sanitizer
266
+ // does not rewrite an author's markup. The CLICK is where it matters, and
267
+ // the nav bridge and the parent's resolver apply the same rule, so the
268
+ // address followed is `Board.html` and not a filename with spaces on it.
269
+ it('keeps a padded page link without rewriting it', () => {
270
+ expect(hrefOf('<a href=" Board.html ">Board</a>')).toBe(' Board.html ');
271
+ });
272
+
273
+ // Generated markup writes an href on its own line; the address is still an
274
+ // ordinary external one and the reader should reach it.
275
+ it('keeps an external address written across lines, verbatim', () => {
276
+ const padded = '\n https://example.com/docs\n ';
277
+ expect(hrefOf(`<a href="${padded}">docs</a>`)).toBe(padded);
278
+ });
279
+
280
+ // A scheme only a tab makes valid is nobody's markup, but a browser reads
281
+ // `htt<tab>ps:` as `https:` and so does every reader of an href here — the
282
+ // bridge posts the normalized address and the parent opens it. Keeping it is
283
+ // therefore a live link to the address a browser would have followed, not a
284
+ // dead one. The decision is the same whichever way the tab falls: the
285
+ // normalized string is checked against the allowlist, so a tab cannot turn
286
+ // a rejected scheme into an accepted one.
287
+ it('keeps an address a browser reads as external even with a tab in the scheme', () => {
288
+ expect(hrefOf('<a href="htt\tps://example.com/docs">docs</a>')).toBe(
289
+ 'htt\tps://example.com/docs',
290
+ );
291
+ // …and the same reading still refuses the dangerous ones.
292
+ expect(hrefOf('<a href="javas\tcript:alert(1)">x</a>')).toBeNull();
293
+ expect(hrefOf('<a href="da\tta:text/html,evil">x</a>')).toBeNull();
294
+ });
295
+
296
+ it('keeps an empty href alone, as an anchor with nowhere to go', () => {
297
+ expect(hrefOf('<a href="">x</a>')).toBe('');
298
+ });
299
+
300
+ // The exception is anchor + href. Nothing else gains an address.
301
+ it('does not extend the exception to other elements or attributes', () => {
302
+ const out = sanitizeAgentHtml(`
303
+ <img src="Board.html">
304
+ <img src="https://example.com/x.png">
305
+ <script src="https://example.com/x.js"></script>
306
+ <form action="https://example.com/submit"></form>
307
+ <a href="Board.html" cite="https://example.com/why">Board</a>
308
+ `);
309
+ expect(out).toContain('Board.html');
310
+ expect(out).not.toContain('example.com');
311
+ expect(out).not.toMatch(/src="Board\.html"/);
312
+ });
313
+ });
314
+
177
315
  describe('buildSandboxedHtml', () => {
178
316
  const okOpts = {
179
317
  title: 'Test',
@@ -285,6 +423,47 @@ describe('buildSandboxedHtml', () => {
285
423
  expect(out).toContain("href.charAt(0) === '#'");
286
424
  });
287
425
 
426
+ // The bridge half of the one-rule promise. The sanitizer keeps a padded
427
+ // href by reading past the padding; the bridge has to hand the parent the
428
+ // same reading, or the resolver builds a path out of the spaces. A padded
429
+ // `#goal` is still an in-page anchor and stays with the browser to scroll.
430
+ it('posts the href a browser would follow, and leaves a padded fragment alone', () => {
431
+ // No lib sources: `okOpts` carries an `export`, which a vm script cannot
432
+ // parse. The bridge is appended after the lib either way.
433
+ const out = buildSandboxedHtml({ ...okOpts, libModuleSources: [] });
434
+ const scriptBody = out.match(/<script type="module">([\s\S]*?)<\/script>/)![1];
435
+
436
+ type ClickEvent = { target: { closest: () => unknown }; preventDefault: () => void };
437
+ const handlers: ((e: ClickEvent) => void)[] = [];
438
+ const posted: unknown[] = [];
439
+ const ctx: Record<string, unknown> = {
440
+ document: {
441
+ addEventListener: (type: string, fn: (e: ClickEvent) => void) => {
442
+ if (type === 'click') handlers.push(fn);
443
+ },
444
+ },
445
+ parent: { postMessage: (msg: unknown) => posted.push(msg) },
446
+ };
447
+ vm.createContext(ctx);
448
+ vm.runInContext(`"use strict"; (function(){ ${scriptBody} }).call(undefined);`, ctx);
449
+ expect(handlers).toHaveLength(1);
450
+
451
+ const click = (href: string) => {
452
+ const anchor = { getAttribute: () => href };
453
+ handlers[0]({ target: { closest: () => anchor }, preventDefault: () => {} });
454
+ };
455
+
456
+ click('\n Board.html\n ');
457
+ click(' #goal ');
458
+ click(' https://example.com/docs ');
459
+ click(' ');
460
+
461
+ expect(posted).toEqual([
462
+ { type: 'bevel.navigate', href: 'Board.html' },
463
+ { type: 'bevel.navigate', href: 'https://example.com/docs' },
464
+ ]);
465
+ });
466
+
288
467
  it('embeds the body HTML verbatim (sanitization happens upstream)', () => {
289
468
  const out = buildSandboxedHtml({
290
469
  ...okOpts,
@@ -0,0 +1,59 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { render, screen, fireEvent } from '@testing-library/react';
3
+ import { readFileSync } from 'node:fs';
4
+ import { READ_PANE } from '../readPane';
5
+ import { RetryReadButton } from '../RetryReadButton';
6
+
7
+ /**
8
+ * Where focus goes when a viewer's "Try again" removes itself from the page.
9
+ *
10
+ * Every byte-reading renderer returns its error block as its WHOLE output, so
11
+ * the retry unmounts the button the reader just pressed and focus falls to
12
+ * `document.body` — the next Tab then starts at the top of the page. The
13
+ * handoff is in `RetryReadButton`, shared by all six viewers; the destination
14
+ * is the host pane's own region, which it declares by spreading `READ_PANE`.
15
+ */
16
+ describe('a viewer\'s retry hands focus to its host pane', () => {
17
+ it('focuses the nearest READ_PANE ancestor, and does so before the retry runs', () => {
18
+ // The order matters: the retry is what unmounts the button, so a handoff
19
+ // that happened afterwards would be looking for focus on an element that
20
+ // had already gone. Asserted by capturing `document.activeElement` from
21
+ // inside the retry callback.
22
+ const focusedWhenRetryRan = vi.fn();
23
+ render(
24
+ <div {...READ_PANE} data-testid="host">
25
+ <RetryReadButton onRetry={() => focusedWhenRetryRan(document.activeElement)} />
26
+ </div>,
27
+ );
28
+ const host = screen.getByTestId('host');
29
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
30
+ expect(focusedWhenRetryRan).toHaveBeenCalledWith(host);
31
+ expect(document.activeElement).toBe(host);
32
+ });
33
+
34
+ it('leaves focus alone when no host declares a region', () => {
35
+ // A pane that names no region keeps today's behaviour rather than throwing:
36
+ // `closest` simply finds nothing.
37
+ const onRetry = vi.fn();
38
+ render(<RetryReadButton onRetry={onRetry} />);
39
+ const activeBefore = document.activeElement;
40
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
41
+ expect(document.activeElement).toBe(activeBefore);
42
+ expect(onRetry).toHaveBeenCalledTimes(1);
43
+ });
44
+
45
+ /**
46
+ * The handoff only works where the HOST declares the region, so every place
47
+ * that mounts a viewer has to. Read from the source rather than rendered,
48
+ * because rendering `FileViewer` needs most of the app around it — and what
49
+ * would regress here is a new host, or an old one losing the spread.
50
+ */
51
+ it.each([
52
+ ['the file page', 'workspace/components/FileViewer.tsx'],
53
+ ['Version history', 'git/components/HistoryVersionPreview.tsx'],
54
+ ['the change-request dialog', 'change-requests/components/BranchFilePreview.tsx'],
55
+ ])('%s marks its viewer host as a region', (_where, file) => {
56
+ // Package root is vitest's working directory.
57
+ expect(readFileSync(`src/modules/${file}`, 'utf8')).toContain('{...READ_PANE}');
58
+ });
59
+ });
@@ -18,6 +18,13 @@
18
18
  * smaller, easier to audit, and removes any chance a future CSP
19
19
  * misconfiguration accidentally leaks something through.
20
20
  *
21
+ * An `<a href>` is the one exception, because a link is not a resource
22
+ * the document loads — it is an address the READER may choose to follow,
23
+ * and the parent, not the iframe, is what follows it. So a link to
24
+ * another document of the knowledge base, or to an `http:`, `https:` or
25
+ * `mailto:` address, keeps its href and reaches the parent through the
26
+ * nav bridge; see `isKeptLink`. Every other address is still removed.
27
+ *
21
28
  * 2. `buildSandboxedHtml` — wraps the sanitized body and the inlined
22
29
  * knowledge-base JS library into a complete HTML document with the
23
30
  * strict CSP and a single inline `<script type="module">` containing
@@ -25,6 +32,8 @@
25
32
  * the agent's own scripts).
26
33
  */
27
34
 
35
+ import { isPageLinkExternalHref, normalizeHref } from '../../../../shared/markdown/hrefs';
36
+
28
37
  const DROP_ELEMENTS = new Set([
29
38
  'link',
30
39
  'iframe',
@@ -62,6 +71,12 @@ const URL_ATTRIBUTES = [
62
71
  * shape (absolute URL, protocol-relative, scheme-bearing, or plain
63
72
  * relative path that the browser would resolve against `about:srcdoc`)
64
73
  * is stripped.
74
+ *
75
+ * This governs every URL-bearing attribute EXCEPT an anchor's `href`, which
76
+ * is a destination rather than a resource and has its own rule in
77
+ * {@link isKeptLink}. In particular a `data:image/*` href is NOT a picture
78
+ * the document shows, it is an address a click would try to open, so an
79
+ * anchor does not get this allowance.
65
80
  */
66
81
  function isAllowedUrl(rawUrl: string): boolean {
67
82
  const url = rawUrl.trim().toLowerCase();
@@ -71,26 +86,50 @@ function isAllowedUrl(rawUrl: string): boolean {
71
86
  return false;
72
87
  }
73
88
 
89
+ /** The scheme of a URL (`https:`), lower-cased, or null when it has none. */
90
+ function schemeOf(url: string): string | null {
91
+ const match = /^[a-z][a-z0-9+.-]*:/i.exec(url);
92
+ return match ? match[0].toLowerCase() : null;
93
+ }
94
+
74
95
  /**
75
- * Decide whether an `<a href>` deep-links to a node in the knowledge graph:
76
- * either a `.md` node path (optionally with a `#heading` anchor, e.g.
77
- * `../NodeTypes/Process.md#goal`) or an absolute `/workspace/<branch>/<path>`
78
- * citation URL — the same shapes the markdown renderer treats as internal
79
- * links.
96
+ * Decide whether an `<a href>` written in the page's markup keeps its address.
97
+ * Three shapes survive:
80
98
  *
81
- * These survive sanitization (unlike other relative URLs, which are stripped):
82
- * the iframe sandbox forbids navigating the top window, so the runtime
83
- * intercepts the click and asks the parent to navigate instead of letting the
84
- * browser attempt — and error on — the navigation. Any scheme-bearing
85
- * (`http:`, `javascript:`, …) or protocol-relative (`//host`) URL is rejected.
99
+ * - another document of the knowledge base — a `.md`, `.html` or `.htm`
100
+ * path, with an optional `#heading` (`../Reports/Q3.html#totals`);
101
+ * - an absolute `/workspace/<branch>/<path>` citation URL;
102
+ * - an external `http:`, `https:` or `mailto:` address, per
103
+ * {@link isPageLinkExternalHref}.
104
+ *
105
+ * Everything else loses its href: any other scheme (`javascript:`, `data:`,
106
+ * `file:`, `vbscript:`, an app's own `x-foo:`), protocol-relative `//host`,
107
+ * and any other relative path — the iframe loads from `about:srcdoc`, where a
108
+ * relative URL resolves to nothing the browser can fetch.
109
+ *
110
+ * A kept link is never followed by the browser: the sandbox forbids
111
+ * navigating the top window, so the nav bridge in `buildSandboxedHtml` cancels
112
+ * the click and hands the address to the parent, which resolves a document
113
+ * against this page's own folder and opens an external address in a new tab
114
+ * (`noopener,noreferrer`). This predicate is one of two gates on that path —
115
+ * the other is `isOpenableExternalHref`, which guards the bridge against the
116
+ * strings a page's SCRIPT can post without any anchor at all.
117
+ *
118
+ * The href is read through {@link normalizeHref}, the same rule the nav bridge
119
+ * and the parent's resolver apply, so the string judged here is the string
120
+ * followed: a padded `' Board.html '` is kept AND resolves against the
121
+ * page's folder as `Board.html`, rather than becoming a filename with spaces
122
+ * in it. HTML entities are already decoded by the time we see the value — it
123
+ * comes out of `getAttribute`, past the parser.
86
124
  */
87
- function isInternalNodeLink(rawUrl: string): boolean {
88
- const url = rawUrl.trim();
89
- if (url === '') return false;
125
+ function isKeptLink(rawUrl: string): boolean {
126
+ const url = normalizeHref(rawUrl);
127
+ if (url === '') return true; // an anchor with nowhere to go; nothing to strip
128
+ if (url.startsWith('#')) return true; // a section of this same page
90
129
  if (url.startsWith('//')) return false; // protocol-relative
91
- if (/^[a-z][a-z0-9+.-]*:/i.test(url)) return false; // any URL scheme
130
+ if (schemeOf(url)) return isPageLinkExternalHref(url);
92
131
  if (url.startsWith('/workspace/')) return true;
93
- return /\.md(#|$)/i.test(url);
132
+ return /\.(?:md|html|htm)(?:#|$)/i.test(url);
94
133
  }
95
134
 
96
135
  /**
@@ -150,10 +189,18 @@ export function sanitizeAgentHtml(html: string): string {
150
189
  for (const attr of URL_ATTRIBUTES) {
151
190
  if (!el.hasAttribute(attr)) continue;
152
191
  const value = el.getAttribute(attr) ?? '';
153
- // An anchor that deep-links to a KB node keeps its href — the runtime
154
- // intercepts the click and routes navigation through the parent (see
155
- // the nav-bridge script in `buildSandboxedHtml`).
156
- if (isAnchor && attr === 'href' && isInternalNodeLink(value)) continue;
192
+ // An anchor's `href` is a destination, not a resource, so `isKeptLink`
193
+ // decides it ALONE — not as an exception layered on top of
194
+ // `isAllowedUrl`. It keeps a link to another document of the knowledge
195
+ // base or to an allowed external address (the runtime intercepts the
196
+ // click and routes it through the parent — see the nav-bridge script in
197
+ // `buildSandboxedHtml`), and it is stricter than `isAllowedUrl` about
198
+ // `data:image/*`, which is a picture an `<img>` may show and not an
199
+ // address a reader may be sent to.
200
+ if (isAnchor && attr === 'href') {
201
+ if (!isKeptLink(value)) el.removeAttribute(attr);
202
+ continue;
203
+ }
157
204
  if (!isAllowedUrl(value)) el.removeAttribute(attr);
158
205
  }
159
206
  }
@@ -263,11 +310,24 @@ const NAV_BRIDGE = `
263
310
  globalThis.bevel.openNode = navigate;
264
311
  globalThis.bevel.navigate = navigate;
265
312
  if (typeof document !== 'undefined') {
313
+ // A written href is read the way a browser reads it before the bridge
314
+ // decides anything — the same rule as \`normalizeHref\` in the parent, kept
315
+ // here in ES5 because this source is a string injected into the iframe and
316
+ // cannot import. Without it a padded ' #goal ' would be posted to the
317
+ // parent instead of left to the browser to scroll.
318
+ function normalize(url) {
319
+ var s = url.replace(/[\\t\\n\\r]/g, '');
320
+ var start = 0;
321
+ var end = s.length;
322
+ while (start < end && s.charCodeAt(start) <= 0x20) start++;
323
+ while (end > start && s.charCodeAt(end - 1) <= 0x20) end--;
324
+ return s.slice(start, end);
325
+ }
266
326
  document.addEventListener('click', function (e) {
267
327
  var el = e.target;
268
328
  var a = el && el.closest ? el.closest('a[href]') : null;
269
329
  if (!a) return;
270
- var href = a.getAttribute('href');
330
+ var href = normalize(a.getAttribute('href') || '');
271
331
  if (!href || href.charAt(0) === '#') return;
272
332
  e.preventDefault();
273
333
  navigate(href);
@@ -10,7 +10,12 @@ import { LegacyOfficeRenderer } from './LegacyOfficeRenderer';
10
10
  import { lazyRenderer } from './lazyRenderer';
11
11
 
12
12
  export type { FileRendererProps, RendererSaveState } from './types';
13
- export { RendererWorkspaceContext, useRendererWorkspaceId } from './rendererWorkspace';
13
+ export {
14
+ RendererWorkspaceContext,
15
+ useRendererWorkspaceId,
16
+ useRendererFileRef,
17
+ type RendererFileRef,
18
+ } from './rendererWorkspace';
14
19
 
15
20
  /**
16
21
  * The document viewers are code-split: their parsers (xlsx ~141 KB gzip,
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The attribute naming the element a host pane keeps mounted around a viewer —
3
+ * see `RetryReadButton` for what it is for.
4
+ */
5
+ const READ_PANE_ATTRIBUTE = 'data-read-pane';
6
+
7
+ /** The selector `RetryReadButton` looks the region up with. */
8
+ export const READ_PANE_SELECTOR = `[${READ_PANE_ATTRIBUTE}]`;
9
+
10
+ /**
11
+ * Spread this onto a host pane's own container to make it that pane's read
12
+ * region: `<div {...READ_PANE} …>`.
13
+ *
14
+ * One object rather than an attribute to copy, because the attribute is
15
+ * useless without the `tabIndex`: `.focus()` only lands on an element the
16
+ * document considers focusable, which is what `tabIndex={-1}` makes a plain
17
+ * div (the same idiom `KbPageHeader` and `SkillPage` use for their regions).
18
+ *
19
+ * Its own module, not `RetryReadButton`'s, so that file keeps exporting a
20
+ * component and nothing else — the fast-refresh rule the package lints for.
21
+ */
22
+ export const READ_PANE = { [READ_PANE_ATTRIBUTE]: '', tabIndex: -1 };
@@ -1,24 +1,50 @@
1
1
  import { createContext, useContext } from 'react';
2
2
  import { WorkspaceContext } from '../../state/workspace.context';
3
3
 
4
+ /**
5
+ * A PAST SAVE the renderers should read instead of the working tree.
6
+ *
7
+ * Version history shows a file as it was after one particular save, in the
8
+ * very viewer the file page uses. A viewer only ever asks two things of its
9
+ * surroundings — which workspace, which path — so pointing it at a past
10
+ * version is one more coordinate on the same question rather than a second
11
+ * kind of viewer: the byte-reading renderers pass this straight to
12
+ * `rawFileUrl`, and the backend serves `git show <ref>:<path>` under the
13
+ * file's own read gate.
14
+ *
15
+ * `side: 'before'` reads `<sha>^`, which is what the save that DELETED a file
16
+ * has to show — there is nothing at that path after such a save.
17
+ */
18
+ export interface RendererFileRef {
19
+ /** The save, as a commit sha. */
20
+ ref: string;
21
+ /** Which side of that save. Defaults to `'after'`. */
22
+ side?: 'after' | 'before';
23
+ }
24
+
4
25
  /**
5
26
  * The workspace a renderer should fetch its bytes from, when that is NOT the
6
- * workspace the app has checked out.
27
+ * workspace the app has checked out — and, optionally, the past save within
28
+ * it.
7
29
  *
8
30
  * Every viewer here reads the file itself — `rawFileUrl(workspaceId, path)` —
9
31
  * rather than the text buffer, and until now `workspaceId` could only be the
10
32
  * one the user is browsing. The change-request dialog needs the same viewers
11
33
  * pointed at a DIFFERENT branch's workspace (the request's), so it provides
12
- * this override around them.
34
+ * this override around them; Version history needs them pointed at a past
35
+ * save of THIS workspace, which is `fileRef`.
13
36
  *
14
- * A narrow context on purpose: `workspaceId` is the only thing any renderer
15
- * takes from the workspace, and standing up a whole `WorkspaceContextValue`
16
- * (forty methods that mutate a working tree the dialog must never touch) to
17
- * pass one string would be a lie about what the pane can do.
37
+ * A narrow context on purpose: `workspaceId` (and now the save) is the only
38
+ * thing any renderer takes from the workspace, and standing up a whole
39
+ * `WorkspaceContextValue` (forty methods that mutate a working tree neither
40
+ * pane must ever touch) to pass one string would be a lie about what the pane
41
+ * can do.
18
42
  */
19
- export const RendererWorkspaceContext = createContext<{ workspaceId: string | null } | null>(
20
- null,
21
- );
43
+ export const RendererWorkspaceContext = createContext<{
44
+ workspaceId: string | null;
45
+ /** A past save to read instead of the working tree; omitted = the tree. */
46
+ fileRef?: RendererFileRef | null;
47
+ } | null>(null);
22
48
 
23
49
  /**
24
50
  * The workspace id the renderer should read from: the override when one is
@@ -38,3 +64,18 @@ export function useRendererWorkspaceId(): string | null {
38
64
  }
39
65
  return workspace.workspaceId;
40
66
  }
67
+
68
+ /**
69
+ * The past save this renderer is bound to, or `null` for the working tree.
70
+ *
71
+ * Never throws and needs no provider: reading the working tree is the answer
72
+ * for every surface that has not asked for a version, which is all of them
73
+ * except Version history.
74
+ *
75
+ * Renderers spread the two FIELDS into their effect dependencies rather than
76
+ * this object, so a provider that rebuilds its context value on an unrelated
77
+ * render cannot re-trigger a read.
78
+ */
79
+ export function useRendererFileRef(): RendererFileRef | null {
80
+ return useContext(RendererWorkspaceContext)?.fileRef ?? null;
81
+ }
@@ -0,0 +1,27 @@
1
+ import { useCallback, useState } from 'react';
2
+
3
+ /**
4
+ * "Try again" for a viewer that fetches its own bytes.
5
+ *
6
+ * Every byte-reading renderer here loads in an effect keyed on the workspace
7
+ * and the path, and reports a failed read as a terminal message. That is
8
+ * exactly as far as recovery went: a failure whose inputs are all unchanged
9
+ * has nothing to re-trigger the effect, so a dropped connection or a 502 left
10
+ * the pane on its error until something else remounted it. On the file page a
11
+ * reload is at least available; in a pane that is part of a larger surface —
12
+ * the change-request dialog, Version history's version pane — there was no way
13
+ * back to the document at all.
14
+ *
15
+ * `attempt` goes in the read effect's dependency list and is the whole
16
+ * mechanism; `retry()` bumps it. Automatic recovery on a path, workspace or
17
+ * version change is untouched, since those change the deps by themselves.
18
+ *
19
+ * `ImageRenderer` grew this counter first, inline, for the change-request
20
+ * pane. Shared here so the five other viewers answer a failed read the same
21
+ * way rather than each inventing it.
22
+ */
23
+ export function useReadRetry(): { attempt: number; retry: () => void } {
24
+ const [attempt, setAttempt] = useState(0);
25
+ const retry = useCallback(() => setAttempt((n) => n + 1), []);
26
+ return { attempt, retry };
27
+ }