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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +1 -1
  3. package/src/lib/__tests__/api.test.ts +28 -1
  4. package/src/lib/api.ts +4 -2
  5. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  6. package/src/modules/access/api.ts +4 -5
  7. package/src/modules/access/components/ManageAccessDialog.tsx +11 -12
  8. package/src/modules/access/hooks/useAccessRequests.ts +1 -1
  9. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  10. package/src/modules/access/index.ts +11 -0
  11. package/src/modules/access/requests.api.ts +1 -1
  12. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  13. package/src/modules/admin/components/AddMemberInput.tsx +1 -1
  14. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  15. package/src/modules/admin/components/UserAccountsPage.tsx +3 -3
  16. package/src/modules/admin/index.ts +7 -0
  17. package/src/modules/admin/services/groups.api.ts +11 -1
  18. package/src/modules/admin/state/admin.context.tsx +1 -1
  19. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  20. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  21. package/src/modules/agents/connect-as.ts +15 -0
  22. package/src/modules/agents/index.ts +5 -0
  23. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  24. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  25. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  26. package/src/modules/audit/components/AuditEventsPanel.tsx +1 -1
  27. package/src/modules/audit/components/AuditLogPage.tsx +11 -2
  28. package/src/modules/audit/services/audit.api.ts +5 -0
  29. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  30. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  31. package/src/modules/auth/components/AccountPage.tsx +8 -2
  32. package/src/modules/auth/index.ts +12 -0
  33. package/src/modules/auth/services/account.api.ts +18 -2
  34. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +0 -1
  35. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +0 -1
  36. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +0 -1
  37. package/src/modules/change-requests/__tests__/ChangeRequestDialog.edit.test.tsx +166 -0
  38. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +0 -1
  39. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +0 -1
  40. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +0 -1
  41. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +0 -1
  42. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +0 -2
  43. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +0 -1
  44. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +0 -1
  45. package/src/modules/change-requests/components/BranchFilePreview.tsx +4 -12
  46. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +138 -30
  47. package/src/modules/change-requests/components/ChangeRequestLink.tsx +2 -3
  48. package/src/modules/change-requests/components/CrFileTree.tsx +1 -1
  49. package/src/modules/change-requests/components/FileChangeBoxes.tsx +2 -3
  50. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +3 -5
  51. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +1 -1
  52. package/src/modules/change-requests/index.ts +14 -0
  53. package/src/modules/change-requests/services/change-requests.api.ts +2 -2
  54. package/src/modules/change-requests/services/denied-file.api.ts +2 -2
  55. package/src/modules/change-requests/services/propose.api.ts +3 -4
  56. package/src/modules/change-requests/utils/diff.ts +1 -1
  57. package/src/modules/change-requests/utils/readFailure.ts +1 -1
  58. package/src/modules/embed/__tests__/EmbedView.test.tsx +19 -2
  59. package/src/modules/embed/components/EmbedLinkPage.tsx +1 -2
  60. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  61. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  62. package/src/modules/git/components/BranchSwitcher.tsx +3 -4
  63. package/src/modules/git/components/FileHistoryPanel.tsx +2 -2
  64. package/src/modules/git/components/GitSyncFailedBanner.tsx +2 -4
  65. package/src/modules/git/components/HistoryVersionPreview.tsx +4 -15
  66. package/src/modules/git/components/PullNeededBanner.tsx +1 -1
  67. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  68. package/src/modules/git/hooks/useAutoPullUpdates.ts +1 -1
  69. package/src/modules/git/index.ts +11 -0
  70. package/src/modules/layout/components/MobileChatLayout.tsx +1 -1
  71. package/src/modules/layout/index.ts +9 -0
  72. package/src/modules/library/__tests__/SkillPage.test.tsx +268 -24
  73. package/src/modules/library/__tests__/propose-change.test.ts +75 -0
  74. package/src/modules/library/components/AddToPluginDialog.tsx +1 -1
  75. package/src/modules/library/components/ChangeRequestDock.tsx +1 -1
  76. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  77. package/src/modules/library/components/LibraryPage.tsx +3 -3
  78. package/src/modules/library/components/ManagedPluginRequests.tsx +1 -1
  79. package/src/modules/library/components/NewSkillPanel.tsx +2 -2
  80. package/src/modules/library/components/PersonalAddDialog.tsx +1 -1
  81. package/src/modules/library/components/PersonalPluginPage.tsx +1 -1
  82. package/src/modules/library/components/PluginExtras.tsx +1 -4
  83. package/src/modules/library/components/PluginPage.tsx +1 -1
  84. package/src/modules/library/components/PluginRows.tsx +1 -1
  85. package/src/modules/library/components/SkillsTree.tsx +1 -4
  86. package/src/modules/library/components/plugin-page-parts.tsx +1 -1
  87. package/src/modules/library/components/skill-page/SkillFilePane.tsx +74 -14
  88. package/src/modules/library/components/skill-page/SkillPage.tsx +80 -47
  89. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +2 -4
  90. package/src/modules/library/components/tool-page/ToolVarRow.tsx +2 -2
  91. package/src/modules/library/hooks/useJoinRequests.ts +1 -1
  92. package/src/modules/library/hooks/useLibraryData.ts +3 -3
  93. package/src/modules/library/hooks/useToolPage.ts +1 -1
  94. package/src/modules/library/hooks/useToolSource.ts +1 -1
  95. package/src/modules/library/index.ts +12 -0
  96. package/src/modules/library/routes/LibraryRoutes.tsx +1 -1
  97. package/src/modules/library/routes/WorkspaceItemRoute.tsx +1 -3
  98. package/src/modules/library/routes/library-paths.ts +1 -1
  99. package/src/modules/library/services/library.api.ts +10 -8
  100. package/src/modules/library/services/plugins.api.ts +1 -1
  101. package/src/modules/library/services/teams.api.ts +1 -1
  102. package/src/modules/library/utils/status.ts +2 -2
  103. package/src/modules/onboarding/components/ConnectAgentPill.tsx +1 -1
  104. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +2 -3
  105. package/src/modules/onboarding/components/GetStartedColumn.tsx +6 -13
  106. package/src/modules/onboarding/components/InviteButton.tsx +2 -2
  107. package/src/modules/onboarding/components/InviteDialog.tsx +4 -6
  108. package/src/modules/onboarding/components/RootLanding.tsx +2 -2
  109. package/src/modules/onboarding/components/StarterPackCard.tsx +1 -1
  110. package/src/modules/onboarding/components/WelcomePage.tsx +2 -5
  111. package/src/modules/onboarding/index.ts +10 -0
  112. package/src/modules/onboarding/paths.ts +1 -1
  113. package/src/modules/onboarding/state/agent-connection.ts +2 -2
  114. package/src/modules/onboarding/state/onboarding.ts +1 -1
  115. package/src/modules/onboarding/state/starter-packs.ts +1 -1
  116. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +1 -1
  117. package/src/modules/pr/index.ts +14 -0
  118. package/src/modules/pr/services/pr-approvals.api.ts +1 -1
  119. package/src/modules/pr/services/pr-cancel.api.ts +1 -1
  120. package/src/modules/pr/services/pr-detail.api.ts +2 -2
  121. package/src/modules/pr/services/pr-edit.api.ts +22 -0
  122. package/src/modules/pr/services/pr-merge.api.ts +1 -1
  123. package/src/modules/pr/services/pr-open.api.ts +1 -1
  124. package/src/modules/review/components/DiffViewer.tsx +1 -1
  125. package/src/modules/review/components/MarkdownDiffViewer.tsx +24 -3
  126. package/src/modules/review/components/ReviewPanel.tsx +10 -5
  127. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  128. package/src/modules/review/state/ReviewProvider.tsx +2 -2
  129. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  130. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  131. package/src/modules/secrets-vault/index.ts +6 -0
  132. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  133. package/src/modules/settings/components/DeploymentPage.tsx +2 -2
  134. package/src/modules/settings/components/SettingsLayout.tsx +2 -2
  135. package/src/modules/settings/index.ts +8 -0
  136. package/src/modules/setup/components/FirstRunStorage.tsx +1 -1
  137. package/src/modules/setup/index.ts +6 -0
  138. package/src/modules/toolbar/commands/actions.tsx +3 -3
  139. package/src/modules/toolbar/commands/useCommandActions.ts +5 -9
  140. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +2 -2
  141. package/src/modules/toolbar/components/AppSwitcher.tsx +1 -2
  142. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +1 -1
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +39 -5
  144. package/src/modules/toolbar/components/ProfileMenu.tsx +3 -3
  145. package/src/modules/toolbar/components/SearchPalette.tsx +4 -8
  146. package/src/modules/toolbar/components/Toolbar.tsx +2 -5
  147. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  148. package/src/modules/toolbar/index.ts +6 -0
  149. package/src/modules/toolbar/search/sources.ts +4 -7
  150. package/src/modules/toolbar/services/agent-instructions.api.ts +1 -1
  151. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  152. package/src/modules/tools/ToolsExplorerPage.tsx +217 -18
  153. package/src/modules/tools/__tests__/ToolsExplorerPage.read-only.test.tsx +220 -0
  154. package/src/modules/tools/tool-hints.api.ts +44 -0
  155. package/src/modules/workflow/index.ts +7 -0
  156. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +1 -0
  157. package/src/modules/workflow/state/EventBusFocusBinder.tsx +1 -1
  158. package/src/modules/workspace/components/FileExplorer.tsx +35 -8
  159. package/src/modules/workspace/components/FilePaneCard.tsx +37 -12
  160. package/src/modules/workspace/components/FileRoute.tsx +10 -3
  161. package/src/modules/workspace/components/FileViewer.tsx +169 -25
  162. package/src/modules/workspace/components/FullScreenView.tsx +93 -0
  163. package/src/modules/workspace/components/KbFileRail.tsx +1 -1
  164. package/src/modules/workspace/components/KbPageHeader.tsx +9 -0
  165. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +163 -0
  166. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +11 -0
  167. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +487 -3
  168. package/src/modules/workspace/components/readingCarry.ts +59 -0
  169. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +74 -180
  170. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  171. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  172. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  173. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +1 -1
  174. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  175. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +168 -42
  176. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  177. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  178. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +57 -7
  179. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +122 -4
  180. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +235 -1
  181. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +29 -4
  182. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  183. package/src/modules/workspace/components/renderers/__tests__/pageToolsHarness.ts +79 -0
  184. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +316 -0
  185. package/src/modules/workspace/components/renderers/htmlSandbox.ts +123 -28
  186. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +215 -25
  187. package/src/modules/workspace/components/renderers/index.ts +10 -0
  188. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  189. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  190. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +253 -0
  191. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  192. package/src/modules/workspace/hooks/useFullScreenView.ts +52 -0
  193. package/src/modules/workspace/hooks/useImageRevision.ts +1 -1
  194. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +1 -1
  195. package/src/modules/workspace/hooks/useLastCommit.ts +1 -1
  196. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  197. package/src/modules/workspace/hooks/useWorkspaceState.ts +4 -4
  198. package/src/modules/workspace/index.ts +50 -2
  199. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  200. package/src/modules/workspace/routing/kb-routes.ts +222 -54
  201. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +0 -1
  202. package/src/modules/workspace/state/open-change-requests.tsx +1 -1
  203. package/src/modules/workspace/utils/fileTree.ts +1 -1
  204. package/src/modules/workspace/utils/frameEscape.ts +15 -0
  205. package/src/modules/workspace/utils/treeConfirm.ts +1 -1
  206. package/src/shared/theme/measure.ts +7 -0
  207. 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
