@bevel-software/platform-core-frontend 0.30.0 → 0.31.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 (43) hide show
  1. package/package.json +2 -2
  2. package/src/{modules/access/__tests__ → __tests__}/tailwindDeclarations.ts +1 -1
  3. package/src/__tests__/title-ink-room.ts +30 -0
  4. package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +1 -1
  5. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +35 -2
  6. package/src/modules/audit/components/AuditEventsPanel.tsx +2 -1
  7. package/src/modules/audit/components/AuditLogPage.tsx +20 -12
  8. package/src/modules/audit/services/audit.api.ts +6 -4
  9. package/src/modules/embed/__tests__/EmbedView.test.tsx +20 -0
  10. package/src/modules/embed/components/EmbedView.tsx +2 -0
  11. package/src/modules/git/index.ts +3 -0
  12. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +50 -0
  13. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +37 -0
  14. package/src/modules/library/__tests__/SkillPage.test.tsx +44 -1
  15. package/src/modules/library/__tests__/ToolPage.test.tsx +8 -0
  16. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +25 -0
  17. package/src/modules/library/components/LibraryPage.tsx +2 -2
  18. package/src/modules/library/components/LockedPluginView.tsx +2 -2
  19. package/src/modules/library/components/PersonalPluginPage.tsx +5 -4
  20. package/src/modules/library/components/PluginPage.tsx +7 -4
  21. package/src/modules/library/components/skill-page/SkillFilePane.tsx +11 -1
  22. package/src/modules/library/components/skill-page/SkillPage.tsx +12 -2
  23. package/src/modules/library/components/tool-page/ToolPage.tsx +8 -4
  24. package/src/modules/library/routes/WorkspaceItemRoute.tsx +8 -2
  25. package/src/modules/workspace/components/FileViewer.tsx +6 -1
  26. package/src/modules/workspace/components/KbPageHeader.tsx +7 -4
  27. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +7 -0
  28. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +164 -4
  29. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +1 -0
  30. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +272 -0
  31. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +1 -0
  32. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +44 -3
  33. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +62 -0
  34. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +232 -0
  35. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +29 -1
  36. package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +1 -0
  37. package/src/modules/workspace/components/renderers/htmlSandbox.ts +92 -1
  38. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +383 -0
  39. package/src/modules/workspace/components/renderers/rendererSurface.ts +6 -0
  40. package/src/modules/workspace/index.ts +9 -2
  41. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +7 -0
  42. package/src/modules/workspace/routing/kb-routes.ts +33 -1
  43. package/src/shared/theme/header.ts +20 -0
