@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,185 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import { MemoryRouter, useLocation } from 'react-router-dom';
4
+ import { getFileRenderer } from '..';
5
+ import { GitContext, type GitContextValue } from '../../../../git';
6
+ import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
7
+ import { PageLinkHomeContext } from '../htmlToolBridge';
8
+
9
+ /**
10
+ * A link written in an HTML page, as the app follows it: the frame's nav
11
+ * bridge posts `bevel.navigate`, and the page's file opens in a NEW TAB at its
12
+ * plain address while this tab — its address, its full-screen view — stays.
13
+ */
14
+
15
+ const HtmlRenderer = getFileRenderer('Dashboards/Roadmap.html');
16
+ const PATH = 'knowledge-base/Dashboards/Roadmap.html';
17
+ const AT = '/workspace/main/knowledge-base/Dashboards/Roadmap.html';
18
+
19
+ const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
20
+ const git = { status: { branch: 'main' } } as unknown as GitContextValue;
21
+
22
+ function LocationProbe() {
23
+ const location = useLocation();
24
+ return <output data-testid="location">{location.pathname + location.search + location.hash}</output>;
25
+ }
26
+
27
+ function onFilePage(at: string) {
28
+ return render(
29
+ <MemoryRouter initialEntries={[at]}>
30
+ <WorkspaceContext.Provider value={workspace}>
31
+ <GitContext.Provider value={git}>
32
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly />
33
+ <LocationProbe />
34
+ </GitContext.Provider>
35
+ </WorkspaceContext.Provider>
36
+ </MemoryRouter>,
37
+ );
38
+ }
39
+
40
+ function frameOf(container: HTMLElement) {
41
+ return waitFor(() => {
42
+ const el = container.querySelector('iframe');
43
+ if (!el) throw new Error('no frame yet');
44
+ return el;
45
+ });
46
+ }
47
+
48
+ /** Post a link click from the frame, as its nav bridge does; `newTab` for a modified or middle click. */
49
+ async function clickInFrame(container: HTMLElement, href: string, newTab = false) {
50
+ const iframe = await frameOf(container);
51
+ window.dispatchEvent(
52
+ new MessageEvent('message', {
53
+ data: newTab ? { type: 'bevel.navigate', href, newTab } : { type: 'bevel.navigate', href },
54
+ source: iframe.contentWindow,
55
+ }),
56
+ );
57
+ }
58
+
59
+ function stubWindowOpen() {
60
+ return vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
61
+ }
62
+
63
+ afterEach(() => {
64
+ cleanup();
65
+ vi.restoreAllMocks();
66
+ });
67
+
68
+ describe('a link inside an HTML page', () => {
69
+ it('opens the linked file in a new tab and leaves this tab where it is', async () => {
70
+ const open = stubWindowOpen();
71
+ const { container } = onFilePage(AT);
72
+ await clickInFrame(container, '../Knowledge/Plan.md');
73
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Knowledge/Plan.md', '_blank');
74
+ expect(screen.getByTestId('location').textContent).toBe(AT);
75
+ });
76
+
77
+ it('in full screen, opens the plain address and the page stays full screen', async () => {
78
+ const open = stubWindowOpen();
79
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
80
+ await clickInFrame(container, 'Board.html#totals');
81
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Dashboards/Board.html#totals', '_blank');
82
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
83
+ });
84
+
85
+ it('scrolls a link to a section of the page itself inside the frame, and this tab stays put', async () => {
86
+ const open = stubWindowOpen();
87
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
88
+ const frame = await frameOf(container);
89
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
90
+ await clickInFrame(container, 'Roadmap.html#q3');
91
+ await clickInFrame(container, '/workspace/main/knowledge-base/Dashboards/Roadmap.html#q4');
92
+ expect(open).not.toHaveBeenCalled();
93
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q3' }, '*');
94
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q4' }, '*');
95
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
96
+ });
97
+
98
+ // Where a section link's new tab lands: `Board.html#totals`. The fragment
99
+ // is on the app's address, which the frame never sees, so the page is
100
+ // handed it once it has loaded, as a click on a section link inside it is.
101
+ it('scrolls the page to the section its address names once the frame has loaded', async () => {
102
+ const { container } = onFilePage(`${AT}#q3`);
103
+ const frame = await frameOf(container);
104
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
105
+ fireEvent.load(frame);
106
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q3' }, '*');
107
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}#q3`);
108
+ });
109
+
110
+ it('in full screen, scrolls the page to the section its address names too', async () => {
111
+ const { container } = onFilePage(`${AT}?fullscreen=1#totals`);
112
+ const frame = await frameOf(container);
113
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
114
+ fireEvent.load(frame);
115
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#totals' }, '*');
116
+ });
117
+
118
+ it('hands the frame no jump when its address names no section', async () => {
119
+ const { container } = onFilePage(AT);
120
+ const frame = await frameOf(container);
121
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
122
+ fireEvent.load(frame);
123
+ expect(post).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'bevel.jump' }), '*');
124
+ });
125
+
126
+ it('resolves against the page home its host names (a skill page), on that branch', async () => {
127
+ const open = stubWindowOpen();
128
+ const { container } = render(
129
+ <MemoryRouter initialEntries={['/library/skills/report']}>
130
+ <WorkspaceContext.Provider value={workspace}>
131
+ <GitContext.Provider value={{ status: { branch: 'draft' } } as unknown as GitContextValue}>
132
+ <PageLinkHomeContext.Provider value={{ path: 'knowledge-base/Skills/report/view.html', branch: 'main' }}>
133
+ <HtmlRenderer content="<h1>View</h1>" filePath="view.html" onSave={async () => undefined} readOnly />
134
+ </PageLinkHomeContext.Provider>
135
+ <LocationProbe />
136
+ </GitContext.Provider>
137
+ </WorkspaceContext.Provider>
138
+ </MemoryRouter>,
139
+ );
140
+ const frame = await frameOf(container);
141
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
142
+ await clickInFrame(container, 'template.md');
143
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Skills/report/template.md', '_blank');
144
+ await clickInFrame(container, 'view.html#steps');
145
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#steps' }, '*');
146
+ expect(open).toHaveBeenCalledTimes(1);
147
+ expect(screen.getByTestId('location').textContent).toBe('/library/skills/report');
148
+ });
149
+
150
+ // A modified or middle click in the page, relayed by the bridge: the
151
+ // browser would open the link in a new tab, so the app does, a section of
152
+ // this page included (where it would otherwise scroll in place), at the
153
+ // plain address; this tab and its full-screen view stay.
154
+ it('opens a modified click in a new tab at the plain address, a section of this page too', async () => {
155
+ const open = stubWindowOpen();
156
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
157
+ const frame = await frameOf(container);
158
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
159
+ await clickInFrame(container, 'Board.html', true);
160
+ await clickInFrame(container, '#q3', true);
161
+ await clickInFrame(container, 'Roadmap.html#q4', true);
162
+ expect(open.mock.calls).toEqual([
163
+ ['/workspace/main/knowledge-base/Dashboards/Board.html', '_blank'],
164
+ [`${AT}#q3`, '_blank'],
165
+ [`${AT}#q4`, '_blank'],
166
+ ]);
167
+ expect(post).not.toHaveBeenCalled();
168
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
169
+ });
170
+
171
+ it('opens a modified click on an external link in a new tab, as a plain one', async () => {
172
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
173
+ const { container } = onFilePage(AT);
174
+ await clickInFrame(container, 'https://example.com/docs', true);
175
+ expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
176
+ });
177
+
178
+ it('opens an external link as before, with no referrer', async () => {
179
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
180
+ const { container } = onFilePage(AT);
181
+ await clickInFrame(container, 'https://example.com/docs');
182
+ expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
183
+ expect(screen.getByTestId('location').textContent).toBe(AT);
184
+ });
185
+ });
@@ -1,14 +1,15 @@
1
1
  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
