@bevel-software/platform-core-frontend 0.31.0 → 0.33.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 (167) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +1 -1
  3. package/src/modules/access/api.ts +1 -1
  4. package/src/modules/access/components/ManageAccessDialog.tsx +4 -5
  5. package/src/modules/access/hooks/useAccessRequests.ts +1 -1
  6. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  7. package/src/modules/access/index.ts +11 -0
  8. package/src/modules/access/requests.api.ts +1 -1
  9. package/src/modules/admin/components/AddMemberInput.tsx +1 -1
  10. package/src/modules/admin/components/UserAccountsPage.tsx +3 -3
  11. package/src/modules/admin/index.ts +7 -0
  12. package/src/modules/admin/state/admin.context.tsx +1 -1
  13. package/src/modules/audit/components/AuditEventsPanel.tsx +1 -1
  14. package/src/modules/audit/components/AuditLogPage.tsx +2 -2
  15. package/src/modules/auth/index.ts +12 -0
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +0 -1
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +0 -1
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +0 -1
  19. package/src/modules/change-requests/__tests__/ChangeRequestDialog.edit.test.tsx +166 -0
  20. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +0 -1
  21. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +0 -1
  22. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +0 -1
  23. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +0 -1
  24. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +0 -2
  25. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +0 -1
  26. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +0 -1
  27. package/src/modules/change-requests/components/BranchFilePreview.tsx +4 -12
  28. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +138 -30
  29. package/src/modules/change-requests/components/ChangeRequestLink.tsx +2 -3
  30. package/src/modules/change-requests/components/CrFileTree.tsx +1 -1
  31. package/src/modules/change-requests/components/FileChangeBoxes.tsx +2 -3
  32. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +3 -5
  33. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +1 -1
  34. package/src/modules/change-requests/index.ts +14 -0
  35. package/src/modules/change-requests/services/change-requests.api.ts +2 -2
  36. package/src/modules/change-requests/services/denied-file.api.ts +2 -2
  37. package/src/modules/change-requests/services/propose.api.ts +3 -4
  38. package/src/modules/change-requests/utils/diff.ts +1 -1
  39. package/src/modules/change-requests/utils/readFailure.ts +1 -1
  40. package/src/modules/embed/__tests__/EmbedView.test.tsx +19 -2
  41. package/src/modules/embed/components/EmbedLinkPage.tsx +1 -2
  42. package/src/modules/git/components/BranchSwitcher.tsx +3 -4
  43. package/src/modules/git/components/FileHistoryPanel.tsx +2 -2
  44. package/src/modules/git/components/GitSyncFailedBanner.tsx +2 -4
  45. package/src/modules/git/components/HistoryVersionPreview.tsx +4 -15
  46. package/src/modules/git/components/PullNeededBanner.tsx +1 -1
  47. package/src/modules/git/hooks/useAutoPullUpdates.ts +1 -1
  48. package/src/modules/git/index.ts +11 -0
  49. package/src/modules/layout/components/MobileChatLayout.tsx +1 -1
  50. package/src/modules/layout/index.ts +9 -0
  51. package/src/modules/library/__tests__/SkillPage.test.tsx +39 -0
  52. package/src/modules/library/__tests__/propose-change.test.ts +75 -0
  53. package/src/modules/library/components/AddToPluginDialog.tsx +1 -1
  54. package/src/modules/library/components/ChangeRequestDock.tsx +1 -1
  55. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  56. package/src/modules/library/components/LibraryPage.tsx +3 -3
  57. package/src/modules/library/components/ManagedPluginRequests.tsx +1 -1
  58. package/src/modules/library/components/NewSkillPanel.tsx +2 -2
  59. package/src/modules/library/components/PersonalAddDialog.tsx +1 -1
  60. package/src/modules/library/components/PersonalPluginPage.tsx +1 -1
  61. package/src/modules/library/components/PluginExtras.tsx +1 -4
  62. package/src/modules/library/components/PluginPage.tsx +1 -1
  63. package/src/modules/library/components/PluginRows.tsx +1 -1
  64. package/src/modules/library/components/SkillsTree.tsx +1 -4
  65. package/src/modules/library/components/plugin-page-parts.tsx +1 -1
  66. package/src/modules/library/components/skill-page/SkillFilePane.tsx +19 -7
  67. package/src/modules/library/components/skill-page/SkillPage.tsx +19 -26
  68. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +2 -4
  69. package/src/modules/library/components/tool-page/ToolVarRow.tsx +2 -2
  70. package/src/modules/library/hooks/useJoinRequests.ts +1 -1
  71. package/src/modules/library/hooks/useLibraryData.ts +3 -3
  72. package/src/modules/library/hooks/useToolPage.ts +1 -1
  73. package/src/modules/library/hooks/useToolSource.ts +1 -1
  74. package/src/modules/library/index.ts +12 -0
  75. package/src/modules/library/routes/LibraryRoutes.tsx +1 -1
  76. package/src/modules/library/routes/WorkspaceItemRoute.tsx +1 -3
  77. package/src/modules/library/routes/library-paths.ts +1 -1
  78. package/src/modules/library/services/library.api.ts +10 -8
  79. package/src/modules/library/services/plugins.api.ts +1 -1
  80. package/src/modules/library/services/teams.api.ts +1 -1
  81. package/src/modules/library/utils/status.ts +2 -2
  82. package/src/modules/onboarding/components/ConnectAgentPill.tsx +1 -1
  83. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +2 -3
  84. package/src/modules/onboarding/components/GetStartedColumn.tsx +6 -13
  85. package/src/modules/onboarding/components/InviteButton.tsx +2 -2
  86. package/src/modules/onboarding/components/InviteDialog.tsx +4 -6
  87. package/src/modules/onboarding/components/RootLanding.tsx +2 -2
  88. package/src/modules/onboarding/components/StarterPackCard.tsx +1 -1
  89. package/src/modules/onboarding/components/WelcomePage.tsx +2 -5
  90. package/src/modules/onboarding/index.ts +10 -0
  91. package/src/modules/onboarding/paths.ts +1 -1
  92. package/src/modules/onboarding/state/agent-connection.ts +2 -2
  93. package/src/modules/onboarding/state/onboarding.ts +1 -1
  94. package/src/modules/onboarding/state/starter-packs.ts +1 -1
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +1 -1
  96. package/src/modules/pr/index.ts +14 -0
  97. package/src/modules/pr/services/pr-approvals.api.ts +1 -1
  98. package/src/modules/pr/services/pr-cancel.api.ts +1 -1
  99. package/src/modules/pr/services/pr-detail.api.ts +2 -2
  100. package/src/modules/pr/services/pr-edit.api.ts +22 -0
  101. package/src/modules/pr/services/pr-merge.api.ts +1 -1
  102. package/src/modules/pr/services/pr-open.api.ts +1 -1
  103. package/src/modules/review/components/DiffViewer.tsx +1 -1
  104. package/src/modules/review/components/MarkdownDiffViewer.tsx +1 -2
  105. package/src/modules/review/components/ReviewPanel.tsx +2 -3
  106. package/src/modules/review/state/ReviewProvider.tsx +2 -2
  107. package/src/modules/secrets-vault/index.ts +6 -0
  108. package/src/modules/settings/components/DeploymentPage.tsx +2 -2
  109. package/src/modules/settings/components/SettingsLayout.tsx +2 -2
  110. package/src/modules/settings/index.ts +8 -0
  111. package/src/modules/setup/components/FirstRunStorage.tsx +1 -1
  112. package/src/modules/setup/index.ts +6 -0
  113. package/src/modules/toolbar/commands/actions.tsx +3 -3
  114. package/src/modules/toolbar/commands/useCommandActions.ts +5 -9
  115. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +2 -2
  116. package/src/modules/toolbar/components/AppSwitcher.tsx +1 -2
  117. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +1 -1
  118. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +1 -1
  119. package/src/modules/toolbar/components/ProfileMenu.tsx +3 -3
  120. package/src/modules/toolbar/components/SearchPalette.tsx +4 -8
  121. package/src/modules/toolbar/components/Toolbar.tsx +2 -5
  122. package/src/modules/toolbar/index.ts +6 -0
  123. package/src/modules/toolbar/search/sources.ts +4 -7
  124. package/src/modules/toolbar/services/agent-instructions.api.ts +1 -1
  125. package/src/modules/tools/ToolsExplorerPage.tsx +217 -18
  126. package/src/modules/tools/__tests__/ToolsExplorerPage.read-only.test.tsx +220 -0
  127. package/src/modules/tools/tool-hints.api.ts +44 -0
  128. package/src/modules/workflow/index.ts +7 -0
  129. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +1 -0
  130. package/src/modules/workflow/state/EventBusFocusBinder.tsx +1 -1
  131. package/src/modules/workspace/components/FileExplorer.tsx +35 -8
  132. package/src/modules/workspace/components/FilePaneCard.tsx +37 -12
  133. package/src/modules/workspace/components/FileRoute.tsx +10 -3
  134. package/src/modules/workspace/components/FileViewer.tsx +169 -25
  135. package/src/modules/workspace/components/FullScreenView.tsx +93 -0
  136. package/src/modules/workspace/components/KbFileRail.tsx +1 -1
  137. package/src/modules/workspace/components/KbPageHeader.tsx +9 -0
  138. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +137 -0
  139. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +11 -0
  140. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +487 -3
  141. package/src/modules/workspace/components/readingCarry.ts +59 -0
  142. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +36 -175
  143. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +1 -1
  144. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +168 -42
  145. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +20 -3
  146. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +63 -4
  147. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +235 -1
  148. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +14 -3
  149. package/src/modules/workspace/components/renderers/__tests__/pageToolsHarness.ts +79 -0
  150. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +316 -0
  151. package/src/modules/workspace/components/renderers/htmlSandbox.ts +75 -13
  152. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +196 -25
  153. package/src/modules/workspace/components/renderers/index.ts +10 -0
  154. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +253 -0
  155. package/src/modules/workspace/hooks/useFullScreenView.ts +52 -0
  156. package/src/modules/workspace/hooks/useImageRevision.ts +1 -1
  157. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +1 -1
  158. package/src/modules/workspace/hooks/useLastCommit.ts +1 -1
  159. package/src/modules/workspace/hooks/useWorkspaceState.ts +4 -4
  160. package/src/modules/workspace/index.ts +30 -1
  161. package/src/modules/workspace/routing/kb-routes.ts +1 -1
  162. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +0 -1
  163. package/src/modules/workspace/state/open-change-requests.tsx +1 -1
  164. package/src/modules/workspace/utils/frameEscape.ts +15 -0
  165. package/src/modules/workspace/utils/treeConfirm.ts +1 -1
  166. package/src/shared/theme/measure.ts +7 -0
  167. package/src/modules/pr/services/pr-comments.api.ts +0 -45