+ });
@@ -373,25 +373,80 @@ const NAV_BRIDGE = `
373
373
  }
374
374
  globalThis.bevel.openNode = navigate;
375
375
  globalThis.bevel.navigate = navigate;
376
+ // A link that names this page's own file with a fragment
377
+ // ('Roadmap.html#q3') is posted like any path; the parent recognises the
378
+ // file and hands the fragment back to be scrolled here, as '#q3' is.
379
+ if (typeof globalThis.addEventListener === 'function') globalThis.addEventListener('message', function (event) {
380
+ if (event.source !== parent) return;
381
+ var msg = event.data;
382
+ if (!msg || typeof msg !== 'object' || msg.type !== 'bevel.jump' || typeof msg.hash !== 'string') return;
383
+ var hash = normalize(msg.hash);
384
+ if (hash.charAt(0) === '#') jumpTo(hash);
385
+ });
386
+ // A click the reader asked a NEW TAB of — Ctrl, Cmd or Shift held, or the
387
+ // middle button (an 'auxclick'; it never fires 'click') — is what a browser
388
+ // opens a new tab for. The frame cannot: the sandbox has no allow-popups,
389
+ // so left to the browser it opens nothing, or navigates the frame away.
390
+ // The parent is asked instead, for any destination, a fragment of this
391
+ // page included (the parent opens this page at that section).
392
+ function followLink(e) {
393
+ if (e.type === 'auxclick' && e.button !== 1) return;
394
+ var el = e.target;
395
+ var a = el && el.closest ? el.closest('a[href]') : null;
396
+ if (!a) return;
397
+ // A handler of the page's own that already cancelled this click owns
398
+ // it (a toggle, a hash router); the bridge stays out of its way.
399
+ if (e.defaultPrevented) return;
400
+ // Cancelled even when there is nowhere to go: left to the browser, an
401
+ // empty href reloads the frame against the app's URL, as '#…' would.
402
+ e.preventDefault();
403
+ var href = normalize(a.getAttribute('href') || '');
404
+ if (!href) return;
405
+ if (e.button === 1 || e.ctrlKey || e.metaKey || e.shiftKey) {
406
+ parent.postMessage({ type: 'bevel.navigate', href: href, newTab: true }, '*');
407
+ return;
408
+ }
409
+ navigate(href);
410
+ }
376
411
  if (typeof document !== 'undefined') {
377
- document.addEventListener('click', function (e) {
378
- var el = e.target;
379
- var a = el && el.closest ? el.closest('a[href]') : null;
380
- if (!a) return;
381
- // A handler of the page's own that already cancelled this click owns
382
- // it (a toggle, a hash router); the bridge stays out of its way.
383
- if (e.defaultPrevented) return;
384
- // Cancelled even when there is nowhere to go: left to the browser, an
385
- // empty href reloads the frame against the app's URL, as '#…' would.
386
- e.preventDefault();
387
- var href = normalize(a.getAttribute('href') || '');
388
- if (!href) return;
389
- navigate(href);
390
- });
412
+ document.addEventListener('click', followLink);
413
+ document.addEventListener('auxclick', followLink);
391
414
  }
392
415
  })();
393
416
  `;