@@ -0,0 +1,272 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import { RendererSurfaceContext, getFileRenderer, type RendererSurface } from '..';
5
+ import { OpenPageInPlatformContext, PageToolsContext } from '../htmlToolBridge';
6
+ import { GitContext, type GitContextValue } from '../../../../git';
7
+ import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
8
+
9
+ /**
10
+ * `window.bevel.tools` as the app gives it: present on the file page, `null`
11
+ * everywhere else, and the two cards — consent to write, and the way to the
12
+ * platform — drawn by the app around the frame, driven here by the very
13
+ * messages the frame's runtime posts.
14
+ */
15
+
16
+ const HtmlRenderer = getFileRenderer('Dashboards/Roadmap.html');
17
+ const PATH = 'knowledge-base/Dashboards/Roadmap.html';
18
+ const PAGE = 'Dashboards/Roadmap.html';
19
+
20
+ const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
21
+ const git = { status: { branch: 'main' } } as unknown as GitContextValue;
22
+
23
+ /** The page on the app's file page: in the app, with the file page's provider. */
24
+ function onFilePage({ readOnly = true }: { readOnly?: boolean } = {}) {
25
+ return render(
26
+ <MemoryRouter initialEntries={['/workspace/main/knowledge-base/Dashboards/Roadmap.html']}>
27
+ <WorkspaceContext.Provider value={workspace}>
28
+ <GitContext.Provider value={git}>
29
+ <PageToolsContext.Provider value={{ pagePath: PAGE }}>
30
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly={readOnly} />
31
+ </PageToolsContext.Provider>
32
+ </GitContext.Provider>
33
+ </WorkspaceContext.Provider>
34
+ </MemoryRouter>,
35
+ );
36
+ }
37
+
38
+ /** The page in the app but not on the file page — a skill page, a history preview. */
39
+ function inAppElsewhere() {
40
+ return render(
41
+ <MemoryRouter initialEntries={['/workspace/main']}>
42
+ <WorkspaceContext.Provider value={workspace}>
43
+ <GitContext.Provider value={git}>
44
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly />
45
+ </GitContext.Provider>
46
+ </WorkspaceContext.Provider>
47
+ </MemoryRouter>,
48
+ );
49
+ }
50
+
51
+ /** The page on the embed — a surface, even with a page-tools provider somewhere above. */
52
+ function onEmbed(openFilePage: (path: string) => void, openWorkspacePath: (path: string) => void = () => undefined) {
53
+ const surface: RendererSurface = {
54
+ kbDirName: 'knowledge-base',
55
+ openLink: () => undefined,
56
+ openWorkspacePath,
57
+ openFilePage,
58
+ openNodeId: () => undefined,
59
+ canonicalUrlFor: () => null,
60
+ rawUrl: (path) => `/raw/${path}`,
61
+ rawFetch: async () => new Response(''),
62
+ offersDownload: false,
63
+ };
64
+ return render(
65
+ <MemoryRouter>
66
+ <PageToolsContext.Provider value={{ pagePath: PAGE }}>
67
+ <RendererSurfaceContext.Provider value={surface}>
68
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly />
69
+ </RendererSurfaceContext.Provider>
70
+ </PageToolsContext.Provider>
71
+ </MemoryRouter>,
72
+ );
73
+ }
74
+
75
+ async function frameOf(container: HTMLElement): Promise<HTMLIFrameElement> {
76
+ return waitFor(() => {
77
+ const el = container.querySelector('iframe');
78
+ if (!el) throw new Error('no frame yet');
79
+ return el;
80
+ });
81
+ }
82
+
83
+ /** Post `data` as the frame would, and collect what the app posts back to it. */
84
+ function frameChannel(iframe: HTMLIFrameElement) {
85
+ const win = iframe.contentWindow!;
86
+ const replies: Array<Record<string, unknown>> = [];
87
+ vi.spyOn(win, 'postMessage').mockImplementation(((msg: Record<string, unknown>) => void replies.push(msg)) as never);
88
+ return {
89
+ replies,
90
+ post: (data: unknown) => window.dispatchEvent(new MessageEvent('message', { data, source: win })),
91
+ };
92
+ }
93
+
94
+ /** The hosted server and the manual, as the app's fetch sees them. */
95
+ function stubServer() {
96
+ const mcp: string[] = [];
97
+ vi.stubGlobal(
98
+ 'fetch',
99
+ vi.fn(async (url: string, init?: RequestInit) => {
100
+ if (url === '/api/agent/utcp') return Response.json({ tools: [{ name: 'read_file', tags: [] }, { name: 'edit_file', tags: ['write'] }] });
101
+ if (url === '/api/mcp/page-refusals') return new Response(null, { status: 204 });
102
+ const body = JSON.parse(String(init!.body)) as { id: number; params: { name: string } };
103
+ mcp.push(body.params.name);
104
+ return Response.json({
105
+ jsonrpc: '2.0',
106
+ id: body.id,
107
+ result: { content: [{ type: 'text', text: JSON.stringify({ ran: body.params.name }) }] },
108
+ });
109
+ }),
110
+ );
111
+ return { mcp };
112
+ }
113
+
114
+ afterEach(() => {
115
+ cleanup();
116
+ vi.restoreAllMocks();
117
+ vi.unstubAllGlobals();
118
+ });
119
+
120
+ describe('window.bevel.tools on the file page and elsewhere', () => {
121
+ it('gives the page the four functions on the file page', async () => {
122
+ const { container } = onFilePage();
123
+ const srcdoc = (await frameOf(container)).getAttribute('srcdoc')!;
124
+ expect(srcdoc).toContain('globalThis.bevel.tools = Object.freeze({');
125
+ for (const fn of ['searchTools', 'toolsInfo', 'callTool', 'callToolChain']) expect(srcdoc).toContain(`${fn}: function`);
126
+ });
127
+
128
+ it('gives it null on the embed and on any other preview in the app', async () => {
129
+ const embed = onEmbed(() => undefined);
130
+ expect((await frameOf(embed.container)).getAttribute('srcdoc')).toContain('globalThis.bevel.tools = null;');
131
+ cleanup();
132
+ const elsewhere = inAppElsewhere();
133
+ expect((await frameOf(elsewhere.container)).getAttribute('srcdoc')).toContain('globalThis.bevel.tools = null;');
134
+ });
135
+ });
136
+
137
+ describe('the consent card on the file page', () => {
138
+ it('runs a read with no card', async () => {
139
+ const server = stubServer();
140
+ const { container } = onFilePage();
141
+ const frame = frameChannel(await frameOf(container));
142
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
143
+ await waitFor(() => expect(frame.replies).toEqual([{ type: 'bevel.tool.response', requestId: 'r1', ok: true, result: { ran: 'read_file' } }]));
144
+ expect(server.mcp).toEqual(['read_file']);
145
+ expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
146
+ });
147
+
148
+ it('asks on the first write with the page\'s name and path; Allow runs it and holds for the view', async () => {
149
+ const server = stubServer();
150
+ const { container } = onFilePage();
151
+ const frame = frameChannel(await frameOf(container));
152
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
153
+ expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
154
+ expect(screen.getByText(PAGE)).toBeTruthy();
155
+ expect(server.mcp).toEqual([]);
156
+
157
+ fireEvent.click(screen.getByRole('button', { name: 'Allow while open' }));
158
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true, result: { ran: 'edit_file' } }));
159
+
160
+ frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callToolChain', args: ['return 1'] });
161
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
162
+ expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
163
+ expect(server.mcp).toEqual(['edit_file', 'call_tool_chain']);
164
+ });
165
+
166
+ it('Deny answers denied and runs nothing; the next write asks again; a reload asks again after an Allow', async () => {
167
+ const server = stubServer();
168
+ const { container } = onFilePage();
169
+ const frame = frameChannel(await frameOf(container));
170
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
171
+ fireEvent.click(await screen.findByRole('button', { name: 'Deny' }));
172
+ await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'w1', ok: false, error: 'denied', code: 'denied' }));
173
+ expect(server.mcp).toEqual([]);
174
+
175
+ frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
176
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
177
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
178
+
179
+ // Reload the page: a new view, a new frame window, and the card again.
180
+ fireEvent.click(screen.getByTitle('Reload preview'));
181
+ const reloaded = frameChannel(await waitFor(() => {
182
+ const el = container.querySelector('iframe')!;
183
+ if (el.contentWindow === null) throw new Error('not yet');
184
+ return el;
185
+ }));
186
+ reloaded.post({ type: 'bevel.tool.call', requestId: 'w3', fn: 'callTool', args: ['edit_file', {}] });
187
+ expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
188
+ });
189
+
190
+ it('asks again after Edit and back to Preview, though the document is the same', async () => {
191
+ stubServer();
192
+ const { container } = onFilePage({ readOnly: false });
193
+ const frame = frameChannel(await frameOf(container));
194
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
195
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
196
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
197
+
198
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
199
+ await waitFor(() => expect(container.querySelector('iframe')).toBeNull());
200
+ fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
201
+ const back = frameChannel(await frameOf(container));
202
+ back.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
203
+ expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
204
+ });
205
+
206
+ it('answers requireTools true with nothing shown', async () => {
207
+ const { container } = onFilePage();
208
+ const frame = frameChannel(await frameOf(container));
209
+ frame.post({ type: 'bevel.tools.require', requestId: 'q1' });
210
+ await waitFor(() => expect(frame.replies).toEqual([{ type: 'bevel.tools.require.response', requestId: 'q1', ok: true, result: true }]));
211
+ expect(screen.queryByRole('dialog')).toBeNull();
212
+ });
213
+ });
214
+
215
+ describe('the platform card where there are no tools', () => {
216
+ it('on the embed offers Continue without tools (false) and Open in the platform (opens the page, false)', async () => {
217
+ const openFilePage = vi.fn();
218
+ const openWorkspacePath = vi.fn();
219
+ const { container } = onEmbed(openFilePage, openWorkspacePath);
220
+ const frame = frameChannel(await frameOf(container));
221
+
222
+ frame.post({ type: 'bevel.tools.require', requestId: 'q1' });
223
+ expect(await screen.findByText('Roadmap uses tools that are only available in the platform')).toBeTruthy();
224
+ fireEvent.click(screen.getByRole('button', { name: 'Continue without tools' }));
225
+ await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tools.require.response', requestId: 'q1', ok: true, result: false }));
226
+ expect(openFilePage).not.toHaveBeenCalled();
227
+
228
+ frame.post({ type: 'bevel.tools.require', requestId: 'q2' });
229
+ fireEvent.click(await screen.findByRole('button', { name: 'Open in the platform' }));
230
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'q2', result: false }));
231
+ // The FILE PAGE verb, not the plain path: the embed opens a new tab, and
232
+ // a page in a skill's folder would otherwise open as the skill page.
233
+ expect(openFilePage).toHaveBeenCalledWith(PATH);
234
+ expect(openWorkspacePath).not.toHaveBeenCalled();
235
+ });
236
+
237
+ it("on a skill page opens the page the host's way, not the skill-relative name", async () => {
238
+ const open = vi.fn();
239
+ const { container } = render(
240
+ <MemoryRouter initialEntries={['/skills-and-tools/skills/roadmap']}>
241
+ <WorkspaceContext.Provider value={workspace}>
242
+ <GitContext.Provider value={git}>
243
+ <OpenPageInPlatformContext.Provider value={open}>
244
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath="view.html" onSave={async () => undefined} readOnly />
245
+ </OpenPageInPlatformContext.Provider>
246
+ </GitContext.Provider>
247
+ </WorkspaceContext.Provider>
248
+ </MemoryRouter>,
249
+ );
250
+ const frame = frameChannel(await frameOf(container));
251
+ frame.post({ type: 'bevel.tools.require', requestId: 'q1' });
252
+ expect(await screen.findByText('view uses tools that are only available in the platform')).toBeTruthy();
253
+ fireEvent.click(screen.getByRole('button', { name: 'Open in the platform' }));
254
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'q1', result: false }));
255
+ expect(open).toHaveBeenCalledTimes(1);
256
+ });
257
+
258
+ it('refuses a tool call outright where there are no tools', async () => {
259
+ const { container } = onEmbed(() => undefined);
260
+ const frame = frameChannel(await frameOf(container));
261
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
262
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'r1', ok: false, code: 'unavailable' }));
263
+ });
264
+
265
+ it('ignores messages that do not come from its own frame', async () => {
266
+ const { container } = onEmbed(() => undefined);
267
+ await frameOf(container);
268
+ window.dispatchEvent(new MessageEvent('message', { data: { type: 'bevel.tools.require', requestId: 'x' }, source: window }));
269
+ await new Promise((r) => setTimeout(r, 10));
270
+ expect(screen.queryByText(/only available in the platform/)).toBeNull();
271
+ });
272
+ });
@@ -18,6 +18,7 @@ const SURFACE: RendererSurface = {
18
18
  kbDirName: 'knowledge-base',
19
19
  openLink: () => undefined,
20
20
  openWorkspacePath: () => undefined,
21
+ openFilePage: () => undefined,
21
22
  openNodeId: () => undefined,
22
23
  canonicalUrlFor: () => null,
23
24
  rawUrl: () => '',
@@ -1,4 +1,5 @@
1
1
  import vm from 'node:vm';
2
+ import { onTestFinished } from 'vitest';
2
3
  import { buildSandboxedHtml } from '../htmlSandbox';
3
4
 
4
5
  /**
@@ -28,6 +29,12 @@ export interface BridgeRun {
28
29
  scrolledTags: string[];
29
30
  /** How many times the page was scrolled to its top. */
30
31
  scrolledToTop: () => number;
32
+ /**
33
+ * Deliver a message to the frame's window, as the parent posting it
34
+ * (`fromParent: false` — anything else, such as the page posting to itself).
35
+ * Answers once the frame's handlers and the promises they settle have run.
36
+ */
37
+ deliver: (data: unknown, opts?: { fromParent?: boolean }) => Promise<void>;
31
38
  }
