@bevel-software/platform-core-frontend 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/package.json +2 -2
  2. package/src/lib/__tests__/api.test.ts +28 -1
  3. package/src/lib/api.ts +4 -2
  4. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  5. package/src/modules/access/api.ts +3 -4
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  8. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  9. package/src/modules/admin/services/groups.api.ts +11 -1
  10. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  11. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  12. package/src/modules/agents/connect-as.ts +15 -0
  13. package/src/modules/agents/index.ts +5 -0
  14. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  15. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  16. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  17. package/src/modules/audit/components/AuditLogPage.tsx +9 -0
  18. package/src/modules/audit/services/audit.api.ts +5 -0
  19. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  20. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  21. package/src/modules/auth/components/AccountPage.tsx +8 -2
  22. package/src/modules/auth/services/account.api.ts +18 -2
  23. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  24. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  25. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  26. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  27. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  28. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  29. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  30. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  31. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  32. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  33. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  34. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  35. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +38 -4
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  37. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  38. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +26 -0
  39. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  40. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  41. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  42. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  43. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  44. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  45. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  46. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  47. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  48. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  49. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  50. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  51. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  52. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  53. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  54. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  55. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  56. package/src/modules/workspace/index.ts +21 -2
  57. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  58. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  59. package/src/modules/workspace/utils/fileTree.ts +1 -1