- import { RendererSurfaceContext, getFileRenderer, type RendererSurface } from '..';
5
- import { OpenPageInPlatformContext, PageToolsContext } from '../htmlToolBridge';
4
+ import { OpenPageInPlatformContext, PageToolsContext, RendererSurfaceContext, getFileRenderer, type RendererSurface } from '..';
6
5
  import { GitContext, type GitContextValue } from '../../../../git';
6
+ import { clearToken, setToken } from '../../../../../lib/api';
7
7
  import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
8
+ import { frameChannel, stubServer } from './pageToolsHarness';
8
9
 
9
10
  /**
10
- * `window.bevel.tools` as the app gives it: present on the file page, `null`
11
- * everywhere else, and the two cards — consent to write, and the way to the
11
+ * `window.bevel.tools` as the app gives it: present where a host provides the
12
+ * bridge (the file page, the skill page), `null` everywhere else, and the two cards — consent to write, and the way to the
12
13
  * platform — drawn by the app around the frame, driven here by the very
13
14
  * messages the frame's runtime posts.
14
15
  */
@@ -20,22 +21,28 @@ const PAGE = 'Dashboards/Roadmap.html';
20
21
  const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
21
22
  const git = { status: { branch: 'main' } } as unknown as GitContextValue;
22
23
 