@@ -0,0 +1,316 @@
1
+ import { useRef } from 'react';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
4
+ import { MemoryRouter } from 'react-router-dom';
5
+ import {
6
+ OpenPageInPlatformContext,
7
+ PageToolsContext,
8
+ RendererSurfaceContext,
9
+ useHtmlToolBridge,
10
+ type RendererSurface,
11
+ } from '..';
12
+ import { GitContext, type GitContextValue } from '../../../../git';
13
+ import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
14
+ import { frameChannel, stubServer } from './pageToolsHarness';
15
+
16
+ /**
17
+ * The bridge controller's contract, through a renderer that is not the app's:
18
+ * a component that owns its frame, calls `useHtmlToolBridge` with the frame,
19
+ * its file and its view key, and renders the cards it hands back — exactly
20
+ * what a distribution's own HTML renderer does. Everything comes from the
21
+ * renderers module's entry. The frame stays the same element across a view
22
+ * change here — the one window a browser keeps when a document is rebuilt in
23
+ * place — so the suite can show that an ended view's calls are answered into
24
+ * nobody: the controller decides them `closed` and never posts the reply.
25
+ */
26
+
27
+ const PATH = 'knowledge-base/Dashboards/Roadmap.html';
28
+ const PAGE = 'Dashboards/Roadmap.html';
29
+
30
+ const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
31
+ const git = { status: { branch: 'main' } } as unknown as GitContextValue;
32
+
33
+ /** A downstream renderer: its own frame and document, the controller's bridge. */
34
+ function OtherHtmlRenderer({ viewKey }: { viewKey: number }) {
35
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
36
+ const { toolBridge, cards } = useHtmlToolBridge({ iframeRef, filePath: PATH, viewKey });
37
+ // The document carries the identity the controller minted for it, as the
38
+ // real runtime does (`buildSandboxedHtml` with this `toolBridge`).
39
+ const srcDoc = `${toolBridge.tools ? 'with tools' : 'without tools'} documentId="${toolBridge.documentId}"`;
40
+ return (
41
+ <>
42
+ <iframe ref={iframeRef} title="page" sandbox="allow-scripts" srcDoc={srcDoc} />
43
+ {cards}
44
+ </>
45
+ );
46
+ }
47
+
48
+ type Where = 'file page' | 'elsewhere' | 'embed';
49
+
50
+ function mount(where: Where, opts: { openFilePage?: (path: string) => void; openInPlatform?: () => void } = {}) {
51
+ const surface: RendererSurface = {
52
+ kbDirName: 'knowledge-base',
53
+ openLink: () => undefined,
54
+ openWorkspacePath: () => undefined,
55
+ openFilePage: opts.openFilePage ?? (() => undefined),
56
+ openNodeId: () => undefined,
57
+ canonicalUrlFor: () => null,
58
+ rawUrl: (path) => `/raw/${path}`,
59
+ rawFetch: async () => new Response(''),
60
+ offersDownload: false,
61
+ };
62
+ const tree = (viewKey: number) => {
63
+ const renderer = opts.openInPlatform ? (
64
+ <OpenPageInPlatformContext.Provider value={opts.openInPlatform}>
65
+ <OtherHtmlRenderer viewKey={viewKey} />
66
+ </OpenPageInPlatformContext.Provider>
67
+ ) : (
68
+ <OtherHtmlRenderer viewKey={viewKey} />
69
+ );
70
+ // A page-tools provider on the embed too: a surface never gets tools, whatever is above it.
71
+ const placed =
72
+ where === 'embed' ? (
73
+ <PageToolsContext.Provider value={{ pagePath: PAGE }}>
74
+ <RendererSurfaceContext.Provider value={surface}>{renderer}</RendererSurfaceContext.Provider>
75
+ </PageToolsContext.Provider>
76
+ ) : where === 'file page' ? (
77
+ <PageToolsContext.Provider value={{ pagePath: PAGE }}>{renderer}</PageToolsContext.Provider>
78
+ ) : (
79
+ renderer
80
+ );
81
+ return (
82
+ <MemoryRouter>
83
+ <WorkspaceContext.Provider value={workspace}>
84
+ <GitContext.Provider value={git}>{placed}</GitContext.Provider>
85
+ </WorkspaceContext.Provider>
86
+ </MemoryRouter>
87
+ );
88
+ };
89
+ let viewKey = 0;
90
+ const result = render(tree(viewKey));
91
+ const iframe = result.container.querySelector('iframe')!;
92
+ return {
93
+ iframe,
94
+ frame: frameChannel(iframe),
95
+ /**
96
+ * The renderer's view ends (a reload, a rebuilt document) while its
97
+ * frame stays. Answers a channel for the NEW document; the one taken
98
+ * before still posts as the old document.
99
+ */
100
+ nextView: () => {
101
+ viewKey += 1;
102
+ result.rerender(tree(viewKey));
103
+ return frameChannel(iframe);
104
+ },
105
+ };
106
+ }
107
+
108
+ const write = (requestId: string) => ({ type: 'bevel.tool.call', requestId, fn: 'callTool', args: ['edit_file', {}] });
109
+ const CARD = 'Roadmap wants to write to the knowledge base';
110
+
111
+ afterEach(() => {
112
+ cleanup();
113
+ vi.restoreAllMocks();
114
+ vi.unstubAllGlobals();
115
+ });
116
+
117
+ describe('useHtmlToolBridge through a renderer of its own', () => {
118
+ it('builds the frame with tools on the file page only, each view\'s document with its own identity', () => {
119
+ const page = mount('file page');
120
+ expect(page.iframe.getAttribute('srcdoc')).toMatch(/^with tools documentId="doc-/);
121
+ const first = page.frame.documentId;
122
+ const next = page.nextView();
123
+ expect(next.documentId).toMatch(/^doc-/);
124
+ expect(next.documentId).not.toBe(first);
125
+ cleanup();
126
+ expect(mount('elsewhere').iframe.getAttribute('srcdoc')).toMatch(/^without tools documentId="doc-/);
127
+ cleanup();
128
+ expect(mount('embed').iframe.getAttribute('srcdoc')).toMatch(/^without tools documentId="doc-/);
129
+ });
130
+
131
+ it('on a view without tools, a requireTools from the replaced document is ignored too', async () => {
132
+ const { frame: old, nextView } = mount('embed');
133
+ const current = nextView();
134
+ old.post({ type: 'bevel.tools.require', requestId: 'q1' });
135
+ await settled();
136
+ expect(screen.queryByText(/only available in the platform/)).toBeNull();
137
+ expect(old.replies).toEqual([]);
138
+ expect(current.replies).toEqual([]);
139
+
140
+ current.post({ type: 'bevel.tools.require', requestId: 'q2' });
141
+ expect(await screen.findByText('Roadmap uses tools that are only available in the platform')).toBeTruthy();
142
+ fireEvent.click(screen.getByRole('button', { name: 'Continue without tools' }));
143
+ await waitFor(() => expect(current.replies.at(-1)).toEqual({ type: 'bevel.tools.require.response', requestId: 'q2', ok: true, result: false }));
144
+ });
145
+
146
+ it('ignores a message from the document a view change replaced, and answers the new document', async () => {
147
+ // The old document queued its call before the change and the frame's
148
+ // window delivered it after: same window, old identity. Nothing of it
149
+ // runs or shows; the new document's own call is answered.
150
+ const server = stubServer();
151
+ const { frame: old, nextView } = mount('file page');
152
+ const current = nextView();
153
+ old.post(write('w1'));
154
+ old.post({ type: 'bevel.tools.require', requestId: 'q1' });
155
+ await settled();
156
+ expect(screen.queryByRole('dialog')).toBeNull();
157
+ // Nothing posted to the window at all: neither the old channel nor the new one hears a reply.
158
+ expect(old.replies).toEqual([]);
159
+ expect(current.replies).toEqual([]);
160
+ expect(server.mcp).toEqual([]);
161
+
162
+ current.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
163
+ await waitFor(() => expect(current.replies).toEqual([{ type: 'bevel.tool.response', requestId: 'r1', ok: true, result: { ran: 'read_file' } }]));
164
+ expect(server.mcp).toEqual(['read_file']);
165
+ });
166
+
167
+ it('runs a read with no card', async () => {
168
+ const server = stubServer();
169
+ const { frame } = mount('file page');
170
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
171
+ await waitFor(() => expect(frame.replies).toEqual([{ type: 'bevel.tool.response', requestId: 'r1', ok: true, result: { ran: 'read_file' } }]));
172
+ expect(screen.queryByText(CARD)).toBeNull();
173
+ expect(server.mcp).toEqual(['read_file']);
174
+ });
175
+
176
+ it('asks once for ten writes at once; Allow answers all ten and holds for the view; a new view asks again', async () => {
177
+ const server = stubServer();
178
+ const { frame, nextView } = mount('file page');
179
+ for (let i = 0; i < 10; i += 1) frame.post(write(`w${i}`));
180
+ expect(await screen.findByText(CARD)).toBeTruthy();
181
+ expect(screen.getByText(PAGE)).toBeTruthy();
182
+ expect(screen.getAllByRole('button', { name: 'Allow while open' })).toHaveLength(1);
183
+ expect(server.mcp).toEqual([]);
184
+
185
+ fireEvent.click(screen.getByRole('button', { name: 'Allow while open' }));
186
+ await waitFor(() => expect(frame.replies).toHaveLength(10));
187
+ expect(frame.replies.every((r) => r.ok === true)).toBe(true);
188
+
189
+ frame.post(write('w10'));
190
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w10', ok: true }));
191
+ expect(screen.queryByText(CARD)).toBeNull();
192
+
193
+ const next = nextView();
194
+ next.post(write('w11'));
195
+ expect(await screen.findByText(CARD)).toBeTruthy();
196
+ });
197
+
198
+ it('Deny answers denied and runs nothing; the next write asks again', async () => {
199
+ const server = stubServer();
200
+ const { frame } = mount('file page');
201
+ frame.post(write('w1'));
202
+ fireEvent.click(await screen.findByRole('button', { name: 'Deny' }));
203
+ await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'w1', ok: false, error: 'denied', code: 'denied' }));
204
+ expect(server.mcp).toEqual([]);
205
+ frame.post(write('w2'));
206
+ expect(await screen.findByText(CARD)).toBeTruthy();
207
+ });
208
+
209
+ // The frame keeps its window across `nextView` here, as a browser's does
210
+ // when a document is rebuilt in the same frame element. So these cases
211
+ // show the whole of what an ended view's calls get: no card, nothing run,
212
+ // and no reply posted into the next view — the window alone would let one
213
+ // through. (`closed` is what `answerToolCall` decides; nobody is left to
214
+ // hear it.)
215
+ const settled = () => new Promise((r) => setTimeout(r, 50));
216
+
217
+ it('closes an open card when the view ends: nothing runs, and the next view hears nothing of it', async () => {
218
+ const server = stubServer();
219
+ const { frame, nextView } = mount('file page');
220
+ frame.post(write('w1'));
221
+ expect(await screen.findByText(CARD)).toBeTruthy();
222
+ nextView();
223
+ await waitFor(() => expect(screen.queryByText(CARD)).toBeNull());
224
+ await settled();
225
+ expect(frame.replies).toEqual([]);
226
+ expect(server.mcp).toEqual([]);
227
+ });
228
+
229
+ it('a call decided after its view ended shows no card, runs nothing, and is not answered into the next view', async () => {
230
+ const server = stubServer({ holdManual: true });
231
+ const { frame, nextView } = mount('file page');
232
+ frame.post(write('w1'));
233
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
234
+ nextView();
235
+ server.releaseManual();
236
+ await settled();
237
+ expect(frame.replies).toEqual([]);
238
+ expect(screen.queryByText(CARD)).toBeNull();
239
+ expect(server.mcp).toEqual([]);
240
+ });
241
+
242
+ it('runs nothing for calls still being decided when the view ends, even after its Allow, and answers none of them', async () => {
243
+ const server = stubServer();
244
+ const { frame, nextView } = mount('file page');
245
+ frame.post({ type: 'bevel.tool.call', requestId: 'c1', fn: 'callToolChain', args: ['return 1'] });
246
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
247
+ await waitFor(() => expect(frame.replies).toEqual([expect.objectContaining({ requestId: 'c1', ok: true })]));
248
+
249
+ frame.post(write('w1'));
250
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
251
+ frame.post({ type: 'bevel.tool.call', requestId: 'c2', fn: 'callToolChain', args: ['return 2'] });
252
+ nextView();
253
+ await settled();
254
+ expect(frame.replies).toHaveLength(1);
255
+ expect(screen.queryByText(CARD)).toBeNull();
256
+ expect(server.mcp).toEqual(['call_tool_chain']);
257
+ });
258
+
259
+ it('answers the new view\'s own calls after an older view\'s are dropped', async () => {
260
+ const server = stubServer();
261
+ const { frame, nextView } = mount('file page');
262
+ frame.post(write('w1'));
263
+ expect(await screen.findByText(CARD)).toBeTruthy();
264
+ const next = nextView();
265
+ await waitFor(() => expect(screen.queryByText(CARD)).toBeNull());
266
+ next.post({ type: 'bevel.tool.call', requestId: 'r2', fn: 'callTool', args: ['read_file', {}] });
267
+ await waitFor(() => expect(next.replies).toEqual([{ type: 'bevel.tool.response', requestId: 'r2', ok: true, result: { ran: 'read_file' } }]));
268
+ expect(frame.replies).toEqual([]);
269
+ expect(server.mcp).toEqual(['read_file']);
270
+ });
271
+
272
+ it('answers requireTools true on the file page with nothing shown', async () => {
273
+ const { frame } = mount('file page');
274
+ frame.post({ type: 'bevel.tools.require', requestId: 'q1' });
275
+ await waitFor(() => expect(frame.replies).toEqual([{ type: 'bevel.tools.require.response', requestId: 'q1', ok: true, result: true }]));
276
+ expect(screen.queryByRole('dialog')).toBeNull();
277
+ });
278
+
279
+ it('shows the platform card elsewhere: Continue without tools, and Open in the platform the host\'s way or the file page', async () => {
280
+ const openFilePage = vi.fn();
281
+ const { frame } = mount('embed', { openFilePage });
282
+ frame.post({ type: 'bevel.tools.require', requestId: 'q1' });
283
+ expect(await screen.findByText('Roadmap uses tools that are only available in the platform')).toBeTruthy();
284
+ fireEvent.click(screen.getByRole('button', { name: 'Continue without tools' }));
285
+ await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tools.require.response', requestId: 'q1', ok: true, result: false }));
286
+ frame.post({ type: 'bevel.tools.require', requestId: 'q2' });
287
+ fireEvent.click(await screen.findByRole('button', { name: 'Open in the platform' }));
288
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'q2', result: false }));
289
+ expect(openFilePage).toHaveBeenCalledWith(PATH);
290
+ cleanup();
291
+
292
+ const openInPlatform = vi.fn();
293
+ const elsewhere = mount('elsewhere', { openInPlatform });
294
+ elsewhere.frame.post({ type: 'bevel.tools.require', requestId: 'q3' });
295
+ fireEvent.click(await screen.findByRole('button', { name: 'Open in the platform' }));
296
+ await waitFor(() => expect(elsewhere.frame.replies.at(-1)).toMatchObject({ requestId: 'q3', result: false }));
297
+ expect(openInPlatform).toHaveBeenCalledTimes(1);
298
+ });
299
+
300
+ it('refuses a tool call outright where there are no tools', async () => {
301
+ const { frame } = mount('embed');
302
+ frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
303
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'r1', ok: false, code: 'unavailable' }));
304
+ });
305
+
306
+ it('ignores messages that do not come from its own frame', async () => {
307
+ const server = stubServer();
308
+ const { frame } = mount('file page');
309
+ window.dispatchEvent(new MessageEvent('message', { data: write('x1'), source: window }));
310
+ window.dispatchEvent(new MessageEvent('message', { data: { type: 'bevel.tools.require', requestId: 'x2' }, source: window }));
311
+ await new Promise((r) => setTimeout(r, 10));
312
+ expect(screen.queryByRole('dialog')).toBeNull();
313
+ expect(frame.replies).toEqual([]);
314
+ expect(server.mcp).toEqual([]);
315
+ });
316
+ });
@@ -392,6 +392,38 @@ const NAV_BRIDGE = `
392
392
  })();
393
393
  `;