@@ -0,0 +1,397 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { buildSandboxedHtml, sanitizeAgentHtml } from '../htmlSandbox';
6
+
7
+ /**
8
+ * The `### Live data` subsection of the agent guide's `## HTML views` tells
9
+ * page authors how a data-driven page loads: final shell first, one consistent
10
+ * dataset at a time, refresh over the current board, a failed read with a
11
+ * retry, reads in bounded parallel, links by root-relative path. Its reference
12
+ * page is the one example an agent copies, so this suite runs THAT page —
13
+ * taken out of the guide, not a copy of it — and holds it to every one of
14
+ * those rules.
15
+ *
16
+ * The page goes through the renderer's own pipeline: the sanitizer, the
17
+ * sandbox document and its tool-bridge runtime. The test plays the app on the
18
+ * other side of the bridge, answering each `bevel.tool.call` the page posts
19
+ * when the test decides — which is how a slow, partial or failed load is
20
+ * produced without touching the page. The section is core-backend's file and
21
+ * is read here as TEXT, in a test only, like `htmlViewsGuide.test.ts` does.
22
+ */
23
+ const HTML_VIEWS_MD = path.resolve(
24
+ path.dirname(fileURLToPath(import.meta.url)),
25
+ '../../../../../../../core-backend/agent-guide/html-views.md',
26
+ );
27
+
28
+ /** The checkout folder the guide is rendered for here: any name will do. */
29
+ const KB_DIR_NAME = 'knowledge-base';
30
+
31
+ function referencePage(): string {
32
+ // Read as LF whatever the checkout's line endings.
33
+ const section = readFileSync(HTML_VIEWS_MD, 'utf8').replace(/\r\n/g, '\n');
34
+ const live = /\n### Live data[^\n]*\n([\s\S]*?)(?=\n### |$)/.exec(section);
35
+ if (!live) throw new Error('the `## HTML views` section has no `### Live data` subsection');
36
+ const page = /```html\n([\s\S]*?)\n```/.exec(live[1]!);
37
+ if (!page) throw new Error('the `### Live data` subsection has no reference page');
38
+ // Rendered as the guide renders it for a deployment.
39
+ return page[1]!.replaceAll('{{kbDirName}}', KB_DIR_NAME);
40
+ }
41
+
42
+ const FOLDER = 'Data/Tickets';
43
+
44
+ interface ToolCall {
45
+ requestId: string;
46
+ fn: string;
47
+ args: [string, { body: { branch: string; path: string } }];
48
+ }
49
+
50
+ /**
51
+ * The reference page, mounted the way the renderer mounts it on the app's
52
+ * file page, with the test as the app behind `window.bevel.tools`.
53
+ */
54
+ async function mountReferencePage(branch = 'main') {
55
+ const srcdoc = buildSandboxedHtml({
56
+ title: 'Tickets',
57
+ libModuleSources: [],
58
+ bodyHtml: sanitizeAgentHtml(referencePage()),
59
+ toolBridge: true,
60
+ branch,
61
+ });
62
+ document.body.innerHTML = /<body>([\s\S]*)<\/body>/.exec(srcdoc)![1]!;
63
+
64
+ const calls: ToolCall[] = [];
65
+ const answered = new Set<string>();
66
+ const listeners: Array<(event: { source: unknown; data: unknown }) => void> = [];
67
+ const parent = {
68
+ postMessage(msg: { type: string }) {
69
+ if (msg.type === 'bevel.tool.call') calls.push(msg as unknown as ToolCall);
70
+ },
71
+ };
72
+ const frameGlobal: Record<string, unknown> = {
73
+ addEventListener(type: string, fn: (event: { source: unknown; data: unknown }) => void) {
74
+ if (type === 'message') listeners.push(fn);
75
+ },
76
+ removeEventListener() {},
77
+ };
78
+
79
+ // Module scripts in document order over one global, as the frame runs them;
80
+ // the page's own script may use top-level await.
81
+ const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (
82
+ ...args: string[]
83
+ ) => (...values: unknown[]) => Promise<void>;
84
+ for (const script of Array.from(document.querySelectorAll('script[type="module"]'))) {
85
+ const body = script.textContent!.replace(/<\\\/(script)/gi, '</$1');
86
+ void new AsyncFunction('globalThis', 'window', 'document', 'parent', body)(
87
+ frameGlobal,
88
+ frameGlobal,
89
+ document,
90
+ parent,
91
+ );
92
+ }
93
+ await settle();
94
+
95
+ function respond(call: ToolCall, outcome: { ok: true; result: unknown } | { ok: false; error: string }) {
96
+ answered.add(call.requestId);
97
+ const data = { type: 'bevel.tool.response', requestId: call.requestId, ...outcome };
98
+ for (const listener of listeners) listener({ source: parent, data });
99
+ }
100
+
101
+ return {
102
+ calls,
103
+ /** The calls the page is still waiting on. */
104
+ pending: () => calls.filter((c) => !answered.has(c.requestId)),
105
+ respond,
106
+ };
107
+ }
108
+
109
+ type Page = Awaited<ReturnType<typeof mountReferencePage>>;
110
+
111
+ /** Let the page's promise chains and the bridge's replies run. */
112
+ function settle() {
113
+ return new Promise((resolve) => setTimeout(resolve, 0));
114
+ }
115
+
116
+ function ticket(name: string, status: string, eol = '\n') {
117
+ return ['---', 'nodeType: "[Ticket](../NodeTypes/Ticket.md)"', '---', '', '# Name', name, '', '# Status', status, ''].join(eol);
118
+ }
119
+
120
+ /** The knowledge base the app answers from: file name → markdown. */
121
+ type Files = Record<string, string>;
122
+
123
+ const FIRST: Files = {
124
+ 'A.md': ticket('Alpha', 'todo'),
125
+ 'B.md': ticket('Bravo', 'todo'),
126
+ 'C.md': ticket('Charlie', 'doing'),
127
+ 'D.md': ticket('Delta', 'done'),
128
+ 'E.md': ticket('Echo', 'done'),
129
+ 'F.md': ticket('Foxtrot', 'done'),
130
+ };
131
+
132
+ const SECOND: Files = { ...FIRST, 'A.md': ticket('Alpha', 'done'), 'G.md': ticket('Golf', 'doing') };
133
+
134
+ /** Answer the page's pending `list_files` from `files`, naming paths as the tool does: checkout folder first. */
135
+ async function answerListing(page: Page, files: Files) {
136
+ const listing = page.pending().find((c) => c.args[0] === 'list_files');
137
+ expect(listing, 'the page lists its folder first').toBeDefined();
138
+ page.respond(listing!, {
139
+ ok: true,
140
+ result: {
141
+ path: `${KB_DIR_NAME}/${FOLDER}`,
142
+ entries: Object.keys(files).map((name) => ({ name, type: 'file', canWrite: false })),
143
+ },
144
+ });
145
+ await settle();
146
+ }
147
+
148
+ /**
149
+ * Answer up to `count` of the page's pending reads from `files` (all of them
150
+ * when omitted), failing the one named by `fail`.
151
+ */
152
+ async function answerReads(page: Page, files: Files, { count = Infinity, fail }: { count?: number; fail?: string } = {}) {
153
+ let left = count;
154
+ while (left > 0) {
155
+ const read = page.pending().find((c) => c.args[0] === 'read_file');
156
+ if (!read) break;
157
+ const name = read.args[1].body.path.slice(FOLDER.length + 1);
158
+ if (name === fail) page.respond(read, { ok: false, error: `You cannot read ${read.args[1].body.path}.` });
159
+ else
160
+ page.respond(read, {
161
+ ok: true,
162
+ // The tool answers the path checkout folder first, whatever spelling it was asked with.
163
+ result: { path: `${KB_DIR_NAME}/${read.args[1].body.path}`, content: files[name], canWrite: false },
164
+ });
165
+ left -= 1;
166
+ await settle();
167
+ }
168
+ }
169
+
170
+ const el = (id: string) => document.getElementById(id)!;
171
+ const status = () => el('status').textContent;
172
+ const countOf = (column: string) => document.querySelector(`[data-status="${column}"] .count`)!.textContent;
173
+ const cardsOf = (column: string) =>
174
+ Array.from(document.querySelectorAll(`[data-status="${column}"] li`)).map((li) =>
175
+ li.classList.contains('placeholder') ? '…' : li.textContent,
176
+ );
177
+ const boardText = () => ['todo', 'doing', 'done'].map((c) => [countOf(c), ...cardsOf(c)].join('|')).join(' / ');
178
+
179
+ const FIRST_BOARD = '(2)|Alpha|Bravo / (1)|Charlie / (3)|Delta|Echo|Foxtrot';
180
+ const SECOND_BOARD = '(1)|Bravo / (2)|Charlie|Golf / (4)|Alpha|Delta|Echo|Foxtrot';
181
+ const LOADING_BOARD = '|…|… / |…|… / |…|…';
182
+
183
+ /**
184
+ * The shell's elements, and a watch on the page's top level: a load that
185
+ * replaces the page instead of filling it shows up as a changed element or a
186
+ * child added to or removed from `<body>`.
187
+ */
188
+ function watchShell() {
189
+ const ids = ['board', 'status', 'refresh', 'retry'];
190
+ const elements = [...ids.map(el), ...Array.from(document.querySelectorAll('.column, .column ul'))];
191
+ const topLevel: MutationRecord[] = [];
192
+ const observer = new MutationObserver((records) => topLevel.push(...records));
193
+ observer.observe(document.body, { childList: true });
194
+ return {
195
+ expectUnchanged() {
196
+ topLevel.push(...observer.takeRecords());
197
+ expect(topLevel, 'nothing is added to or removed from <body>').toEqual([]);
198
+ const now = [...ids.map(el), ...Array.from(document.querySelectorAll('.column, .column ul'))];
199
+ expect(now.length).toBe(elements.length);
200
+ now.forEach((node, i) => expect(node, 'the same shell element').toBe(elements[i]));
201
+ },
202
+ };
203
+ }
204
+
205
+ afterEach(() => {
206
+ document.body.innerHTML = '';
207
+ });
208
+
209
+ describe("the guide's live-data reference page", () => {
210
+ it('is plain HTML with inline script: the sanitizer keeps all of it', () => {
211
+ const page = referencePage();
212
+ expect(page).not.toMatch(/<script[^>]*\bsrc=|import\s|React|useState/);
213
+ const kept = sanitizeAgentHtml(page);
214
+ for (const id of ['board', 'status', 'refresh', 'retry']) expect(kept).toContain(`id="${id}"`);
215
+ expect(kept).toContain('<script type="module">');
216
+ });
217
+
218
+ it('cold load: the final shell at once, no partial data, then the whole board in one step', async () => {
219
+ const page = await mountReferencePage();
220
+ const shell = watchShell();
221
+
222
+ // Before any data: the board's columns, with placeholders inside them.
223
+ expect(status()).toBe('Loading…');
224
+ expect(el('board').getAttribute('aria-busy')).toBe('true');
225
+ expect(boardText()).toBe(LOADING_BOARD);
226
+ expect((el('refresh') as HTMLButtonElement).disabled).toBe(true);
227
+
228
+ await answerListing(page, FIRST);
229
+ await answerReads(page, FIRST, { count: 4 });
230
+ // Four of six read: no count, card or empty column is shown yet.
231
+ expect(boardText()).toBe(LOADING_BOARD);
232
+ expect(status()).toBe('Loading…');
233
+
234
+ await answerReads(page, FIRST);
235
+ expect(boardText()).toBe(FIRST_BOARD);
236
+ expect(el('board').getAttribute('aria-busy')).toBe('false');
237
+ expect(status()).toMatch(/^Updated /);
238
+ expect((el('refresh') as HTMLButtonElement).disabled).toBe(false);
239
+ shell.expectUnchanged();
240
+ });
241
+
242
+ it('links each card to the file on the branch it read it from, by the path the tool answered', async () => {
243
+ const page = await mountReferencePage();
244
+ await answerListing(page, FIRST);
245
+ await answerReads(page, FIRST);
246
+ const hrefs = Array.from(document.querySelectorAll('.column a')).map((a) => a.getAttribute('href'));
247
+ // The tool's path already carries the checkout folder; the page adds nothing in front of it.
248
+ expect(hrefs).toEqual(Object.keys(FIRST).map((name) => `/workspace/main/${KB_DIR_NAME}/${FOLDER}/${name}`));
249
+ });
250
+
251
+ it('keeps a name carrying `#`, `?` or `%` in the link, each segment encoded on its own', async () => {
252
+ const files: Files = { 'A#1.md': ticket('Sharp', 'todo'), 'B?2.md': ticket('Query', 'doing'), 'C%3.md': ticket('Percent', 'done') };
253
+ const page = await mountReferencePage();
254
+ await answerListing(page, files);
255
+ await answerReads(page, files);
256
+ const hrefs = Array.from(document.querySelectorAll('.column a')).map((a) => a.getAttribute('href'));
257
+ // `#1.md` would otherwise be the URL's fragment, and the card would open `A`.
258
+ expect(hrefs).toEqual([
259
+ `/workspace/main/${KB_DIR_NAME}/Data/Tickets/A%231.md`,
260
+ `/workspace/main/${KB_DIR_NAME}/Data/Tickets/B%3F2.md`,
261
+ `/workspace/main/${KB_DIR_NAME}/Data/Tickets/C%253.md`,
262
+ ]);
263
+ });
264
+
265
+ it('reads a file saved with Windows line endings like any other', async () => {
266
+ const page = await mountReferencePage();
267
+ const crlf: Files = { 'A.md': ticket('Alpha', 'todo', '\r\n'), 'B.md': ticket('Bravo', 'done', '\r\n') };
268
+ await answerListing(page, crlf);
269
+ await answerReads(page, crlf);
270
+ expect(boardText()).toBe('(1)|Alpha / (0)|None / (1)|Bravo');
271
+ });
272
+
273
+ it('reads its data and links its cards on the branch it is viewed on, read from window.bevel.branch', async () => {
274
+ const page = await mountReferencePage('alice/drafts');
275
+ expect(page.calls.map((c) => [c.args[0], c.args[1].body.branch])).toEqual([['list_files', 'alice/drafts']]);
276
+ await answerListing(page, FIRST);
277
+ expect(page.pending().every((c) => c.args[1].body.branch === 'alice/drafts')).toBe(true);
278
+ await answerReads(page, FIRST);
279
+ const hrefs = Array.from(document.querySelectorAll('.column a')).map((a) => a.getAttribute('href'));
280
+ expect(hrefs).toEqual(Object.keys(FIRST).map((name) => `/workspace/alice%2Fdrafts/${KB_DIR_NAME}/${FOLDER}/${name}`));
281
+ });
282
+
283
+ it('reads in bounded parallel, only after listing, through read-only tools, never a chain', async () => {
284
+ const page = await mountReferencePage();
285
+ expect(page.calls.map((c) => c.args[0])).toEqual(['list_files']);
286
+
287
+ await answerListing(page, FIRST);
288
+ // Six files to read, four at a time.
289
+ expect(page.pending().length).toBe(4);
290
+ await answerReads(page, FIRST, { count: 1 });
291
+ expect(page.pending().length).toBe(4);
292
+ await answerReads(page, FIRST);
293
+
294
+ expect(page.calls.filter((c) => c.args[0] === 'read_file').map((c) => c.args[1].body.path).sort()).toEqual(
295
+ Object.keys(FIRST).map((name) => `${FOLDER}/${name}`),
296
+ );
297
+ for (const call of page.calls) {
298
+ expect(call.fn).toBe('callTool');
299
+ expect(['list_files', 'read_file']).toContain(call.args[0]);
300
+ }
301
+ });
302
+
303
+ it('warm refresh: the current board stays, marked busy, while a small refreshing state shows, then is replaced whole', async () => {
304
+ const page = await mountReferencePage();
305
+ await answerListing(page, FIRST);
306
+ await answerReads(page, FIRST);
307
+ const shell = watchShell();
308
+
309
+ (el('refresh') as HTMLButtonElement).click();
310
+ await settle();
311
+ expect(status()).toBe('Refreshing…');
312
+ expect(el('board').getAttribute('aria-busy')).toBe('true');
313
+ expect((el('refresh') as HTMLButtonElement).disabled).toBe(true);
314
+ expect(boardText()).toBe(FIRST_BOARD);
315
+
316
+ await answerListing(page, SECOND);
317
+ await answerReads(page, SECOND, { count: 5 });
318
+ // Part of the new dataset is in: the board is still the last whole one.
319
+ expect(boardText()).toBe(FIRST_BOARD);
320
+ expect(status()).toBe('Refreshing…');
321
+
322
+ await answerReads(page, SECOND);
323
+ expect(boardText()).toBe(SECOND_BOARD);
324
+ expect(el('board').getAttribute('aria-busy')).toBe('false');
325
+ expect(status()).toMatch(/^Updated /);
326
+ expect((el('refresh') as HTMLButtonElement).disabled).toBe(false);
327
+ shell.expectUnchanged();
328
+ });
329
+
330
+ it('a failed read on refresh keeps the last good board, says why, and retry recovers', async () => {
331
+ const page = await mountReferencePage();
332
+ await answerListing(page, FIRST);
333
+ await answerReads(page, FIRST);
334
+ const shell = watchShell();
335
+
336
+ (el('refresh') as HTMLButtonElement).click();
337
+ await settle();
338
+ await answerListing(page, SECOND);
339
+ await answerReads(page, SECOND, { fail: 'C.md' });
340
+
341
+ expect(boardText()).toBe(FIRST_BOARD);
342
+ expect(el('status').className).toBe('error');
343
+ expect(status()).toBe('Could not refresh; showing the last loaded board. You cannot read Data/Tickets/C.md.');
344
+ expect(el('retry').hidden).toBe(false);
345
+
346
+ el('retry').click();
347
+ await settle();
348
+ expect(el('retry').hidden).toBe(true);
349
+ expect(status()).toBe('Refreshing…');
350
+ await answerListing(page, SECOND);
351
+ await answerReads(page, SECOND);
352
+ expect(boardText()).toBe(SECOND_BOARD);
353
+ expect(el('status').className).toBe('');
354
+ shell.expectUnchanged();
355
+ });
356
+
357
+ it('a failed read starts no further read and offers Retry only once the reads in flight settle', async () => {
358
+ const page = await mountReferencePage();
359
+ await answerListing(page, FIRST);
360
+ const reads = () => page.calls.filter((c) => c.args[0] === 'read_file').length;
361
+ expect(reads()).toBe(4);
362
+
363
+ await answerReads(page, FIRST, { count: 1, fail: 'A.md' });
364
+ // Three reads still in flight; the two files left are not started.
365
+ expect(page.pending().length).toBe(3);
366
+ expect(reads()).toBe(4);
367
+ expect(el('retry').hidden).toBe(true);
368
+ expect(status()).toBe('Loading…');
369
+
370
+ await answerReads(page, FIRST);
371
+ expect(reads()).toBe(4);
372
+ expect(status()).toBe('Could not load the tickets. You cannot read Data/Tickets/A.md.');
373
+ expect(el('retry').hidden).toBe(false);
374
+ expect(boardText()).toBe(LOADING_BOARD);
375
+ });
376
+
377
+ it('a failed read on the first load keeps the shell, says why, and retry recovers', async () => {
378
+ const page = await mountReferencePage();
379
+ const shell = watchShell();
380
+ await answerListing(page, FIRST);
381
+ await answerReads(page, FIRST, { fail: 'E.md' });
382
+
383
+ // The reads that succeeded are not shown as if they were the board.
384
+ expect(boardText()).toBe(LOADING_BOARD);
385
+ expect(status()).toBe('Could not load the tickets. You cannot read Data/Tickets/E.md.');
386
+ expect(el('retry').hidden).toBe(false);
387
+
388
+ el('retry').click();
389
+ await settle();
390
+ expect(status()).toBe('Loading…');
391
+ await answerListing(page, FIRST);
392
+ await answerReads(page, FIRST);
393
+ expect(boardText()).toBe(FIRST_BOARD);
394
+ expect(el('retry').hidden).toBe(true);
395
+ shell.expectUnchanged();
396
+ });
397
+ });
@@ -373,21 +373,44 @@ const NAV_BRIDGE = `
373
373
  }
374
374
  globalThis.bevel.openNode = navigate;
375
375
  globalThis.bevel.navigate = navigate;
376
+ // A link that names this page's own file with a fragment
377
+ // ('Roadmap.html#q3') is posted like any path; the parent recognises the
378
+ // file and hands the fragment back to be scrolled here, as '#q3' is.
379
+ if (typeof globalThis.addEventListener === 'function') globalThis.addEventListener('message', function (event) {
380
+ if (event.source !== parent) return;
381
+ var msg = event.data;
382
+ if (!msg || typeof msg !== 'object' || msg.type !== 'bevel.jump' || typeof msg.hash !== 'string') return;
383
+ var hash = normalize(msg.hash);
384
+ if (hash.charAt(0) === '#') jumpTo(hash);
385
+ });
386
+ // A click the reader asked a NEW TAB of — Ctrl, Cmd or Shift held, or the
387
+ // middle button (an 'auxclick'; it never fires 'click') — is what a browser
388
+ // opens a new tab for. The frame cannot: the sandbox has no allow-popups,
389
+ // so left to the browser it opens nothing, or navigates the frame away.
390
+ // The parent is asked instead, for any destination, a fragment of this
391
+ // page included (the parent opens this page at that section).
392
+ function followLink(e) {
393
+ if (e.type === 'auxclick' && e.button !== 1) return;
394
+ var el = e.target;
395
+ var a = el && el.closest ? el.closest('a[href]') : null;
396
+ if (!a) return;
397
+ // A handler of the page's own that already cancelled this click owns
398
+ // it (a toggle, a hash router); the bridge stays out of its way.
399
+ if (e.defaultPrevented) return;
400
+ // Cancelled even when there is nowhere to go: left to the browser, an
401
+ // empty href reloads the frame against the app's URL, as '#…' would.
402
+ e.preventDefault();
403
+ var href = normalize(a.getAttribute('href') || '');
404
+ if (!href) return;
405
+ if (e.button === 1 || e.ctrlKey || e.metaKey || e.shiftKey) {
406
+ parent.postMessage({ type: 'bevel.navigate', href: href, newTab: true }, '*');
407
+ return;
408
+ }
409
+ navigate(href);
410
+ }
376
411
  if (typeof document !== 'undefined') {
377
- document.addEventListener('click', function (e) {
378
- var el = e.target;
379
- var a = el && el.closest ? el.closest('a[href]') : null;
380
- if (!a) return;
381
- // A handler of the page's own that already cancelled this click owns
382
- // it (a toggle, a hash router); the bridge stays out of its way.
383
- if (e.defaultPrevented) return;
384
- // Cancelled even when there is nowhere to go: left to the browser, an
385
- // empty href reloads the frame against the app's URL, as '#…' would.
386
- e.preventDefault();
387
- var href = normalize(a.getAttribute('href') || '');
388
- if (!href) return;
389
- navigate(href);
390
- });
412
+ document.addEventListener('click', followLink);
413
+ document.addEventListener('auxclick', followLink);
391
414
  }
392
415
  })();
393
416
  `;
