@bevel-software/platform-core-frontend 0.37.0 → 0.38.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 (23) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +21 -2
  3. package/src/lib/api.ts +7 -1
  4. package/src/modules/auth/__tests__/useAuthState.test.ts +92 -0
  5. package/src/modules/auth/hooks/useAuthState.ts +4 -1
  6. package/src/modules/auth/index.ts +2 -0
  7. package/src/modules/auth/state/accountStorage.ts +32 -0
  8. package/src/modules/auth/state/tokenAccount.ts +53 -0
  9. package/src/modules/settings/settings-nav-items.tsx +24 -4
  10. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -5
  11. package/src/modules/toolbar/commands/actions.tsx +1 -0
  12. package/src/modules/toolbar/components/ProfileMenu.tsx +13 -1
  13. package/src/modules/toolbar/components/__tests__/ProfileMenu.app-sections.test.tsx +87 -0
  14. package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +1 -0
  15. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +2 -1
  16. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +80 -32
  17. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +78 -8
  18. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +10 -3
  19. package/src/modules/workspace/components/renderers/__tests__/pageConsentMemory.test.ts +177 -0
  20. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +249 -23
  21. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +52 -16
  22. package/src/modules/workspace/components/renderers/pageConsentMemory.ts +75 -0
  23. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +46 -11
@@ -2,9 +2,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
3
  import { MemoryRouter } from 'react-router-dom';
4
4
  import { OpenPageInPlatformContext, PageToolsContext, RendererSurfaceContext, getFileRenderer, type RendererSurface } from '..';
5
+ import { AuthContext, type AuthContextValue } from '../../../../auth';
5
6
  import { GitContext, type GitContextValue } from '../../../../git';
6
7
  import { clearToken, setToken } from '../../../../../lib/api';
7
8
  import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
9
+ import { sha256Hex } from '@bevel-software/platform-shared';
8
10
  import { frameChannel, stubServer } from './pageToolsHarness';
9
11
 