394
417
 
418
+ /**
419
+ * Runtime that hands an Escape the page did not use to the parent.
420
+ *
421
+ * A key pressed while focus is inside the frame never reaches the app: the
422
+ * frame is its own document, and the sandbox gives the parent no way to
423
+ * listen in. So once a reader has clicked into a page, the app's Escape — a
424
+ * card's close, the file page's way out of full screen — went deaf. The frame
425
+ * posts `bevel.key` instead, and the parent decides what Escape means there
426
+ * (see `ExitFullScreenButton`).
427
+ *
428
+ * Only Escape, and only one the page left alone: an Escape one of the page's
429
+ * handlers cancelled (closing the page's own popup) is the page's. Which
430
+ * handlers run before this one is not the bridge's to choose — a handler the
431
+ * page adds to the window after the bridge ran (a module of its own, a popup
432
+ * that listens only while open) comes after it in the same phase — so the
433
+ * bridge does not decide while the key is still being dispatched. It looks
434
+ * on the next task, once the dispatch is over, every handler of the page's
435
+ * has had its turn and `defaultPrevented` is final.
436
+ */
437
+ const KEY_BRIDGE = `
438
+ ;(function () {
439
+ if (typeof globalThis.addEventListener !== 'function') return;
440
+ globalThis.addEventListener('keydown', function (e) {
441
+ if (e.key !== 'Escape') return;
442
+ setTimeout(function () {
443
+ if (e.defaultPrevented) return;
444
+ parent.postMessage({ type: 'bevel.key', key: 'Escape' }, '*');
445
+ }, 0);
446
+ });
447
+ })();
448
+ `;
449
+
395
450
  /**
396
451
  * How long a page waits for the app to answer one of its tool calls. Long,
397
452
  * because the answer may wait on a person: the first writing call shows a
@@ -407,29 +462,53 @@ export const TOOL_CALL_TIMEOUT_MS = 15 * 60 * 1000;
407
462
  * The frame has no network (`connect-src 'none'`), so a page reaches tools the
408
463
  * way it reaches navigation: it posts `bevel.tool.call` `{ requestId, fn, args }`
409
464
  * to the parent and awaits `bevel.tool.response` `{ requestId, ok, result |
410
- * error, code? }`. The parent (`HtmlRenderer`, through `htmlToolBridge.ts`)
465
+ * error, code? }`. The parent (an HTML renderer, through `useHtmlToolBridge`)
411
466
  * answers each one over the hosted MCP server with the viewer's session —
412
467
  * after asking the viewer, on the first call that writes. Nothing about the
413
468
  * consent lives in the frame: the card is the app's, drawn outside it, and a
414
469
  * page can neither see nor answer it.
415
470
  *
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
471
+ * `uploadFile(file, options)` posts the `File` (or `Blob`) itself, by
472
+ * structured clone, beside the four options it reads (`name`, `branch`,
473
+ * `destination`, `mode`); the parent judges both, runs the agent upload path
474
+ * and posts back only `apply_file_upload`'s answer — the upload token never
475
+ * enters the frame.
476
+ *
477
+ * `tools` exists only where the app can answer it — the hosts that provide
478
+ * `PageToolsContext` (`htmlToolBridge.ts` lists them: the file page, the skill
479
+ * page). Everywhere else (the embed, the change-request and history previews)
480
+ * it is `null`, so a page checks `window.bevel && window.bevel.tools` before
481
+ * every use and renders without tools when it is null. `requireTools()` is how
482
+ * a page that needs them asks: it posts `bevel.tools.require` and resolves with the
483
+ * parent's answer — `true` at once where tools are answered, `false` after the
422
484
  * parent's card offered the way to the platform and the viewer chose either.
423
485
  *
424
486
  * Every response is matched to its request by id, and only from `parent`.
425
487
  * The `html-views` section of the agent guide documents the members, and
426
488
  * `htmlViewsGuide.test.ts` holds the two together.
427
489
  */