23
- /** The page on the app's file page: in the app, with the file page's provider. */
24
+ /**
25
+ * The page on the app's file page: in the app, with the file page's provider.
26
+ * `receive` is the file's content changing under the open page (a teammate's
27
+ * save arriving): the same frame, a new document in it.
28
+ */
24
29
  function onFilePage({ readOnly = true }: { readOnly?: boolean } = {}) {
25
- return render(
30
+ const tree = (content: string) => (
26
31
  <MemoryRouter initialEntries={['/workspace/main/knowledge-base/Dashboards/Roadmap.html']}>
27
32
  <WorkspaceContext.Provider value={workspace}>
28
33
  <GitContext.Provider value={git}>
29
34
  <PageToolsContext.Provider value={{ pagePath: PAGE }}>
30
- <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly={readOnly} />
35
+ <HtmlRenderer content={content} filePath={PATH} onSave={async () => undefined} readOnly={readOnly} />
31
36
  </PageToolsContext.Provider>
32
37
  </GitContext.Provider>
33
38
  </WorkspaceContext.Provider>
34
- </MemoryRouter>,
39
+ </MemoryRouter>
35
40
  );
41
+ const result = render(tree('<h1>Roadmap</h1>'));
42
+ return { ...result, receive: (content: string) => result.rerender(tree(content)) };
36
43
  }
37
44
 
38
- /** The page in the app but not on the file page — a skill page, a history preview. */
45
+ /** The page in the app on a host without the bridge — a history or change-request preview. */
39
46
  function inAppElsewhere() {
40
47
  return render(
41
48
  <MemoryRouter initialEntries={['/workspace/main']}>
@@ -80,37 +87,6 @@ async function frameOf(container: HTMLElement): Promise<HTMLIFrameElement> {
80
87
  });
81
88
  }
82
89
 
83
- /** Post `data` as the frame would, and collect what the app posts back to it. */
84
- function frameChannel(iframe: HTMLIFrameElement) {
85
- const win = iframe.contentWindow!;
86
- const replies: Array<Record<string, unknown>> = [];
87
- vi.spyOn(win, 'postMessage').mockImplementation(((msg: Record<string, unknown>) => void replies.push(msg)) as never);
88
- return {
89
- replies,
90
- post: (data: unknown) => window.dispatchEvent(new MessageEvent('message', { data, source: win })),
91
- };
92
- }
93
-
94
- /** The hosted server and the manual, as the app's fetch sees them. */
95
- function stubServer() {
96
- const mcp: string[] = [];
97
- vi.stubGlobal(
98
- 'fetch',
99
- vi.fn(async (url: string, init?: RequestInit) => {
100
- if (url === '/api/agent/utcp') return Response.json({ tools: [{ name: 'read_file', tags: [] }, { name: 'edit_file', tags: ['write'] }] });
101
- if (url === '/api/mcp/page-refusals') return new Response(null, { status: 204 });
102
- const body = JSON.parse(String(init!.body)) as { id: number; params: { name: string } };
103
- mcp.push(body.params.name);
104
- return Response.json({
105
- jsonrpc: '2.0',
106
- id: body.id,
107
- result: { content: [{ type: 'text', text: JSON.stringify({ ran: body.params.name }) }] },
108
- });
109
- }),
110
- );
111
- return { mcp };
112
- }
113
-
114
90
  afterEach(() => {
115
91
  cleanup();
116
92
  vi.restoreAllMocks();
@@ -118,11 +94,11 @@ afterEach(() => {
118
94
  });
119
95
 
120
96
  describe('window.bevel.tools on the file page and elsewhere', () => {
121
- it('gives the page the four functions on the file page', async () => {
97
+ it('gives the page the five functions on the file page', async () => {
122
98
  const { container } = onFilePage();
123
99
  const srcdoc = (await frameOf(container)).getAttribute('srcdoc')!;
124
100
  expect(srcdoc).toContain('globalThis.bevel.tools = Object.freeze({');
125
- for (const fn of ['searchTools', 'toolsInfo', 'callTool', 'callToolChain']) expect(srcdoc).toContain(`${fn}: function`);
101
+ for (const fn of ['searchTools', 'toolsInfo', 'callTool', 'callToolChain', 'uploadFile']) expect(srcdoc).toContain(`${fn}: function`);
126
102
  });
127
103
 
128
104
  it('gives it null on the embed and on any other preview in the app', async () => {
@@ -212,6 +188,86 @@ describe('the consent card on the file page', () => {
212
188
  });
213
189
  });
214
190
 
191
+ describe('an upload from the file page', () => {
192
+ const TOKEN = 'bevel-up_s3cret';
193
+
194
+ /** The hosted server and the upload endpoint, as the app's fetch sees them: every request, with its headers. */
195
+ function stubUploadServer() {
196
+ const requests: Array<{ step: string; headers: Headers; body: unknown }> = [];
197
+ vi.stubGlobal(
198
+ 'fetch',
199
+ vi.fn(async (url: string, init?: RequestInit) => {
200
+ const headers = new Headers(init?.headers);
201
+ if (url === '/api/agent/utcp') return Response.json({ tools: [] });
202
+ if (url === '/api/mcp/page-refusals') {
203
+ requests.push({ step: 'refusal', headers, body: JSON.parse(String(init!.body)) });
204
+ return new Response(null, { status: 204 });
205
+ }
206
+ if (url.startsWith('/api/agent/uploads')) {
207
+ requests.push({ step: `${init?.method} ${url}`, headers, body: init?.body });
208
+ return Response.json({ filename: 'Assets.xlsx', bytes: 4, kind: 'file' });
209
+ }
210
+ const rpc = JSON.parse(String(init!.body)) as { id: number; params: { name: string; arguments: { body: Record<string, unknown> } } };
211
+ requests.push({ step: rpc.params.name, headers, body: rpc.params.arguments });
212
+ const answer =
213
+ rpc.params.name === 'request_file_upload'
214
+ ? { uploadUrl: `https://kb.example.com/api/agent/uploads/${TOKEN}`, token: TOKEN, maxBytes: 1024 }
215
+ : { destination: 'Data/Campaigns/Easter', count: 1, total: 1, files: [{ path: 'knowledge-base/Data/Campaigns/Easter/Assets.xlsx', outcome: 'created' }] };
216
+ return Response.json({ jsonrpc: '2.0', id: rpc.id, result: { content: [{ type: 'text', text: JSON.stringify(answer) }] } });
217
+ }),
218
+ );
219
+ return { requests };
220
+ }
221
+
222
+ const file = () => new File([new Uint8Array([0x50, 0x4b, 0x03, 0x04])], 'Assets.xlsx');
223
+
224
+ 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');
226
+ try {
227
+ const server = stubUploadServer();
228
+ const { container } = onFilePage();
229
+ const frame = frameChannel(await frameOf(container));
230
+ 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();
232
+ expect(server.requests).toEqual([]);
233
+
234
+ fireEvent.click(screen.getByRole('button', { name: 'Allow while open' }));
235
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'u1', ok: true, result: { count: 1, destination: 'Data/Campaigns/Easter' } }));
236
+ expect(server.requests.map((r) => r.step)).toEqual([
237
+ 'request_file_upload',
238
+ 'POST /api/agent/uploads?filename=Assets.xlsx',
239
+ 'apply_file_upload',
240
+ ]);
241
+ for (const r of server.requests) expect(r.headers.get('Authorization')).toBe('Bearer viewer-session');
242
+ for (const r of server.requests.filter((x) => x.step.endsWith('_upload'))) {
243
+ expect(decodeURIComponent(r.headers.get('X-Bevel-Page')!)).toBe(PAGE);
244
+ }
245
+ expect(server.requests[1]!.headers.get('x-upload-token')).toBe(TOKEN);
246
+ // The token went to the server and nowhere else: not into an address, not back to the frame.
247
+ expect(server.requests[1]!.step).not.toContain(TOKEN);
248
+ expect(JSON.stringify(frame.replies)).not.toContain(TOKEN);
249
+
250
+ // Allow holds for the view: the next upload runs with no card.
251
+ frame.post({ type: 'bevel.tool.call', requestId: 'u2', fn: 'uploadFile', args: [file(), { branch: 'main', destination: 'Data' }] });
252
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'u2', ok: true }));
253
+ expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
254
+ } finally {
255
+ clearToken();
256
+ }
257
+ });
258
+
259
+ it('Deny answers denied, uploads nothing, and reports a refused apply_file_upload under the page', async () => {
260
+ const server = stubUploadServer();
261
+ const { container } = onFilePage();
262
+ const frame = frameChannel(await frameOf(container));
263
+ 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' }));
265
+ await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'u1', ok: false, error: 'denied', code: 'denied' }));
266
+ await waitFor(() => expect(server.requests.map((r) => r.step)).toEqual(['refusal']));
267
+ expect(server.requests[0]!.body).toMatchObject({ page: PAGE, tool: 'apply_file_upload' });
268
+ });
269
+ });
270
+
215
271
  describe('the platform card where there are no tools', () => {
216
272
  it('on the embed offers Continue without tools (false) and Open in the platform (opens the page, false)', async () => {
217
273
  const openFilePage = vi.fn();
@@ -270,3 +326,73 @@ describe('the platform card where there are no tools', () => {
270
326
  expect(screen.queryByText(/only available in the platform/)).toBeNull();
271
327
  });
272
328
  });
329
+
330
+ describe('a call whose view ended before it was decided', () => {
331
+ // An ended view's calls are decided `closed` and their replies are never
332
+ // posted: the controller fences replies by view generation, which its own
333
+ // suite pins with a frame that keeps its window across a view change. A
334
+ // rebuilt document is a new frame window here, so this renderer shows the
335
+ // rest: no card in the new view, nothing run, and neither window hearing
336
+ // an answer meant for a view that is gone.
337
+ const settled = () => new Promise((r) => setTimeout(r, 50));
338
+
339
+ it('shows no card and runs nothing when the document changes under it while the lookup is in flight', async () => {
340
+ const server = stubServer({ holdManual: true });
341
+ const page = onFilePage();
342
+ const iframe = await frameOf(page.container);
343
+ const frame = frameChannel(iframe);
344
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
345
+
346
+ // The lookup of whether edit_file writes is still in flight when the page's document is replaced.
347
+ page.receive('<h1>Roadmap, v2</h1>');
348
+ await waitFor(() => expect(iframe.getAttribute('srcdoc')).toContain('Roadmap, v2'));
349
+ const changed = frameChannel(iframe);
350
+ server.releaseManual();
351
+ await settled();
352
+
353
+ expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
354
+ expect(server.mcp).toEqual([]);
355
+ expect(changed.replies).toEqual([]);
356
+ });
357
+
358
+ it('does not run on an Allow the ended view gave', async () => {
359
+ const server = stubServer({ holdManual: true });
360
+ const page = onFilePage();
361
+ const iframe = await frameOf(page.container);
362
+ const frame = frameChannel(iframe);
363
+ // A chain asks without the manual: Allow it, so the view holds an Allow.
364
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callToolChain', args: ['return 1'] });
365
+ fireEvent.click(await screen.findByRole('button', { name: 'Allow while open' }));
366
+ await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
367
+
368
+ frame.post({ type: 'bevel.tool.call', requestId: 'w2', fn: 'callTool', args: ['edit_file', {}] });
369
+ page.receive('<h1>Roadmap, v2</h1>');
370
+ await waitFor(() => expect(iframe.getAttribute('srcdoc')).toContain('Roadmap, v2'));
371
+ server.releaseManual();
372
+ await settled();
373
+
374
+ expect(server.mcp).toEqual(['call_tool_chain']);
375
+ });
376
+
377
+ it('opens no card in the reloaded view and sends the server nothing when the viewer reloads first', async () => {
378
+ const server = stubServer({ holdManual: true });
379
+ const { container } = onFilePage();
380
+ const frame = frameChannel(await frameOf(container));
381
+ frame.post({ type: 'bevel.tool.call', requestId: 'w1', fn: 'callTool', args: ['edit_file', {}] });
382
+
383
+ fireEvent.click(screen.getByTitle('Reload preview'));
384
+ const reloaded = frameChannel(await waitFor(() => {
385
+ const el = container.querySelector('iframe')!;
386
+ if (el.contentWindow === null) throw new Error('not yet');
387
+ return el;
388
+ }));
389
+ server.releaseManual();
390
+ await settled();
391
+
392
+ expect(screen.queryByText(/wants to write to the knowledge base/)).toBeNull();
393
+ expect(server.mcp).toEqual([]);
394
+ // Neither document hears an answer meant for a view that is gone.
395
+ expect(frame.replies).toEqual([]);
396
+ expect(reloaded.replies).toEqual([]);
397
+ });
398
+ });
@@ -0,0 +1,88 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { MemoryRouter, useLocation } from 'react-router-dom';
5
+ import { WorkspaceContext } from '../../../state/workspace.context';
6
+ import { makeWorkspaceFixture } from '../../../__tests__/testFixtures';
7
+ import { GitContext, type GitContextValue } from '../../../../git/state/git.context';
8
+ import { MarkdownRenderer } from '../MarkdownRenderer';
9
+
10
+ /**
11
+ * A section link to the file on screen, clicked TWICE. `MarkdownRenderer.test`
12
+ * stubs the router's `navigate` to assert where a link goes; this file keeps
13
+ * the real one, because the second click is the point: it navigates to the
14
+ * address the tab is already at, so the hash string does not change — only
15
+ * the router's `location.key` — and the heading must scroll into view again
16
+ * all the same, as it would for a reader who scrolled away and clicked the
17
+ * link a second time.
18
+ */
19
+
20
+ function LocationProbe() {
21
+ const location = useLocation();
22
+ return <output data-testid="location">{location.pathname + location.search + location.hash}</output>;
23
+ }
24
+
25
+ const git: GitContextValue = {
26
+ status: { branch: 'alice/draft', hasUpstream: true, unmergedFromUpstream: false },
27
+ branches: [],
28
+ availability: 'ready',
29
+ lastError: null,
30
+ refreshStatus: async () => null,
31
+ refreshBranches: async () => {},
32
+ createBranch: async () => {},
33
+ deleteBranch: async () => {},
34
+ pull: async () => {},
35
+ fetchForkBase: async () => null,
36
+ fetchFileHistory: async () => [],
37
+ fetchFileDiff: async () => '',
38
+ fetchFileAtChange: async () => ({ baseline: null, current: null }),
39
+ fetchFileComparison: async () => '',
40
+ };
41
+
42
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
43
+ afterEach(() => {
44
+ Element.prototype.scrollIntoView = originalScrollIntoView;
45
+ });
46
+
47
+ describe('MarkdownRenderer — a section link clicked again', () => {
48
+ it('scrolls the heading into view on every click, not only when the hash changes', async () => {
49
+ const scrolled: string[] = [];
50
+ Element.prototype.scrollIntoView = function (this: Element) {
51
+ scrolled.push(this.id);
52
+ };
53
+ const content = '# Intro\n\n[Goal](Foo.md#goal)\n\n## Goal\n\nText';
54
+ const tab = { path: 'Knowledge/Foo.md', content, savedContent: content, isDirty: false, pendingFileContent: null };
55
+ render(
56
+ <MemoryRouter initialEntries={['/workspace/alice%2Fdraft/Knowledge/Foo.md']}>
57
+ <WorkspaceContext.Provider
58
+ value={makeWorkspaceFixture({
59
+ openTabs: [tab],
60
+ activeTab: tab,
61
+ openFilePath: 'Knowledge/Foo.md',
62
+ openFileContent: content,
63
+ openFileSavedContent: content,
64
+ })}
65
+ >
66
+ <GitContext.Provider value={git}>
67
+ <MarkdownRenderer content={content} filePath="Knowledge/Foo.md" onSave={async () => {}} readOnly />
68
+ <LocationProbe />
69
+ </GitContext.Provider>
70
+ </WorkspaceContext.Provider>
71
+ </MemoryRouter>,
72
+ );
73
+ const user = userEvent.setup();
74
+ const link = screen.getByRole('link', { name: 'Goal' });
75
+ expect(link).toHaveAttribute('href', '/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
76
+
77
+ await user.click(link);
78
+ await waitFor(() => expect(scrolled).toEqual(['goal']));
79
+ expect(screen.getByTestId('location').textContent).toBe('/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
80
+
81
+ // The reader scrolled away and clicks the same link: same address, same
82
+ // hash, and the heading comes back into view. (Queried again: the
83
+ // navigation re-rendered the page's anchors.)
84
+ await user.click(screen.getByRole('link', { name: 'Goal' }));
85
+ await waitFor(() => expect(scrolled).toEqual(['goal', 'goal']));
86
+ expect(screen.getByTestId('location').textContent).toBe('/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
87
+ });
88
+ });