394
394
 
395
+ /**
396
+ * Runtime that hands an Escape the page did not use to the parent.
397
+ *
398
+ * A key pressed while focus is inside the frame never reaches the app: the
399
+ * frame is its own document, and the sandbox gives the parent no way to
400
+ * listen in. So once a reader has clicked into a page, the app's Escape — a
401
+ * card's close, the file page's way out of full screen — went deaf. The frame
402
+ * posts `bevel.key` instead, and the parent decides what Escape means there
403
+ * (see `ExitFullScreenButton`).
404
+ *
405
+ * Only Escape, and only one the page left alone: an Escape one of the page's
406
+ * handlers cancelled (closing the page's own popup) is the page's. Which
407
+ * handlers run before this one is not the bridge's to choose — a handler the
408
+ * page adds to the window after the bridge ran (a module of its own, a popup
409
+ * that listens only while open) comes after it in the same phase — so the
410
+ * bridge does not decide while the key is still being dispatched. It looks
411
+ * on the next task, once the dispatch is over, every handler of the page's
412
+ * has had its turn and `defaultPrevented` is final.
413
+ */
414
+ const KEY_BRIDGE = `
415
+ ;(function () {
416
+ if (typeof globalThis.addEventListener !== 'function') return;
417
+ globalThis.addEventListener('keydown', function (e) {
418
+ if (e.key !== 'Escape') return;
419
+ setTimeout(function () {
420
+ if (e.defaultPrevented) return;
421
+ parent.postMessage({ type: 'bevel.key', key: 'Escape' }, '*');
422
+ }, 0);
423
+ });
424
+ })();
425
+ `;
426
+
395
427
  /**
396
428
  * How long a page waits for the app to answer one of its tool calls. Long,
397
429
  * because the answer may wait on a person: the first writing call shows a
@@ -407,29 +439,53 @@ export const TOOL_CALL_TIMEOUT_MS = 15 * 60 * 1000;
407
439
  * The frame has no network (`connect-src 'none'`), so a page reaches tools the
408
440
  * way it reaches navigation: it posts `bevel.tool.call` `{ requestId, fn, args }`
409
441
  * to the parent and awaits `bevel.tool.response` `{ requestId, ok, result |
410
- * error, code? }`. The parent (`HtmlRenderer`, through `htmlToolBridge.ts`)
442
+ * error, code? }`. The parent (an HTML renderer, through `useHtmlToolBridge`)
411
443
  * answers each one over the hosted MCP server with the viewer's session —
412
444
  * after asking the viewer, on the first call that writes. Nothing about the
413
445
  * consent lives in the frame: the card is the app's, drawn outside it, and a
414
446
  * page can neither see nor answer it.
415
447
  *
416
- * `tools` exists only where the app can answer it — the app's file page.
417
- * Everywhere else (the embed, a skill page, any other preview) it is `null`,
418
- * so a page checks `window.bevel && window.bevel.tools` before every use and
419
- * renders without tools when it is null. `requireTools()` is how a page that
420
- * needs them asks: it posts `bevel.tools.require` and resolves with the
421
- * parent's answer — `true` on the file page at once, `false` after the
448
+ * `uploadFile(file, options)` posts the `File` (or `Blob`) itself, by
449
+ * structured clone, beside the four options it reads (`name`, `branch`,
450
+ * `destination`, `mode`); the parent judges both, runs the agent upload path
451
+ * and posts back only `apply_file_upload`'s answer — the upload token never
452
+ * enters the frame.
453
+ *
454
+ * `tools` exists only where the app can answer it — the hosts that provide
455
+ * `PageToolsContext` (`htmlToolBridge.ts` lists them: the file page, the skill
456
+ * page). Everywhere else (the embed, the change-request and history previews)
457
+ * it is `null`, so a page checks `window.bevel && window.bevel.tools` before
458
+ * every use and renders without tools when it is null. `requireTools()` is how
459
+ * a page that needs them asks: it posts `bevel.tools.require` and resolves with the
460
+ * parent's answer — `true` at once where tools are answered, `false` after the
422
461
  * parent's card offered the way to the platform and the viewer chose either.
423
462
  *
424
463
  * Every response is matched to its request by id, and only from `parent`.
425
464
  * The `html-views` section of the agent guide documents the members, and
426
465
  * `htmlViewsGuide.test.ts` holds the two together.
427
466
  */