10
12
  /**
@@ -17,9 +19,25 @@ import { frameChannel, stubServer } from './pageToolsHarness';
17
19
  const HtmlRenderer = getFileRenderer('Dashboards/Roadmap.html');
18
20
  const PATH = 'knowledge-base/Dashboards/Roadmap.html';
19
21
  const PAGE = 'Dashboards/Roadmap.html';
22
+ const CARD = "You're allowing changes using your account. Do you want to allow that?";
20
23
 
21
24
  const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
22
25
  const git = { status: { branch: 'main' } } as unknown as GitContextValue;
26
+ /** The account on the file page, as the app's auth gate carries it above the renderer. */
27
+ const auth = { user: { id: 'user-a' } } as unknown as AuthContextValue;
28
+ /** user-a's session token, as the server signs it: a JWT whose `userId` claim names the account (the signature is not checked here). */
29
+ const VIEWER_SESSION = (() => {
30
+ const part = (value: object) => btoa(JSON.stringify(value)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
31
+ return `${part({ alg: 'HS256', typ: 'JWT' })}.${part({ userId: 'user-a', email: 'user-a@example.com' })}.signature`;
32
+ })();
33
+ /** Where the browser keeps the account's Allow: one entry per digest, holding when it was allowed. */
34
+ const ALLOWED_PAGE_KEY_PREFIX = 'bevel.account/user-a/htmlPage.allowedWrite.';
35
+ /** The digests stored in localStorage, least recently allowed first: read through the storage API, as another tab would. */
36
+ const rememberedDigests = (): string[] =>
37
+ Array.from({ length: window.localStorage.length }, (_, i) => window.localStorage.key(i)!)
38
+ .filter((key) => key.startsWith(ALLOWED_PAGE_KEY_PREFIX) && Number.isFinite(Number(window.localStorage.getItem(key))))
39
+ .sort((a, b) => Number(window.localStorage.getItem(a)) - Number(window.localStorage.getItem(b)))
40
+ .map((key) => key.slice(ALLOWED_PAGE_KEY_PREFIX.length));
23
41
 
24
42
  /**
25
43
  * The page on the app's file page: in the app, with the file page's provider.
@@ -27,16 +45,20 @@ const git = { status: { branch: 'main' } } as unknown as GitContextValue;
27
45
  * save arriving): the same frame, a new document in it.
28
46
  */
29
47
  function onFilePage({ readOnly = true }: { readOnly?: boolean } = {}) {
48
+ // Signed in as user-a: its session token is the stored one.
49
+ setToken(VIEWER_SESSION);
30
50
  const tree = (content: string) => (
31
- <MemoryRouter initialEntries={['/workspace/main/knowledge-base/Dashboards/Roadmap.html']}>
32
- <WorkspaceContext.Provider value={workspace}>
33
- <GitContext.Provider value={git}>
34
- <PageToolsContext.Provider value={{ pagePath: PAGE }}>
35
- <HtmlRenderer content={content} filePath={PATH} onSave={async () => undefined} readOnly={readOnly} />
36
- </PageToolsContext.Provider>
37
- </GitContext.Provider>
38
- </WorkspaceContext.Provider>
39
- </MemoryRouter>
51
+ <AuthContext.Provider value={auth}>
52
+ <MemoryRouter initialEntries={['/workspace/main/knowledge-base/Dashboards/Roadmap.html']}>
53
+ <WorkspaceContext.Provider value={workspace}>
54
+ <GitContext.Provider value={git}>
55
+ <PageToolsContext.Provider value={{ pagePath: PAGE }}>
56
+ <HtmlRenderer content={content} filePath={PATH} onSave={async () => undefined} readOnly={readOnly} />
57
+ </PageToolsContext.Provider>
58
+ </GitContext.Provider>
59
+ </WorkspaceContext.Provider>
60
+ </MemoryRouter>
61
+ </AuthContext.Provider>
40
62
  );
41
63
  const result = render(tree('<h1>Roadmap</h1>'));
42
64
  return { ...result, receive: (content: string) => result.rerender(tree(content)) };
@@ -118,41 +140,45 @@ describe('the consent card on the file page', () => {
118
140
  frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
119
141
  await waitFor(() => expect(frame.replies).toEqual([{ type: 'bevel.tool.response', requestId: 'r1', ok: true, result: { ran: 'read_file' } }]));
120
142
  expect(server.mcp).toEqual(['read_file']);
121
- expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
143
+ expect(screen.queryByText(CARD)).toBeNull();
122
144
  });
123
145
 
124
- it('asks on the first write with the page\'s name and path; Allow runs it and holds for the view', async () => {
146
+ it('asks on the first write in the plain sentence with the page\'s path; Allow runs it and holds for the view', async () => {
125
147
  const server = stubServer();
126
148
  const { container } = onFilePage();
127
149
  const frame = frameChannel(await frameOf(container));
128
150
  frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
129
- expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
151
+ expect(await screen.findByText(CARD)).toBeTruthy();
130
152
  expect(screen.getByText(PAGE)).toBeTruthy();
131
153
  expect(server.mcp).toEqual([]);
132
154
 
133
- fireEvent.click(screen.getByRole('button', { name: 'Allow while open' }));
155
+ fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
134
156
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true, result: { ran: 'edit_file' } }));
135
157
 
136
158
  frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callToolChain', args: ['return 1'] });
137
159
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
138
- expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
160
+ expect(screen.queryByText(CARD)).toBeNull();
139
161
  expect(server.mcp).toEqual(['edit_file', 'call_tool_chain']);
140
162
  });
141
163
 
142
- it('Deny answers denied and runs nothing; the next write asks again; a reload asks again after an Allow', async () => {
164
+ it("Don't allow answers denied and runs nothing; the next write asks again; a reload after an Allow asks nothing", async () => {
143
165
  const server = stubServer();
144
166
  const { container } = onFilePage();
145
167
  const frame = frameChannel(await frameOf(container));
146
168
  frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
147
- fireEvent.click(await screen.findByRole('button', { name: 'Deny' }));
169
+ fireEvent.click(await screen.findByRole('button', { name: "Don't allow" }));
148
170
  await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'w1', ok: false, error: 'denied', code: 'denied' }));
149
171
  expect(server.mcp).toEqual([]);
172
+ expect(window.localStorage.getItem(ALLOWED_PAGE_KEY_PREFIX + sha256Hex('<h1>Roadmap</h1>'))).toBeNull();
173
+ expect(Array.from({ length: window.localStorage.length }, (_, i) => window.localStorage.key(i)!).filter((key) => key.startsWith(ALLOWED_PAGE_KEY_PREFIX))).toEqual([]);
150
174
 
151
175
  frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
152
- fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
176
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
153
177
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
178
+ // The digest of the source the renderer received, not of the document it built.
179
+ expect(rememberedDigests()).toEqual([sha256Hex('<h1>Roadmap</h1>')]);
154
180
 
155
- // Reload the page: a new view, a new frame window, and the card again.
181
+ // Reload the page: a new view, a new frame window, and no card for the same source.
156
182
  fireEvent.click(screen.getByTitle('Reload preview'));
157
183
  const reloaded = frameChannel(await waitFor(() => {
158
184
  const el = container.querySelector('iframe')!;
@@ -160,15 +186,16 @@ describe('the consent card on the file page', () => {
160
186
  return el;
161
187
  }));
162
188
  reloaded.post({ type: 'bevel.tool.call', requestId: 'w3', fn: 'callTool', args: ['edit_file', {}] });
163
- expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
189
+ await waitFor(() => expect(reloaded.replies.at(-1)).toMatchObject({ requestId: 'w3', ok: true }));
190
+ expect(screen.queryByText(CARD)).toBeNull();
164
191
  });
165
192
 
166
- it('asks again after Edit and back to Preview, though the document is the same', async () => {
193
+ it('asks nothing after Edit and back to Preview: the source is the same', async () => {
167
194
  stubServer();
168
195
  const { container } = onFilePage({ readOnly: false });
169
196
  const frame = frameChannel(await frameOf(container));
170
197
  frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
171
- fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
198
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
172
199
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
173
200
 
174
201
  fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
@@ -176,7 +203,28 @@ describe('the consent card on the file page', () => {
176
203
  fireEvent.click(screen.getByRole('button', { name: 'Preview' }));
177
204
  const back = frameChannel(await frameOf(container));
178
205
  back.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
179
- expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
206
+ await waitFor(() => expect(back.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
207
+ expect(screen.queryByText(CARD)).toBeNull();
208
+ });
209
+
210
+ it('asks again when one character of the source changed, and keeps the earlier Allow', async () => {
211
+ stubServer();
212
+ const { container, receive } = onFilePage();
213
+ const frame = frameChannel(await frameOf(container));
214
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
215
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
216
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
217
+
218
+ receive('<h1>Roadmap!</h1>');
219
+ const changed = frameChannel(await frameOf(container));
220
+ changed.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
221
+ expect(await screen.findByText(CARD)).toBeTruthy();
222
+ fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
223
+ await waitFor(() => expect(changed.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
224
+ expect(rememberedDigests()).toEqual([
225
+ sha256Hex('<h1>Roadmap</h1>'),
226
+ sha256Hex('<h1>Roadmap!</h1>'),
227
+ ]);
180
228
  });
181
229
 
182
230
  it('answers requireTools true with nothing shown', async () => {
@@ -222,23 +270,23 @@ describe('an upload from the file page', () => {
222
270
  const file = () => new File([new Uint8Array([0x50, 0x4b, 0x03, 0x04])], 'Assets.xlsx');
223
271
 
224
272
  it('asks with the write card, and on Allow runs the three steps in order with the viewer\'s session', async () => {
225
- setToken('viewer-session');
273
+ setToken(VIEWER_SESSION);
226
274
  try {
227
275
  const server = stubUploadServer();
228
276
  const { container } = onFilePage();
229
277
  const frame = frameChannel(await frameOf(container));
230
278
  frame.post({ type: 'bevel.tool.call', requestId: 'u1', fn: 'uploadFile', args: [file(), { branch: 'main', destination: 'Data/Campaigns/Easter' }] });
231
- expect(await screen.findByText('Roadmap wants to write to the knowledge base')).toBeTruthy();
279
+ expect(await screen.findByText(CARD)).toBeTruthy();
232
280
  expect(server.requests).toEqual([]);
233
281
 
234
- fireEvent.click(screen.getByRole('button', { name: 'Allow while open' }));
282
+ fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
235
283
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'u1', ok: true, result: { count: 1, destination: 'Data/Campaigns/Easter' } }));
236
284
  expect(server.requests.map((r) => r.step)).toEqual([
237
285
  'request_file_upload',
238
286
  'POST /api/agent/uploads?filename=Assets.xlsx',
239
287
  'apply_file_upload',
240
288
  ]);
241
- for (const r of server.requests) expect(r.headers.get('Authorization')).toBe('Bearer viewer-session');
289
+ for (const r of server.requests) expect(r.headers.get('Authorization')).toBe(`Bearer ${VIEWER_SESSION}`);
242
290
  for (const r of server.requests.filter((x) => x.step.endsWith('_upload'))) {
243
291
  expect(decodeURIComponent(r.headers.get('X-Bevel-Page')!)).toBe(PAGE);
244
292
  }
@@ -250,18 +298,18 @@ describe('an upload from the file page', () => {
250
298
  // Allow holds for the view: the next upload runs with no card.
251
299
  frame.post({ type: 'bevel.tool.call', requestId: 'u2', fn: 'uploadFile', args: [file(), { branch: 'main', destination: 'Data' }] });
252
300
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'u2', ok: true }));
253
- expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
301
+ expect(screen.queryByText(CARD)).toBeNull();
254
302
  } finally {
255
303
  clearToken();
256
304
  }
257
305
  });
258
306
 
259
- it('Deny answers denied, uploads nothing, and reports a refused apply_file_upload under the page', async () => {
307
+ it("Don't allow answers denied, uploads nothing, and reports a refused apply_file_upload under the page", async () => {
260
308
  const server = stubUploadServer();
261
309
  const { container } = onFilePage();
262
310
  const frame = frameChannel(await frameOf(container));
263
311
  frame.post({ type: 'bevel.tool.call', requestId: 'u1', fn: 'uploadFile', args: [file(), { branch: 'main', destination: 'Data/Campaigns/Easter' }] });
264
- fireEvent.click(await screen.findByRole('button', { name: 'Deny' }));
312
+ fireEvent.click(await screen.findByRole('button', { name: "Don't allow" }));
265
313
  await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'u1', ok: false, error: 'denied', code: 'denied' }));
266
314
  await waitFor(() => expect(server.requests.map((r) => r.step)).toEqual(['refusal']));
267
315
  expect(server.requests[0]!.body).toMatchObject({ page: PAGE, tool: 'apply_file_upload' });
@@ -350,7 +398,7 @@ describe('a call whose view ended before it was decided', () => {
350
398
  server.releaseManual();
351
399
  await settled();
352
400
 
353
- expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
401
+ expect(screen.queryByText(CARD)).toBeNull();
354
402
  expect(server.mcp).toEqual([]);
355
403
  expect(changed.replies).toEqual([]);
356
404
  });
@@ -362,7 +410,7 @@ describe('a call whose view ended before it was decided', () => {
362
410
  const frame = frameChannel(iframe);
363
411
  // A chain asks without the manual: Allow it, so the view holds an Allow.
364
412
  frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callToolChain', args: ['return 1'] });
365
- fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
413
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
366
414
  await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
367
415
 
368
416
  frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
@@ -389,7 +437,7 @@ describe('a call whose view ended before it was decided', () => {
389
437
  server.releaseManual();
390
438
  await settled();
391
439
 
392
- expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
440
+ expect(screen.queryByText(CARD)).toBeNull();
393
441
  expect(server.mcp).toEqual([]);
394
442
  // Neither document hears an answer meant for a view that is gone.
395
443
  expect(frame.replies).toEqual([]);
@@ -18,6 +18,17 @@ import {
18
18
 
19
19
  const PAGE = 'Dashboards/Roadmap.html';
20
20
 
21
+ /** A browser memory for one page's source, as the hook binds it: `allowed` says whether it already holds an Allow. */
22
+ function memoryOf(allowed: boolean) {
23
+ const memory = { remembered: vi.fn(() => allowed), remember: vi.fn(() => void (allowed = true)) };
24
+ return memory;
25
+ }
26
+
27
+ /** A browser that remembers no Allow for the page. */
28
+ function nothingRemembered() {
29
+ return memoryOf(false);
30
+ }
31
+
21
32
  /** The deployment's UTCP manual: `read_file` reads, `edit_file` and `write_file` write. */
22
33
  const MANUAL = {
23
34
  tools: [
@@ -143,7 +154,7 @@ describe('answering a page: reads at once, the first write asks', () => {
143
154
  const client = new PageToolsClient(PAGE, server.fetchImpl);
144
155
  let answer: (ok: boolean) => void = () => {};
145
156
  const ask = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));
146
- const consent = new PageConsent(ask);
157
+ const consent = new PageConsent(ask, nothingRemembered());
147
158
  return { server, client, consent, ask, answer: (ok: boolean) => answer(ok) };
148
159
  }
149
160
 
@@ -171,7 +182,7 @@ describe('answering a page: reads at once, the first write asks', () => {
171
182
  expect(ask).toHaveBeenCalledTimes(1);
172
183
  });
173
184
 
174
- it('Deny answers `denied`, runs nothing, reports the refusal, and the next write asks again', async () => {
185
+ it("Don't allow answers `denied`, runs nothing, reports the refusal, and the next write asks again", async () => {
175
186
  const { client, consent, ask, answer, server } = setup();
176
187
  const denied = answerToolCall(call('callTool', 'edit_file', { body: { path: 'a.md' } }), client, consent);
177
188
  await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
@@ -204,18 +215,77 @@ describe('answering a page: reads at once, the first write asks', () => {
204
215
  expect(ask).toHaveBeenCalledTimes(1);
205
216
  });
206
217
 
207
- it('asks again in a new view of the page: an Allow holds only until the page is reloaded', async () => {
218
+ it('asks again in a new view of the page when the browser remembers no Allow for it', async () => {
208
219
  const { client, answer } = setup();
209
- const firstView = new PageConsent(() => Promise.resolve(true));
220
+ const firstView = new PageConsent(() => Promise.resolve(true), nothingRemembered());
210
221
  await answerToolCall(call('callTool', 'edit_file', {}), client, firstView);
211
222
  const ask = vi.fn(() => Promise.resolve(false));
212
- const reloaded = new PageConsent(ask);
223
+ const reloaded = new PageConsent(ask, nothingRemembered());
213
224
  expect(await answerToolCall(call('callTool', 'edit_file', {}), client, reloaded)).toMatchObject({ ok: false, code: DENIED });
214
225
  expect(ask).toHaveBeenCalledTimes(1);
215
226
  answer(true);
216
227
  });
217
228
  });
218
229
 
230
+ describe('the browser memory: an Allow is remembered for the page, a refusal never is', () => {
231
+ it('runs the first write of a remembered page with no card', async () => {
232
+ const server = fakeServer((name) => text({ ran: name }));
233
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
234
+ const ask = vi.fn(() => Promise.resolve(false));
235
+ const consent = new PageConsent(ask, memoryOf(true));
236
+ expect(await answerToolCall(call('callTool', 'edit_file', {}), client, consent)).toMatchObject({ ok: true, result: { ran: 'edit_file' } });
237
+ expect(await answerToolCall(call('callToolChain', 'return 1'), client, consent)).toMatchObject({ ok: true });
238
+ expect(ask).not.toHaveBeenCalled();
239
+ expect(server.mcpCalls()).toEqual(['edit_file', 'call_tool_chain']);
240
+ });
241
+
242
+ it('remembers an Allow, so the next view of the same page asks nothing', async () => {
243
+ const server = fakeServer((name) => text({ ran: name }));
244
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
245
+ const memory = nothingRemembered();
246
+ await answerToolCall(call('callTool', 'edit_file', {}), client, new PageConsent(() => Promise.resolve(true), memory));
247
+ expect(memory.remember).toHaveBeenCalledTimes(1);
248
+ const ask = vi.fn(() => Promise.resolve(false));
249
+ expect(await answerToolCall(call('callTool', 'edit_file', {}), client, new PageConsent(ask, memory))).toMatchObject({ ok: true });
250
+ expect(ask).not.toHaveBeenCalled();
251
+ });
252
+
253
+ it("remembers nothing on Don't allow, and nothing when the view ends with the card open", async () => {
254
+ const server = fakeServer((name) => text({ ran: name }));
255
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
256
+ const refused = nothingRemembered();
257
+ const reply = await answerToolCall(call('callTool', 'edit_file', {}), client, new PageConsent(() => Promise.resolve(false), refused));
258
+ expect(reply).toMatchObject({ ok: false, error: DENIED, code: DENIED });
259
+ expect(refused.remember).not.toHaveBeenCalled();
260
+
261
+ const left = nothingRemembered();
262
+ let answer: (ok: boolean) => void = () => {};
263
+ const consent = new PageConsent(() => new Promise<boolean>((resolve) => (answer = resolve)), left);
264
+ const pending = answerToolCall(call('callTool', 'edit_file', {}), client, consent);
265
+ await vi.waitFor(() => expect(consent.open).not.toBeNull());
266
+ consent.close();
267
+ answer(true);
268
+ expect(await pending).toMatchObject({ ok: false, code: 'closed' });
269
+ expect(left.remember).not.toHaveBeenCalled();
270
+ expect(server.mcpCalls()).toEqual([]);
271
+ });
272
+
273
+ it('shows one card for ten writes at once when nothing is remembered, and Allow runs all ten', async () => {
274
+ const server = fakeServer((name) => text({ ran: name }));
275
+ const client = new PageToolsClient(PAGE, server.fetchImpl);
276
+ let answer: (ok: boolean) => void = () => {};
277
+ const ask = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));
278
+ const memory = nothingRemembered();
279
+ const consent = new PageConsent(ask, memory);
280
+ const writes = Array.from({ length: 10 }, () => answerToolCall(call('callTool', 'edit_file', {}), client, consent));
281
+ await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
282
+ answer(true);
283
+ expect((await Promise.all(writes)).every((w) => w.ok)).toBe(true);
284
+ expect(ask).toHaveBeenCalledTimes(1);
285
+ expect(memory.remember).toHaveBeenCalledTimes(1);
286
+ });
287
+ });
288
+
219
289
  describe('the frame messages the app reads', () => {
220
290
  it('accepts only a well-formed call of one of the five functions', () => {
221
291
  expect(asToolCall({ type: 'bevel.tool.call', requestId: 'r', fn: 'callTool', args: ['read_file', {}] })).not.toBeNull();
@@ -429,7 +499,7 @@ describe('uploadFile: the agent upload path, run by the app as the viewer', () =
429
499
  const client = new PageToolsClient(PAGE, server.fetchImpl);
430
500
  let answer: (ok: boolean) => void = () => {};
431
501
  const ask = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));
432
- const consent = new PageConsent(ask);
502
+ const consent = new PageConsent(ask, nothingRemembered());
433
503
 
434
504
  const first = answerToolCall(call('uploadFile', XLSX, { branch: 'main', destination: 'Data/Campaigns/Easter' }), client, consent);
435
505
  await vi.waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
@@ -444,10 +514,10 @@ describe('uploadFile: the agent upload path, run by the app as the viewer', () =
444
514
  expect(ask).toHaveBeenCalledTimes(1);
445
515
  });
446
516
 
447
- it('Deny answers `denied`, uploads nothing, and records a refused apply_file_upload under the page', async () => {
517
+ it("Don't allow answers `denied`, uploads nothing, and records a refused apply_file_upload under the page", async () => {
448
518
  const server = uploadServer();
449
519
  const client = new PageToolsClient(PAGE, server.fetchImpl);
450
- const consent = new PageConsent(() => Promise.resolve(false));
520
+ const consent = new PageConsent(() => Promise.resolve(false), nothingRemembered());
451
521
  const reply = await answerToolCall(
452
522
  call('uploadFile', XLSX, { branch: 'main', destination: 'Data/Campaigns/Easter', mode: 'overwrite' }),
453
523
  client,
@@ -178,8 +178,15 @@ describe('the html-views guide section agrees with the renderer', () => {
178
178
 
179
179
  // The consent rule and the two cards, in the app's words.
180
180
  expect(flat).toContain('A call to a tool that only reads runs with no prompt.');
181
- expect(flat).toContain('"<page name> wants to write to the knowledge base", with the page\'s path under it and Allow while open and Deny.');
182
- expect(flat).toContain('Deny runs nothing and rejects the call with `denied`');
181
+ expect(flat).toContain('"You\'re allowing changes using your account. Do you want to allow that?", with the page\'s path under it and the buttons Don\'t allow and Allow.');
182
+ expect(flat).toContain("Don't allow runs nothing and rejects the call with `denied`");
183
+ expect(flat).toContain("It is never remembered: the next writing call asks again.");
184
+ // The browser's memory: the account's, by the page's exact content, asked again on any change.
185
+ expect(flat).toContain("The browser remembers an Allow for the signed-in account and the page's exact content, so the same page asks that account nothing on a later view in that browser. Signing out clears what the account kept. Content the account has not allowed asks again, such as an edited page, as does another account or browser, a browser that will not store, and content past the account's 500 most recently allowed: never rely on an Allow being kept.");
186
+ // A page reaches the person's own tools, as their agent does.
187
+ expect(flat).toContain("a page calls the tools of the person viewing it — exactly the tools that person's own agent gets from the hosted MCP server, with the same names, answers and refusals —");
188
+ expect(flat).not.toContain('wants to write');
189
+ expect(flat).not.toContain('Allow while open');
183
190
  expect(flat).toContain('"<page name> uses tools that are only available in the platform", with Continue without tools and Open in the platform');
184
191
 
185
192
  // uploadFile: its arguments, the promise, the consent rule and the size limit.
@@ -187,7 +194,7 @@ describe('the html-views guide section agrees with the renderer', () => {
187
194
  expect(flat).toContain("`mode` is `create` (the default), `overwrite` or `update`");
188
195
  expect(flat).toContain("The promise resolves with `apply_file_upload`'s answer, `{ destination, count, total, files }`");
189
196
  expect(flat).toContain("a file over the deployment's upload limit (the message names it)");
190
- expect(flat).toContain('An upload is a writing call: the first one shows the card above, and Allow while open covers it and every later upload and writing call of the page view.');
197
+ expect(flat).toContain('An upload is a writing call: the first one shows the card above, and an Allow covers it and every later upload and writing call of the page view.');
191
198
  expect(flat).toContain("The upload's token stays in the app; the page never sees it.");
192
199
 
193
200
  // requireTools exists on both, asks the app, and resolves with its answer.
@@ -0,0 +1,177 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { isRemembered, remember } from '../pageConsentMemory';
3
+
4
+ /**
5
+ * The browser's memory of the pages an account allowed to write: one
6
+ * `localStorage` entry per digest under the account's prefix, its 500 most
7
+ * recently allowed, and nothing at all with no account or when the browser
8
+ * will not store.
9
+ */
10
+ const A = 'user-a';
11
+ const B = 'user-b';
12
+ const prefixOf = (account: string) => `bevel.account/${account}/htmlPage.allowedWrite.`;
13
+ const PREFIX = prefixOf(A);
14
+
15
+ /** The account's digests stored in localStorage, least recently allowed first: read through the storage API, as another tab would. */
16
+ const rememberedDigests = (account: string = A): string[] =>
17
+ Array.from({ length: window.localStorage.length }, (_, i) => window.localStorage.key(i)!)
18
+ .filter((key) => key.startsWith(prefixOf(account)) && Number.isFinite(Number(window.localStorage.getItem(key))))
19
+ .sort((a, b) => Number(window.localStorage.getItem(a)) - Number(window.localStorage.getItem(b)))
20
+ .map((key) => key.slice(prefixOf(account).length));
21
+
22
+ describe('pageConsentMemory', () => {
23
+ beforeEach(() => window.localStorage.clear());
24
+ afterEach(() => vi.restoreAllMocks());
25
+
26
+ it('remembers a digest it was given, and only that one', () => {
27
+ expect(isRemembered(A, 'a1')).toBe(false);
28
+ remember(A, 'a1');
29
+ expect(isRemembered(A, 'a1')).toBe(true);
30
+ expect(isRemembered(A, 'b2')).toBe(false);
31
+ expect(rememberedDigests()).toEqual(['a1']);
32
+ expect(window.localStorage.getItem(`${PREFIX}a1`)).not.toBeNull();
33
+ });
34
+
35
+ it('keeps an earlier digest when a new one is allowed', () => {
36
+ remember(A, 'old');
37
+ remember(A, 'new');
38
+ expect(isRemembered(A, 'old')).toBe(true);
39
+ expect(isRemembered(A, 'new')).toBe(true);
40
+ expect(rememberedDigests()).toEqual(['old', 'new']);
41
+ });
42
+
43
+ it("an Allow writes only its own entry, so another tab's Allow at the same moment survives", () => {
44
+ remember(A, 'mine');
45
+ const setItem = vi.spyOn(window.localStorage, 'setItem');
46
+ const removeItem = vi.spyOn(window.localStorage, 'removeItem');
47
+ remember(A, 'also-mine');
48
+ // Another tab's Allow lands as its own entry, whenever it lands.
49
+ window.localStorage.setItem(`${PREFIX}theirs`, String(Date.now()));
50
+ expect(setItem.mock.calls[0]![0]).toBe(`${PREFIX}also-mine`);
51
+ expect(removeItem).not.toHaveBeenCalled();
52
+ expect(rememberedDigests().sort()).toEqual(['also-mine', 'mine', 'theirs']);
53
+ });
54
+
55
+ it('keeps the 500 most recently allowed: the 501st forgets the least recently allowed', () => {
56
+ // 500 earlier Allows, d0 the least recent.
57
+ for (let i = 0; i < 500; i++) window.localStorage.setItem(`${PREFIX}d${i}`, String(i + 1));
58
+ // Allowing d0 again makes it the most recent, so d1 is now the oldest.
59
+ remember(A, 'd0');
60
+ remember(A, 'd500');
61
+ expect(isRemembered(A, 'd1')).toBe(false);
62
+ expect(isRemembered(A, 'd0')).toBe(true);
63
+ expect(isRemembered(A, 'd2')).toBe(true);
64
+ expect(isRemembered(A, 'd500')).toBe(true);
65
+ expect(rememberedDigests()).toHaveLength(500);
66
+ expect(rememberedDigests().slice(-2)).toEqual(['d0', 'd500']);
67
+ });
68
+
69
+ it('trims to the cap from what storage holds after its write, so two tabs allowing at once never leave more than 500', () => {
70
+ // Another tab's Allow at the same moment already took the account to 501.
71
+ for (let i = 0; i < 501; i++) window.localStorage.setItem(`${PREFIX}d${i}`, String(i + 1));
72
+ remember(A, 'mine');
73
+ expect(rememberedDigests()).toHaveLength(500);
74
+ expect(isRemembered(A, 'mine')).toBe(true);
75
+ expect(isRemembered(A, 'd0')).toBe(false);
76
+ expect(isRemembered(A, 'd1')).toBe(false);
77
+ });
78
+
79
+ it("never forgets an entry another tab allowed again while this Allow was being written", () => {
80
+ for (let i = 0; i < 500; i++) window.localStorage.setItem(`${PREFIX}d${i}`, String(i + 1));
81
+ const original = window.localStorage.setItem.bind(window.localStorage);
82
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation((key, value) => {
83
+ original(key, value);
84
+ // Another tab allows the oldest page again right as this write lands.
85
+ if (key === `${PREFIX}mine`) original(`${PREFIX}d0`, String(Number(value) + 1));
86
+ });
87
+ remember(A, 'mine');
88
+ expect(isRemembered(A, 'd0')).toBe(true);
89
+ expect(isRemembered(A, 'mine')).toBe(true);
90
+ expect(isRemembered(A, 'd1')).toBe(false);
91
+ expect(rememberedDigests()).toHaveLength(500);
92
+ });
93
+
94
+ it('leaves entries that are not its own alone', () => {
95
+ window.localStorage.setItem('bevel.htmlPage.height', '300');
96
+ for (let i = 0; i < 500; i++) window.localStorage.setItem(`${PREFIX}d${i}`, String(i + 1));
97
+ remember(A, 'd500');
98
+ expect(isRemembered(A, 'd0')).toBe(false);
99
+ expect(window.localStorage.getItem('bevel.htmlPage.height')).toBe('300');
100
+ });
101
+
102
+ it("is the account's: another account is not remembered for a digest the first allowed", () => {
103
+ remember(A, 'a1');
104
+ expect(isRemembered(B, 'a1')).toBe(false);
105
+ remember(B, 'a1');
106
+ expect(isRemembered(B, 'a1')).toBe(true);
107
+ expect(rememberedDigests(A)).toEqual(['a1']);
108
+ expect(rememberedDigests(B)).toEqual(['a1']);
109
+ });
110
+
111
+ it("counts the cap per account: one account's Allows never forget another's", () => {
112
+ for (let i = 0; i < 500; i++) window.localStorage.setItem(`${PREFIX}d${i}`, String(i + 1));
113
+ for (let i = 0; i < 500; i++) window.localStorage.setItem(`${prefixOf(B)}d${i}`, String(i + 1));
114
+
115
+ remember(B, 'd500');
116
+
117
+ expect(rememberedDigests(A)).toHaveLength(500);
118
+ expect(isRemembered(A, 'd0')).toBe(true);
119
+ expect(rememberedDigests(B)).toHaveLength(500);
120
+ expect(isRemembered(B, 'd0')).toBe(false);
121
+ });
122
+
123
+
124
+ it('keeps nothing with no account', () => {
125
+ const setItem = vi.spyOn(window.localStorage, 'setItem');
126
+ remember(null, 'a1');
127
+ expect(setItem).not.toHaveBeenCalled();
128
+ expect(isRemembered(null, 'a1')).toBe(false);
129
+ expect(window.localStorage.length).toBe(0);
130
+ });
131
+
132
+ it('reads a blocked storage as nothing remembered, and stores nothing without an error', () => {
133
+ // What a browser in strict privacy mode does: touching storage throws.
134
+ vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => {
135
+ throw new DOMException('The operation is insecure.', 'SecurityError');
136
+ });
137
+ expect(isRemembered(A, 'a1')).toBe(false);
138
+ expect(() => remember(A, 'a1')).not.toThrow();
139
+ expect(isRemembered(A, 'a1')).toBe(false);
140
+ // Unblocked again, the storage holds nothing of that Allow.
141
+ vi.restoreAllMocks();
142
+ expect(rememberedDigests()).toEqual([]);
143
+ });
144
+
145
+ it('reads a storage whose calls throw as nothing remembered, and stores nothing without an error', () => {
146
+ const fail = () => {
147
+ throw new DOMException('The quota has been exceeded.', 'QuotaExceededError');
148
+ };
149
+ const setItem = vi.fn(fail);
150
+ vi.spyOn(window, 'localStorage', 'get').mockReturnValue({
151
+ length: 0,
152
+ key: () => null,
153
+ getItem: fail,
154
+ setItem,
155
+ removeItem: fail,
156
+ } as unknown as Storage);
157
+ expect(isRemembered(A, 'a1')).toBe(false);
158
+ expect(() => remember(A, 'a1')).not.toThrow();
159
+ expect(setItem).toHaveBeenCalledTimes(1);
160
+ expect(isRemembered(A, 'a1')).toBe(false);
161
+ });
162
+
163
+ it('reads an account id that cannot be encoded as nothing remembered, without an error', () => {
164
+ const unencodable = 'user-\uD800';
165
+ expect(isRemembered(unencodable, 'a1')).toBe(false);
166
+ expect(() => remember(unencodable, 'a1')).not.toThrow();
167
+ expect(window.localStorage.length).toBe(0);
168
+ });
169
+
170
+ it('ignores a corrupt stored entry', () => {
171
+ window.localStorage.setItem(`${PREFIX}a1`, 'not a time');
172
+ expect(isRemembered(A, 'a1')).toBe(false);
173
+ expect(rememberedDigests()).toEqual([]);
174
+ remember(A, 'a1');
175
+ expect(rememberedDigests()).toEqual(['a1']);
176
+ });
177
+ });