428
- function toolBridgeRuntime(enabled: boolean): string {
490
+ /**
491
+ * `toolBridge`: what the document's runtime posts as, and whether it gets the
492
+ * tools. An object carries `documentId`, the identity the app minted for THIS
493
+ * document, which the runtime stamps on every message it posts (tool calls
494
+ * and `requireTools()` alike) — so the app can tell a message queued by a
495
+ * document it has since replaced (the frame's window survives a rebuild in
496
+ * place) from one the current document posts; `tools: false` gives such a
497
+ * document `bevel.tools = null` while it still asks as itself. `true` builds
498
+ * the tools without an identity, for a host that answers one document only;
499
+ * `false` or absent builds neither.
500
+ */
501
+ export type ToolBridgeOption = boolean | { documentId: string; tools?: boolean };
502
+
503
+ function toolBridgeRuntime(option: ToolBridgeOption | undefined): string {
504
+ const withIdentity = typeof option === 'object' && option !== null ? option : null;
505
+ const enabled = option === true || (withIdentity !== null && withIdentity.tools !== false);
506
+ const documentId = withIdentity?.documentId ?? null;
429
507
  return `
430
508
  ;(function () {
431
509
  var pending = {};
432
510
  var seq = 0;
511
+ var documentId = ${JSON.stringify(documentId)};
433
512
  function request(type, payload) {
434
513
  return new Promise(function (resolve, reject) {
435
514
  seq += 1;
@@ -440,6 +519,7 @@ function toolBridgeRuntime(enabled: boolean): string {
440
519
  }, ${TOOL_CALL_TIMEOUT_MS});
441
520
  pending[requestId] = { resolve: resolve, reject: reject, timer: timer };
442
521
  var message = { type: type, requestId: requestId };
522
+ if (documentId !== null) message.documentId = documentId;
443
523
  for (var key in payload) message[key] = payload[key];
444
524
  parent.postMessage(message, '*');
445
525
  });
@@ -468,7 +548,11 @@ function toolBridgeRuntime(enabled: boolean): string {
468
548
  searchTools: function (query) { return call('searchTools', [query === undefined ? '' : query]); },
469
549
  toolsInfo: function (names) { return call('toolsInfo', [names]); },
470
550
  callTool: function (name, args) { return call('callTool', [name, args === undefined ? {} : args]); },
471
- callToolChain: function (code) { return call('callToolChain', [code]); }
551
+ callToolChain: function (code) { return call('callToolChain', [code]); },
552
+ uploadFile: function (file, options) {
553
+ var o = options && typeof options === 'object' ? options : {};
554
+ return call('uploadFile', [file, { name: o.name, branch: o.branch, destination: o.destination, mode: o.mode }]);
555
+ }
472
556
  })` : 'null'};
473
557
  globalThis.bevel.requireTools = function () {
474
558
  return request('bevel.tools.require', {}).then(function (answer) { return answer === true; });
@@ -493,10 +577,19 @@ interface BuildSandboxedHtmlOptions {
493
577
  bodyHtml: string;
494
578
  /**
495
579
  * 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.
580
+ * calls — the hosts `PageToolsContext` lists in `htmlToolBridge.ts`.
581
+ * Absent or false, the member is `null`; `requireTools()` exists either
582
+ * way.
583
+ */
584
+ toolBridge?: ToolBridgeOption;
585
+ /**
586
+ * The branch the page is viewed on — `window.bevel.branch` inside the frame,
587
+ * so a page that reads its data through the tools and links to what they
588
+ * name does both on the branch it is shown on, rather than on one written
589
+ * into its script. Absent where the host has no branch for the page (the
590
+ * embed, a mail body), where the member is `null`.
498
591
  */
499
- toolBridge?: boolean;
592
+ branch?: string;
500
593
  }
501
594
 
502
595
  /**
@@ -507,8 +600,10 @@ interface BuildSandboxedHtmlOptions {
507
600
  */
508
601
  export function buildSandboxedHtml(opts: BuildSandboxedHtmlOptions): string {
509
602
  const lib = opts.libModuleSources.map(stripRelativeImports).join('\n\n');
510
- const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\n`;
511
- const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + toolBridgeRuntime(opts.toolBridge === true));
603
+ // `branch` is data, not code: serialized as JSON into the literal, so a
604
+ // branch name can hold nothing the script would read as source.
605
+ const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\nglobalThis.bevel.branch = ${JSON.stringify(opts.branch ?? null)};\n`;
606
+ const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + KEY_BRIDGE + toolBridgeRuntime(opts.toolBridge));
512
607
 
513
608
  // Title and body are content-only — `srcDoc` already isolates them, but we
514
609
  // still want to escape the few characters that would terminate the parent