428
- function toolBridgeRuntime(enabled: boolean): string {
467
+ /**
468
+ * `toolBridge`: what the document's runtime posts as, and whether it gets the
469
+ * tools. An object carries `documentId`, the identity the app minted for THIS
470
+ * document, which the runtime stamps on every message it posts (tool calls
471
+ * and `requireTools()` alike) — so the app can tell a message queued by a
472
+ * document it has since replaced (the frame's window survives a rebuild in
473
+ * place) from one the current document posts; `tools: false` gives such a
474
+ * document `bevel.tools = null` while it still asks as itself. `true` builds
475
+ * the tools without an identity, for a host that answers one document only;
476
+ * `false` or absent builds neither.
477
+ */
478
+ export type ToolBridgeOption = boolean | { documentId: string; tools?: boolean };
479
+
480
+ function toolBridgeRuntime(option: ToolBridgeOption | undefined): string {
481
+ const withIdentity = typeof option === 'object' && option !== null ? option : null;
482
+ const enabled = option === true || (withIdentity !== null && withIdentity.tools !== false);
483
+ const documentId = withIdentity?.documentId ?? null;
429
484
  return `
430
485
  ;(function () {
431
486
  var pending = {};
432
487
  var seq = 0;
488
+ var documentId = ${JSON.stringify(documentId)};
433
489
  function request(type, payload) {
434
490
  return new Promise(function (resolve, reject) {
435
491
  seq += 1;
@@ -440,6 +496,7 @@ function toolBridgeRuntime(enabled: boolean): string {
440
496
  }, ${TOOL_CALL_TIMEOUT_MS});
441
497
  pending[requestId] = { resolve: resolve, reject: reject, timer: timer };
442
498
  var message = { type: type, requestId: requestId };
499
+ if (documentId !== null) message.documentId = documentId;
443
500
  for (var key in payload) message[key] = payload[key];
444
501
  parent.postMessage(message, '*');
445
502
  });
@@ -468,7 +525,11 @@ function toolBridgeRuntime(enabled: boolean): string {
468
525
  searchTools: function (query) { return call('searchTools', [query === undefined ? '' : query]); },
469
526
  toolsInfo: function (names) { return call('toolsInfo', [names]); },
470
527
  callTool: function (name, args) { return call('callTool', [name, args === undefined ? {} : args]); },
471
- callToolChain: function (code) { return call('callToolChain', [code]); }
528
+ callToolChain: function (code) { return call('callToolChain', [code]); },
529
+ uploadFile: function (file, options) {
530
+ var o = options && typeof options === 'object' ? options : {};
531
+ return call('uploadFile', [file, { name: o.name, branch: o.branch, destination: o.destination, mode: o.mode }]);
532
+ }
472
533
  })` : 'null'};
473
534
  globalThis.bevel.requireTools = function () {
474
535
  return request('bevel.tools.require', {}).then(function (answer) { return answer === true; });
@@ -493,10 +554,11 @@ interface BuildSandboxedHtmlOptions {
493
554
  bodyHtml: string;
494
555
  /**
495
556
  * Give the page `window.bevel.tools`: only where the parent answers tool
496
- * calls, which is the app's file page. Absent or false, the member is
497
- * `null`; `requireTools()` exists either way.
557
+ * calls — the hosts `PageToolsContext` lists in `htmlToolBridge.ts`.
558
+ * Absent or false, the member is `null`; `requireTools()` exists either
559
+ * way.
498
560
  */
499
- toolBridge?: boolean;
561
+ toolBridge?: ToolBridgeOption;
500
562
  }
501
563
 
502
564
  /**
@@ -508,7 +570,7 @@ interface BuildSandboxedHtmlOptions {
508
570
  export function buildSandboxedHtml(opts: BuildSandboxedHtmlOptions): string {
509
571
  const lib = opts.libModuleSources.map(stripRelativeImports).join('\n\n');
510
572
  const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\n`;
511
- const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + toolBridgeRuntime(opts.toolBridge === true));
573
+ const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + KEY_BRIDGE + toolBridgeRuntime(opts.toolBridge));
512
574
 
513
575
  // Title and body are content-only — `srcDoc` already isolates them, but we
514
576
  // still want to escape the few characters that would terminate the parent