@@ -559,6 +582,14 @@ interface BuildSandboxedHtmlOptions {
559
582
  * way.
560
583
  */
561
584
  toolBridge?: ToolBridgeOption;
585
+ /**
586
+ * The branch the page is viewed on — `window.bevel.branch` inside the frame,
587
+ * so a page that reads its data through the tools and links to what they
588
+ * name does both on the branch it is shown on, rather than on one written
589
+ * into its script. Absent where the host has no branch for the page (the
590
+ * embed, a mail body), where the member is `null`.
591
+ */
592
+ branch?: string;
562
593
  }
563
594
 
564
595
  /**
@@ -569,7 +600,9 @@ interface BuildSandboxedHtmlOptions {
569
600
  */
570
601
  export function buildSandboxedHtml(opts: BuildSandboxedHtmlOptions): string {
571
602
  const lib = opts.libModuleSources.map(stripRelativeImports).join('\n\n');
572
- const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\n`;
603
+ // `branch` is data, not code: serialized as JSON into the literal, so a
604
+ // branch name can hold nothing the script would read as source.
605
+ const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\nglobalThis.bevel.branch = ${JSON.stringify(opts.branch ?? null)};\n`;
573
606
  const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + KEY_BRIDGE + toolBridgeRuntime(opts.toolBridge));