32
39
 
33
40
  /**
@@ -35,10 +42,13 @@ export interface BridgeRun {
35
42
  * `namedControls` are `<input name="…">` fields, which a fragment must NOT
36
43
  * scroll to — the standard's fallback is the named anchor alone.
37
44
  */
38
- export function runBridge(page: { ids?: string[]; names?: string[]; namedControls?: string[] } = {}): BridgeRun {
45
+ export function runBridge(
46
+ page: { ids?: string[]; names?: string[]; namedControls?: string[] } = {},
47
+ opts: { toolBridge?: boolean } = {},
48
+ ): BridgeRun {
39
49
  // No lib sources: a vm script cannot parse an `export`. The bridge is
40
50
  // appended after the lib either way.
41
- const out = buildSandboxedHtml({ title: 't', libModuleSources: [], bodyHtml: '' });
51
+ const out = buildSandboxedHtml({ title: 't', libModuleSources: [], bodyHtml: '', toolBridge: opts.toolBridge });
42
52
  const scriptBody = out.match(/<script type="module">([\s\S]*?)<\/script>/)![1];
43
53
 
44
54
  type ClickEvent = { target: { closest: () => unknown }; defaultPrevented: boolean; preventDefault: () => void };
@@ -57,7 +67,33 @@ export function runBridge(page: { ids?: string[]; names?: string[]; namedControl
57
67
  const ids = new Set(page.ids ?? []);
58
68
  const names = new Set(page.names ?? []);
59
69
  const controls = new Set(page.namedControls ?? []);
70
+ const messageHandlers: ((e: { source: unknown; data: unknown }) => void)[] = [];
71
+ const parent = { postMessage: (msg: unknown) => posted.push(msg) };
72
+ // The frame's request timers, cleared when the test ends: a call a test
73
+ // leaves unanswered must not keep the worker alive for the runtime's
74
+ // fifteen minutes, nor reject long after the test that made it.
75
+ const timers = new Set<ReturnType<typeof setTimeout>>();
76
+ onTestFinished(() => {
77
+ for (const t of timers) clearTimeout(t);
78
+ timers.clear();
79
+ });
60
80
  const ctx: Record<string, unknown> = {
81
+ // The frame's window: the tool bridge listens on it for the parent's answers.
82
+ addEventListener: (type: string, fn: (e: { source: unknown; data: unknown }) => void) => {
83
+ if (type === 'message') messageHandlers.push(fn);
84
+ },
85
+ setTimeout: (fn: () => void, ms?: number) => {
86
+ const t = setTimeout(() => {
87
+ timers.delete(t);
88
+ fn();
89
+ }, ms);
90
+ timers.add(t);
91
+ return t;
92
+ },
93
+ clearTimeout: (t: ReturnType<typeof setTimeout>) => {
94
+ timers.delete(t);
95
+ clearTimeout(t);
96
+ },
61
97
  document: {
62
98
  addEventListener: (type: string, fn: (e: ClickEvent) => void) => {
63
99
  if (type === 'click') handlers.push(fn);
@@ -70,7 +106,7 @@ export function runBridge(page: { ids?: string[]; names?: string[]; namedControl
70
106
  ...(names.has(name) ? [element(name, 'A')] : []),
71
107
  ],
72
108
  },
73
- parent: { postMessage: (msg: unknown) => posted.push(msg) },
109
+ parent,
74
110
  scrollTo: () => {
75
111
  toTop += 1;
76
112
  },
@@ -95,5 +131,10 @@ export function runBridge(page: { ids?: string[]; names?: string[]; namedControl
95
131
  scrolled,
96
132
  scrolledTags,
97
133
  scrolledToTop: () => toTop,
134
+ deliver: async (data, deliverOpts = {}) => {
135
+ const source = deliverOpts.fromParent === false ? {} : parent;
136
+ for (const fn of messageHandlers) fn({ source, data });
137
+ await new Promise((r) => setTimeout(r, 0));
138
+ },
98
139
  };
99
140
  }
@@ -598,3 +598,65 @@ describe('buildSandboxedHtml', () => {
598
598
  expect(ctx.__coreLibRan).toBe(true);
599
599
  });
600
600
  });
601
+
602
+ describe('window.bevel.tools in the frame', () => {
603
+ type Tools = Record<'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain', (...a: unknown[]) => Promise<unknown>>;
604
+ const toolsOf = (bridge: ReturnType<typeof runBridge>) => bridge.bevel.tools as Tools | null;
605
+
606
+ it('has the four functions where the app answers tools, each posting a call with a request id', async () => {
607
+ const bridge = runBridge({}, { toolBridge: true });
608
+ const tools = toolsOf(bridge)!;
609
+ expect(Object.keys(tools).sort()).toEqual(['callTool', 'callToolChain', 'searchTools', 'toolsInfo']);
610
+ void tools.searchTools('change request');
611
+ void tools.toolsInfo(['read_file']);
612
+ void tools.callTool('read_file', { body: { path: 'a.md' } });
613
+ void tools.callToolChain('return 1');
614
+ const posted = bridge.posted as Array<{ type: string; requestId: string; fn: string; args: unknown[] }>;
615
+ expect(posted.map((m) => [m.type, m.fn, m.args])).toEqual([
616
+ ['bevel.tool.call', 'searchTools', ['change request']],
617
+ ['bevel.tool.call', 'toolsInfo', [['read_file']]],
618
+ ['bevel.tool.call', 'callTool', ['read_file', { body: { path: 'a.md' } }]],
619
+ ['bevel.tool.call', 'callToolChain', ['return 1']],
620
+ ]);
621
+ expect(new Set(posted.map((m) => m.requestId)).size).toBe(4);
622
+ });
623
+
624
+ it("resolves with the parent's answer and rejects with its error and code, matched by request id", async () => {
625
+ const bridge = runBridge({}, { toolBridge: true });
626
+ const tools = toolsOf(bridge)!;
627
+ const read = tools.callTool('read_file', {});
628
+ const write = tools.callTool('edit_file', {});
629
+ const [readMsg, writeMsg] = bridge.posted as Array<{ requestId: string }>;
630
+ // Handled before the answer arrives, so the rejection is never unhandled.
631
+ const writeRejects = expect(write).rejects.toMatchObject({ message: 'denied', code: 'denied' });
632
+ await bridge.deliver({ type: 'bevel.tool.response', requestId: writeMsg!.requestId, ok: false, error: 'denied', code: 'denied' });
633
+ await bridge.deliver({ type: 'bevel.tool.response', requestId: readMsg!.requestId, ok: true, result: { content: 'hi' } });
634
+ await expect(read).resolves.toEqual({ content: 'hi' });
635
+ await writeRejects;
636
+ });
637
+
638
+ it('believes no answer that does not come from the parent', async () => {
639
+ const bridge = runBridge({}, { toolBridge: true });
640
+ let settled = false;
641
+ void toolsOf(bridge)!.callTool('read_file', {}).finally(() => (settled = true));
642
+ const [msg] = bridge.posted as Array<{ requestId: string }>;
643
+ await bridge.deliver({ type: 'bevel.tool.response', requestId: msg!.requestId, ok: true, result: 'forged' }, { fromParent: false });
644
+ expect(settled).toBe(false);
645
+ });
646
+
647
+ it('is null where the app answers no tools, and requireTools asks the parent and resolves with its answer', async () => {
648
+ const bridge = runBridge();
649
+ expect(bridge.bevel.tools).toBeNull();
650
+ const required = (bridge.bevel.requireTools as () => Promise<boolean>)();
651
+ const [msg] = bridge.posted as Array<{ type: string; requestId: string }>;
652
+ expect(msg!.type).toBe('bevel.tools.require');
653
+ await bridge.deliver({ type: 'bevel.tools.require.response', requestId: msg!.requestId, ok: true, result: false });
654
+ await expect(required).resolves.toBe(false);
655
+
656
+ const onFilePage = runBridge({}, { toolBridge: true });
657
+ const yes = (onFilePage.bevel.requireTools as () => Promise<boolean>)();
658
+ const [ask] = onFilePage.posted as Array<{ requestId: string }>;
659
+ await onFilePage.deliver({ type: 'bevel.tools.require.response', requestId: ask!.requestId, ok: true, result: true });
660
+ await expect(yes).resolves.toBe(true);
661
+ });
662
+ });
@@ -0,0 +1,232 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ DENIED,
4
+ MANUAL_TTL_MS,
5
+ PageConsent,
6
+ PageToolsClient,
7
+ answerToolCall,
8
+ asToolCall,
9
+ pageName,
10
+ type ToolCallMessage,
11
+ } from '../htmlToolBridge';
12
+
13
+ /**
14
+ * The app's half of `window.bevel.tools`: the MCP calls a page's calls become,
15
+ * the rule for which of them ask the viewer first, and the consent that holds
16
+ * for one view of the page.
17
+ */
18
+
19
+ const PAGE = 'Dashboards/Roadmap.html';
20
+
21
+ /** The deployment's UTCP manual: `read_file` reads, `edit_file` and `write_file` write. */
22
+ const MANUAL = {
23
+ tools: [
24
+ { name: 'read_file', tags: [] },
25
+ { name: 'edit_file', tags: ['write'] },
26
+ { name: 'write_file', tags: ['write'] },
27
+ ],
28
+ };
29
+
30
+ interface Sent {
31
+ url: string;
32
+ headers: Headers;
33
+ body: { method?: string; params?: { name: string; arguments: unknown }; page?: string; tool?: string };
34
+ }
35
+
36
+ /** A stand-in for the app's fetch: the manual, the MCP endpoint and the refusal route. */
37
+ function fakeServer(answer: (name: string, args: unknown) => unknown = (name) => ({ ran: name }), opts: { sse?: boolean } = {}) {
38
+ const sent: Sent[] = [];
39
+ const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => {
40
+ const body = init?.body ? JSON.parse(String(init.body)) : {};
41
+ sent.push({ url, headers: new Headers(init?.headers), body });
42
+ if (url === '/api/agent/utcp') return Response.json(MANUAL);
43
+ if (url === '/api/mcp/page-refusals') return new Response(null, { status: 204 });
44
+ const result = answer(body.params.name, body.params.arguments);
45
+ const message = { jsonrpc: '2.0', id: body.id, result };
46
+ if (opts.sse) {
47
+ return new Response(`event: message\ndata: ${JSON.stringify(message)}\n\n`, {
48
+ headers: { 'content-type': 'text/event-stream' },
49
+ });
50
+ }
51
+ return Response.json(message);
52
+ });
53
+ const mcpCalls = () => sent.filter((s) => s.url === '/api/mcp').map((s) => s.body.params!.name);
54
+ return { sent, fetchImpl, mcpCalls };
55
+ }
56
+
57
+ /** A tool result carrying `value` as JSON text, the way the hosted server answers. */
58
+ const text = (value: unknown) => ({ content: [{ type: 'text', text: JSON.stringify(value) }] });
59
+
60
+ const call = (fn: ToolCallMessage['fn'], ...args: unknown[]): ToolCallMessage => ({
61
+ type: 'bevel.tool.call',
62
+ requestId: `r-${Math.random()}`,
63
+ fn,
64
+ args,
65
+ });
66
+
67
+ describe('PageToolsClient', () => {
68
+ it("calls the hosted MCP server as the page, and answers with the tool's own result", async () => {
69
+ const server = fakeServer((name) => text({ ran: name }), { sse: true });
70
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
71
+ await expect(client.callTool('read_file', { body: { path: 'a.md' } })).resolves.toEqual({ ran: 'read_file' });
72
+ const [sent] = server.sent;
73
+ expect(sent!.body).toMatchObject({ method: 'tools/call', params: { name: 'read_file', arguments: { body: { path: 'a.md' } } } });
74
+ expect(decodeURIComponent(sent!.headers.get('X-Bevel-Page')!)).toBe(PAGE);
75
+ });
76
+
77
+ it("rejects with the tool's own refusal, as tools/call answers it", async () => {
78
+ const server = fakeServer(() => ({ isError: true, content: [{ type: 'text', text: 'You don\'t have read access to "a.md"' }] }));
79
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
80
+ await expect(client.callTool('read_file', {})).rejects.toThrow('You don\'t have read access to "a.md"');
81
+ });
82
+
83
+ it('maps searchTools and toolsInfo onto list_tools and tools_info', async () => {
84
+ const server = fakeServer((name, args) =>
85
+ name === 'list_tools'
86
+ ? text({ tools: ['KNOWLEDGE_BASE.list_change_requests', 'KNOWLEDGE_BASE.get_change_request', 'KNOWLEDGE_BASE.read_file'] })
87
+ : text({ interfaces: `for ${JSON.stringify(args)}`, not_found: [] }),
88
+ );
89
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
90
+ await expect(client.searchTools('change request')).resolves.toEqual({
91
+ tools: ['KNOWLEDGE_BASE.list_change_requests', 'KNOWLEDGE_BASE.get_change_request'],
92
+ });
93
+ await expect(client.searchTools('')).resolves.toMatchObject({ tools: expect.arrayContaining(['KNOWLEDGE_BASE.read_file']) });
94
+ await expect(client.toolsInfo(['read_file'])).resolves.toEqual({
95
+ interfaces: 'for {"tool_names":["read_file"]}',
96
+ not_found: [],
97
+ });
98
+ expect(server.mcpCalls()).toEqual(['list_tools', 'list_tools', 'tools_info']);
99
+ });
100
+
101
+ it('counts as writing a write-tagged tool, a tool the manual does not list, and every chain — never a read', async () => {
102
+ const client = new PageToolsClient(PAGE, fakeServer().fetchImpl);
103
+ expect(await client.mayWrite('callTool', ['read_file', {}])).toBe(false);
104
+ expect(await client.mayWrite('searchTools', ['x'])).toBe(false);
105
+ expect(await client.mayWrite('toolsInfo', [['x']])).toBe(false);
106
+ expect(await client.mayWrite('callTool', ['list_tools', {}])).toBe(false);
107
+ expect(await client.mayWrite('callTool', ['edit_file', {}])).toBe(true);
108
+ expect(await client.mayWrite('callTool', ['notion_search', {}])).toBe(true);
109
+ expect(await client.mayWrite('callToolChain', ['return 1'])).toBe(true);
110
+ expect(await client.mayWrite('callTool', ['call_tool_chain', { code: 'x' }])).toBe(true);
111
+ });
112
+
113
+ it('reads the manual again once it is a minute old, so a tool retagged write asks', async () => {
114
+ let tags: string[] = [];
115
+ let reads = 0;
116
+ let now = 1_000_000;
117
+ const fetchImpl = async (url: string) => {
118
+ if (url !== '/api/agent/utcp') throw new Error(`unexpected ${url}`);
119
+ reads += 1;
120
+ return Response.json({ tools: [{ name: 'publish', tags }] });
121
+ };
122
+ const client = new PageToolsClient(PAGE, fetchImpl, () => now);
123
+ expect(await client.mayWrite('callTool', ['publish', {}])).toBe(false);
124
+ tags = ['write'];
125
+ now += MANUAL_TTL_MS - 1;
126
+ expect(await client.mayWrite('callTool', ['publish', {}])).toBe(false);
127
+ expect(reads).toBe(1);
128
+ now += 1;
129
+ expect(await client.mayWrite('callTool', ['publish', {}])).toBe(true);
130
+ expect(reads).toBe(2);
131
+ });
132
+
133
+ it('counts everything but the reading meta-tools as writing when the manual cannot be read', async () => {
134
+ const client = new PageToolsClient(PAGE, async () => new Response('', { status: 500 }));
135
+ expect(await client.mayWrite('callTool', ['read_file', {}])).toBe(true);
136
+ expect(await client.mayWrite('searchTools', ['x'])).toBe(false);
137
+ });
138
+ });
139
+
140
+ describe('answering a page: reads at once, the first write asks', () => {
141
+ function setup() {
142
+ const server = fakeServer((name) => text({ ran: name }));
143
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
144
+ let answer: (ok: boolean) => void = () => {};
145
+ const ask = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));
146
+ const consent = new PageConsent(ask);
147
+ return { server, client, consent, ask, answer: (ok: boolean) => answer(ok) };
148
+ }
149
+
150
+ it('runs a read with no card', async () => {
151
+ const { client, consent, ask, server } = setup();
152
+ const res = await answerToolCall(call('callTool', 'read_file', { body: { path: 'a.md' } }), client, consent);
153
+ expect(res).toMatchObject({ ok: true, result: { ran: 'read_file' } });
154
+ expect(ask).not.toHaveBeenCalled();
155
+ expect(server.mcpCalls()).toEqual(['read_file']);
156
+ });
157
+
158
+ it('asks on the first write; Allow runs it, and later writes run without asking', async () => {
159
+ const { client, consent, ask, answer, server } = setup();
160
+ const first = answerToolCall(call('callTool', 'edit_file', {}), client, consent);
161
+ await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
162
+ // Nothing runs while the card is open — a read included.
163
+ const read = answerToolCall(call('callTool', 'read_file', {}), client, consent);
164
+ await new Promise((r) => setTimeout(r, 10));
165
+ expect(server.mcpCalls()).toEqual([]);
166
+ answer(true);
167
+ expect(await first).toMatchObject({ ok: true, result: { ran: 'edit_file' } });
168
+ expect(await read).toMatchObject({ ok: true });
169
+ expect(await answerToolCall(call('callTool', 'write_file', {}), client, consent)).toMatchObject({ ok: true });
170
+ expect(await answerToolCall(call('callToolChain', 'return 1'), client, consent)).toMatchObject({ ok: true });
171
+ expect(ask).toHaveBeenCalledTimes(1);
172
+ });
173
+
174
+ it('Deny answers `denied`, runs nothing, reports the refusal, and the next write asks again', async () => {
175
+ const { client, consent, ask, answer, server } = setup();
176
+ const denied = answerToolCall(call('callTool', 'edit_file', { body: { path: 'a.md' } }), client, consent);
177
+ await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
178
+ answer(false);
179
+ expect(await denied).toMatchObject({ ok: false, error: DENIED, code: DENIED });
180
+ expect(server.mcpCalls()).toEqual([]);
181
+ await vi.waitFor(() =>
182
+ expect(server.sent.find((s) => s.url === '/api/mcp/page-refusals')?.body).toEqual({
183
+ page: PAGE,
184
+ tool: 'edit_file',
185
+ args: { body: { path: 'a.md' } },
186
+ }),
187
+ );
188
+
189
+ void answerToolCall(call('callTool', 'edit_file', {}), client, consent);
190
+ await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(2));
191
+ });
192
+
193
+ it('shows one card for writes that arrive together, and answers every one of them', async () => {
194
+ const { client, consent, ask, answer } = setup();
195
+ const writes = [
196
+ answerToolCall(call('callTool', 'edit_file', {}), client, consent),
197
+ answerToolCall(call('callTool', 'notion_create_page', {}), client, consent),
198
+ answerToolCall(call('callToolChain', 'return 1'), client, consent),
199
+ ];
200
+ await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
201
+ await new Promise((r) => setTimeout(r, 10));
202
+ answer(false);
203
+ expect((await Promise.all(writes)).map((w) => w.ok)).toEqual([false, false, false]);
204
+ expect(ask).toHaveBeenCalledTimes(1);
205
+ });
206
+
207
+ it('asks again in a new view of the page: an Allow holds only until the page is reloaded', async () => {
208
+ const { client, answer } = setup();
209
+ const firstView = new PageConsent(() => Promise.resolve(true));
210
+ await answerToolCall(call('callTool', 'edit_file', {}), client, firstView);
211
+ const ask = vi.fn(() => Promise.resolve(false));
212
+ const reloaded = new PageConsent(ask);
213
+ expect(await answerToolCall(call('callTool', 'edit_file', {}), client, reloaded)).toMatchObject({ ok: false, code: DENIED });
214
+ expect(ask).toHaveBeenCalledTimes(1);
215
+ answer(true);
216
+ });
217
+ });
218
+
219
+ describe('the frame messages the app reads', () => {
220
+ it('accepts only a well-formed call of one of the four functions', () => {
221
+ expect(asToolCall({ type: 'bevel.tool.call', requestId: 'r', fn: 'callTool', args: ['read_file', {}] })).not.toBeNull();
222
+ expect(asToolCall({ type: 'bevel.tool.call', requestId: 'r', fn: 'eval', args: [] })).toBeNull();
223
+ expect(asToolCall({ type: 'bevel.tool.call', fn: 'callTool', args: [] })).toBeNull();
224
+ expect(asToolCall({ type: 'bevel.navigate', href: 'x' })).toBeNull();
225
+ expect(asToolCall(null)).toBeNull();
226
+ });
227
+
228
+ it("names a page by its file name, without the extension", () => {
229
+ expect(pageName('Dashboards/Roadmap.html')).toBe('Roadmap');
230
+ expect(pageName('knowledge-base/Boards/Q4.board.htm')).toBe('Q4.board');
231
+ });
232
+ });