574
607
 
575
608
  // Title and body are content-only — `srcDoc` already isolates them, but we
@@ -67,6 +67,25 @@ export function useOpenPageInPlatform(): (() => void) | null {
67
67
  return useContext(OpenPageInPlatformContext);
68
68
  }
69
69
 
70
+ /**
71
+ * The file a page's links resolve against, for a host whose `filePath` is not
72
+ * a workspace path on this tab's branch — a skill page names its files
73
+ * relative to the skill and reads them from the default branch. Absent, a
74
+ * link resolves against `filePath` on the branch this tab stands on.
75
+ */
76
+ export interface PageLinkHome {
77
+ /** The page's workspace path. */
78
+ path: string;
79
+ /** The branch the page was read from. */
80
+ branch: string;
81
+ }
82
+
83
+ export const PageLinkHomeContext = createContext<PageLinkHome | null>(null);
84
+
85
+ export function usePageLinkHome(): PageLinkHome | null {
86
+ return useContext(PageLinkHomeContext);
87
+ }
88
+
70
89
  /** The five members a page calls, by the name the frame posts. */
71
90
  export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain' | 'uploadFile';
72
91
 
@@ -44,7 +44,8 @@ import rehypeSanitize from 'rehype-sanitize';
44
44
  import rehypeSlug from 'rehype-slug';
45
45
  import { CopyAnchorButton } from './CopyAnchorButton';
46
46
  import { KbImage, type KbImageResolver } from './KbImage';
47
- import { normalizeHref } from '../../../../shared/markdown/hrefs';
47
+ import { isExternalHref, normalizeHref } from '../../../../shared/markdown/hrefs';
48
+ import { KbAppLink, type KbLinkTarget } from './KbAppLink';
48
49
 
49
50
  export type { KbImageResolver, KbImageSource } from './KbImage';
50
51
 
@@ -106,6 +107,14 @@ export interface KbMarkdownComponentOptions {
106
107
  * text rather than falling through as relative-URL links.
107
108
  */
108
109
  onOpenNodeId?: (id: string) => void;
110
+ /**
111
+ * Where an internal `.md` link leads, so its anchor can say so (see
112
+ * {@link KbAppLink}); `onOpenFile` still follows the click. Omitted (the
113
+ * diff, the skill page, the embed) → the anchor carries the href as written.
114
+ */
115
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
116
+ /** The same for an id-link, beside {@link onOpenNodeId}. */
117
+ nodeIdLinkTarget?: (id: string) => KbLinkTarget | null;
109
118
  /**
110
119
  * When provided, each heading gets a hover-revealed button copying
111
120
  * `headingLink(slug)`. Requires {@link KB_REHYPE_PLUGINS} (slug ids); pass it
@@ -137,7 +146,8 @@ export interface KbMarkdownComponentOptions {
137
146
  * WHICH links this surface wants handed to `onOpenFile`, rather than left
138
147
  * to the browser.
139
148
  *
140
- * - `'browser'` (default, the app): the internal `.md` path links only.
149
+ * - `'browser'` (default, the app): the internal `.md` path links, and
150
+ * with a {@link fileLinkTarget} every workspace destination it resolves.
141
151
  * An `http(s)` destination becomes a plain `target="_blank"` anchor,
142
152
  * because in a tab that is exactly right — the browser opens a new tab
143
153
  * and nothing needs intercepting.
@@ -165,6 +175,8 @@ export interface KbMarkdownComponentOptions {
165
175
  export function useKbMarkdownComponents({
166
176
  onOpenFile,
167
177
  onOpenNodeId,
178
+ fileLinkTarget,
179
+ nodeIdLinkTarget,
168
180
  headingLink,
169
181
  onMermaidError = 'error',
170
182
  resolveImage,
@@ -213,39 +225,34 @@ export function useKbMarkdownComponents({
213
225
  // anchor, so a bare id can't fall through as a relative-URL link.
214
226
  if (!onOpenNodeId) return <span {...props}>{children}</span>;
215
227
  return (
216
- <a
228
+ <KbAppLink
217
229
  {...props}
218
230
  href={href}
219
- onClick={(e) => {
220
- e.preventDefault();
221
- onOpenNodeId(href);
222
- }}
223
- className="cursor-pointer"
231
+ target={nodeIdLinkTarget?.(href) ?? null}
232
+ onOpen={() => onOpenNodeId(href)}
224
233
  >
225
234
  {children}
226
- </a>
235
+ </KbAppLink>
227
236
  );
228
237
  }
229
238
  // Legacy/internal path link: a `.md` destination, optionally with a
230
239
  // heading anchor (`Node.md#goal`) — still used by frontmatter `nodeType`.
231
- // External (`http…`) and same-page (`#…`) links fall through to <a>.
232
- if (
233
- onOpenFile &&
234
- href && !href.startsWith('http') && !href.startsWith('#') && /\.md(#|$)/.test(href)
235
- ) {
236
- return (
237
- <a
238
- {...props}
239
- href={href}
240
- onClick={(e) => {
241
- e.preventDefault();
242
- onOpenFile(href);
243
- }}
244
- className="cursor-pointer"
245
- >
246
- {children}
247
- </a>
248
- );
240
+ // External (any scheme, as `resolveKbHref` reads one — not a name
241
+ // that merely starts `http`, like `http-notes.md`) and same-page
242
+ // (`#…`) links fall through to <a>.
243
+ // Where the caller resolves link targets (the app's file page) every
244
+ // other workspace destination is taken too — a page, an image, a PDF —
245
+ // so none of them is left to the browser as a relative URL that
246
+ // replaces the page being read.
247
+ if (onOpenFile && href && !isExternalHref(href) && !normalizeHref(href).startsWith('#')) {
248
+ const target = fileLinkTarget?.(href) ?? null;
249
+ if (target || /\.md(#|$)/.test(href)) {
250
+ return (
251
+ <KbAppLink {...props} href={href} target={target} onOpen={() => onOpenFile(href)}>
252
+ {children}
253
+ </KbAppLink>
254
+ );
255
+ }
249
256
  }
250
257
  // A surface that owns every outgoing link takes the rest: an
251
258
  // `http(s)` address, and a workspace path the `.md` rule above did
@@ -308,5 +315,5 @@ export function useKbMarkdownComponents({
308
315
  return <pre {...props}>{children}</pre>;
309
316
  },
310
317
  };
311
- }, [onOpenFile, onOpenNodeId, headingLink, onMermaidError, resolveImage, linkPolicy]);
318
+ }, [onOpenFile, onOpenNodeId, fileLinkTarget, nodeIdLinkTarget, headingLink, onMermaidError, resolveImage, linkPolicy]);
312
319
  }
@@ -0,0 +1,35 @@
1
+ /** Decode a URL hash (`#some%20slug`) to its bare slug, tolerating bad escapes. */
2
+ function safeDecodeHash(hash: string): string {
3
+ const raw = hash.replace(/^#/, '');
4
+ try {
5
+ return decodeURIComponent(raw);
6
+ } catch {
7
+ return raw;
8
+ }
9
+ }
10
+
11
+ /** Escape a slug for safe interpolation into an attribute-selector string. */
12
+ function escapeForSelector(value: string): string {
13
+ return (
14
+ value
15
+ .replace(/["\\]/g, '\\$&')
16
+ // CSS-hex-escape control characters (newline, CR, …): a raw control char in
17
+ // a CSS string is a syntax error that would make querySelector throw. The
18
+ // trailing space terminates the hex escape.
19
+ // eslint-disable-next-line no-control-regex
20
+ .replace(/[\x00-\x1f\x7f]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `)
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Scroll the heading a fragment names (`#goal`, the id rehype-slug gave it)
26
+ * into view inside `container` — the one way a rendered markdown file goes
27
+ * to one of its own sections: the file page on its address's fragment, the
28
+ * skill page on a section link's. A fragment naming nothing does nothing.
29
+ */
30
+ export function scrollToHeading(container: ParentNode | null, hash: string): void {
31
+ const slug = hash ? safeDecodeHash(hash) : '';
32
+ if (!slug || !container) return;
33
+ const target = container.querySelector(`[id="${escapeForSelector(slug)}"]`);
34
+ target?.scrollIntoView({ block: 'start' });
35
+ }
@@ -43,6 +43,12 @@ describe('useLinksOut', () => {
43
43
  expect(out).toEqual([]);
44
44
  });
45
45
 
46
+ it('lists a page whose name merely starts with http', () => {
47
+ expect(run('Knowledge/A.md', 'The [notes](http-notes.md).')).toEqual([
48
+ { label: 'notes', target: 'http-notes.md' },
49
+ ]);
50
+ });
51
+
46
52
  it('lists a destination once however many times it is linked', () => {
47
53
  const out = run('Knowledge/A.md', '[One](Same.md) then [again](Same.md).');
48
54
  expect(out).toEqual([{ label: 'One', target: 'Same.md' }]);