@bevel-software/platform-core-frontend 0.26.0 → 0.28.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 (206) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +87 -25
  3. package/src/core/ProductName.tsx +49 -0
  4. package/src/core/__tests__/ProductName.test.tsx +46 -0
  5. package/src/core/__tests__/ShellRoutes.test.tsx +22 -0
  6. package/src/core/__tests__/core-contributions.test.ts +16 -0
  7. package/src/core/core-contributions.ts +17 -0
  8. package/src/core/maker-url.ts +30 -0
  9. package/src/core/registry.ts +78 -1
  10. package/src/index.css +23 -5
  11. package/src/index.ts +5 -0
  12. package/src/lib/__tests__/latest-request.test.ts +48 -0
  13. package/src/lib/latest-request.ts +45 -0
  14. package/src/modules/access/__tests__/ManageAccessDialog.no-sso-invite.test.tsx +222 -0
  15. package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +1 -1
  16. package/src/modules/access/api.ts +19 -3
  17. package/src/modules/access/components/ManageAccessDialog.tsx +61 -8
  18. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +16 -1
  19. package/src/modules/admin/__tests__/RolesCorruptedBanner.test.tsx +70 -0
  20. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +284 -39
  21. package/src/modules/admin/components/AdminRolesPage.tsx +13 -14
  22. package/src/modules/admin/components/RolesCorruptedBanner.tsx +9 -4
  23. package/src/modules/admin/components/UserAccountsPage.tsx +91 -107
  24. package/src/modules/admin/services/roles.api.ts +14 -1
  25. package/src/modules/auth/__tests__/LoginScreen.test.tsx +80 -5
  26. package/src/modules/auth/__tests__/sso-strict-probe.test.ts +66 -0
  27. package/src/modules/auth/components/LoginScreen.tsx +101 -73
  28. package/src/modules/auth/services/account.api.ts +59 -3
  29. package/src/modules/auth/services/sso.ts +30 -10
  30. package/src/modules/auth/state/use-sign-in-methods.ts +41 -0
  31. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +176 -0
  32. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +68 -0
  33. package/src/modules/change-requests/__tests__/ChangeRequestLink.test.tsx +182 -0
  34. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +1 -1
  35. package/src/modules/change-requests/__tests__/readFileOnBranch.test.ts +79 -0
  36. package/src/modules/change-requests/components/ChangeBox.tsx +6 -1
  37. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +45 -15
  38. package/src/modules/change-requests/components/ChangeRequestLink.tsx +151 -0
  39. package/src/modules/change-requests/components/CrFileTree.tsx +2 -1
  40. package/src/modules/change-requests/components/FileChangeBoxes.tsx +4 -2
  41. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +6 -3
  42. package/src/modules/change-requests/services/change-requests.api.ts +15 -2
  43. package/src/modules/change-requests/utils/readFailure.ts +22 -0
  44. package/src/modules/embed/__tests__/EmbedLinkPage.test.tsx +74 -0
  45. package/src/modules/embed/__tests__/EmbedView.test.tsx +473 -0
  46. package/src/modules/embed/__tests__/embed-config.test.ts +128 -0
  47. package/src/modules/embed/__tests__/embed-host.test.ts +111 -0
  48. package/src/modules/embed/__tests__/mcp-app-view.test.ts +295 -0
  49. package/src/modules/embed/__tests__/mount.test.tsx +157 -0
  50. package/src/modules/embed/components/EmbedLinkPage.tsx +109 -0
  51. package/src/modules/embed/components/EmbedView.tsx +545 -0
  52. package/src/modules/embed/embed-config.ts +132 -0
  53. package/src/modules/embed/embed-host.ts +120 -0
  54. package/src/modules/embed/mount.tsx +80 -0
  55. package/src/modules/embed/services/embed-token.ts +22 -0
  56. package/src/modules/embed/services/embed.api.ts +158 -0
  57. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +202 -4
  58. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +59 -1
  59. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +39 -22
  60. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +7 -2
  61. package/src/modules/git/branch-delete-menu-item.tsx +24 -0
  62. package/src/modules/git/components/BranchSwitcher.tsx +29 -5
  63. package/src/modules/git/components/GitSyncFailedBanner.tsx +53 -15
  64. package/src/modules/git/components/HistoryVersionPreview.tsx +5 -3
  65. package/src/modules/git/components/PullNeededBanner.tsx +15 -49
  66. package/src/modules/git/hooks/useAutoPullUpdates.ts +9 -5
  67. package/src/modules/git/index.ts +15 -0
  68. package/src/modules/git/services/__tests__/error-messages.test.ts +67 -0
  69. package/src/modules/git/services/__tests__/pull-failure.test.ts +36 -0
  70. package/src/modules/git/services/error-messages.ts +58 -1
  71. package/src/modules/git/services/pull-failure.ts +68 -0
  72. package/src/modules/git/state/branch-delete-confirm.ts +46 -0
  73. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +1 -0
  74. package/src/modules/layout/__tests__/breakpoints.test.ts +7 -1
  75. package/src/modules/layout/breakpoints.ts +8 -0
  76. package/src/modules/library/__tests__/PluginExtras.test.tsx +9 -9
  77. package/src/modules/library/__tests__/PluginPage.test.tsx +8 -1
  78. package/src/modules/library/__tests__/SkillsTree.test.tsx +13 -4
  79. package/src/modules/library/components/LibraryPage.tsx +22 -0
  80. package/src/modules/library/components/PluginExtras.tsx +23 -6
  81. package/src/modules/library/components/PluginPage.tsx +6 -1
  82. package/src/modules/library/routes/LibraryRoutes.tsx +8 -7
  83. package/src/modules/library/services/plugins.api.ts +4 -1
  84. package/src/modules/library/state/plugins-revision.ts +28 -0
  85. package/src/modules/onboarding/__tests__/InviteButton.test.tsx +214 -0
  86. package/src/modules/onboarding/__tests__/agent-connection-api.test.ts +55 -0
  87. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +87 -82
  88. package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +164 -0
  89. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +1458 -0
  90. package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +811 -0
  91. package/src/modules/onboarding/__tests__/invite-emails.test.ts +247 -0
  92. package/src/modules/onboarding/__tests__/onboarding.test.tsx +226 -193
  93. package/src/modules/onboarding/__tests__/starter-pack-card.test.tsx +136 -0
  94. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +7 -11
  95. package/src/modules/onboarding/components/EmailChipsInput.tsx +138 -0
  96. package/src/modules/onboarding/components/GetStartedColumn.tsx +670 -0
  97. package/src/modules/onboarding/components/InviteButton.tsx +139 -0
  98. package/src/modules/onboarding/components/InviteDialog.tsx +741 -0
  99. package/src/modules/onboarding/components/RootLanding.tsx +8 -24
  100. package/src/modules/onboarding/components/StarterPackCard.tsx +98 -0
  101. package/src/modules/onboarding/components/WelcomePage.tsx +65 -154
  102. package/src/modules/onboarding/first-page-prompt.ts +123 -0
  103. package/src/modules/onboarding/invite-emails.ts +313 -0
  104. package/src/modules/onboarding/services/agent-connection.api.ts +53 -0
  105. package/src/modules/onboarding/services/starter-packs.api.ts +83 -0
  106. package/src/modules/onboarding/state/agent-connection.ts +167 -0
  107. package/src/modules/onboarding/state/invite-dialog.context.ts +35 -0
  108. package/src/modules/onboarding/state/invite-dialog.tsx +39 -0
  109. package/src/modules/onboarding/state/onboarding.ts +133 -59
  110. package/src/modules/onboarding/state/starter-packs.ts +169 -0
  111. package/src/modules/settings/settings-nav-items.tsx +8 -3
  112. package/src/modules/setup/__tests__/setup.first-run-storage.test.tsx +389 -0
  113. package/src/modules/setup/__tests__/setup.github.test.tsx +5 -5
  114. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +1 -1
  115. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +1 -1
  116. package/src/modules/setup/__tests__/setup.repository.test.tsx +21 -21
  117. package/src/modules/setup/__tests__/setup.test.tsx +56 -15
  118. package/src/modules/setup/__tests__/useConnectionProbe.test.tsx +123 -0
  119. package/src/modules/setup/components/FirstRunStorage.tsx +560 -0
  120. package/src/modules/setup/components/SetupGate.tsx +46 -1
  121. package/src/modules/setup/components/SetupScreen.tsx +81 -84
  122. package/src/modules/setup/hooks/useConnectionProbe.ts +93 -0
  123. package/src/modules/setup/services/setup.api.ts +3 -3
  124. package/src/modules/setup/utils/suggested-branch.ts +27 -0
  125. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +210 -0
  126. package/src/modules/toolbar/commands/actions.tsx +330 -0
  127. package/src/modules/toolbar/commands/command-menu.ts +44 -0
  128. package/src/modules/toolbar/commands/useCommandActions.ts +71 -0
  129. package/src/modules/toolbar/commands/useCommandShortcuts.ts +121 -0
  130. package/src/modules/toolbar/components/AppSwitcher.tsx +125 -22
  131. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +1 -1
  132. package/src/modules/toolbar/components/ProfileMenu.tsx +9 -4
  133. package/src/modules/toolbar/components/SearchPalette.tsx +540 -0
  134. package/src/modules/toolbar/components/Toolbar.tsx +10 -0
  135. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +230 -52
  136. package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +64 -0
  137. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +864 -0
  138. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +57 -2
  139. package/src/modules/toolbar/search/__tests__/rank.test.ts +93 -0
  140. package/src/modules/toolbar/search/__tests__/sources.test.ts +131 -0
  141. package/src/modules/toolbar/search/rank.ts +111 -0
  142. package/src/modules/toolbar/search/sources.ts +169 -0
  143. package/src/modules/workflow/hooks/useFileLock.ts +10 -7
  144. package/src/modules/workflow/services/__tests__/lock.api.test.ts +41 -0
  145. package/src/modules/workflow/services/lock.api.ts +17 -2
  146. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +49 -1
  147. package/src/modules/workspace/components/EditorTabs.tsx +39 -15
  148. package/src/modules/workspace/components/FileExplorer.tsx +39 -6
  149. package/src/modules/workspace/components/FilePaneCard.tsx +6 -2
  150. package/src/modules/workspace/components/FileRoute.tsx +12 -7
  151. package/src/modules/workspace/components/FileViewer.tsx +271 -74
  152. package/src/modules/workspace/components/KbPageHeader.tsx +13 -6
  153. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +88 -21
  154. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +92 -4
  155. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +23 -3
  156. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +330 -6
  157. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +17 -2
  158. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -16
  159. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +6 -0
  160. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +23 -21
  161. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +13 -29
  162. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +9 -2
  163. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +8 -0
  164. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +14 -19
  165. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +11 -17
  166. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +35 -7
  167. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -17
  168. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.links.test.tsx +73 -0
  169. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.scaffold.test.tsx +64 -0
  170. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +82 -0
  171. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +99 -0
  172. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +129 -35
  173. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +149 -0
  174. package/src/modules/workspace/components/renderers/__tests__/kbMarkdownLinkPolicy.test.tsx +100 -0
  175. package/src/modules/workspace/components/renderers/htmlSandbox.ts +76 -20
  176. package/src/modules/workspace/components/renderers/index.ts +26 -0
  177. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +51 -1
  178. package/src/modules/workspace/components/renderers/rendererRawRead.ts +53 -0
  179. package/src/modules/workspace/components/renderers/rendererSurface.ts +109 -0
  180. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +8 -2
  181. package/src/modules/workspace/hooks/__tests__/useCreatePage.test.ts +137 -0
  182. package/src/modules/workspace/hooks/__tests__/useKnowledgeWriteTarget.test.ts +302 -0
  183. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +126 -21
  184. package/src/modules/workspace/hooks/useCreatePage.ts +206 -0
  185. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +238 -0
  186. package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +24 -7
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +42 -8
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +10 -0
  189. package/src/modules/workspace/routing/__tests__/md-links-parity.test.tsx +113 -0
  190. package/src/modules/workspace/routing/kb-routes.ts +66 -12
  191. package/src/modules/workspace/state/editable-page.ts +42 -0
  192. package/src/modules/workspace/state/workspace.context.ts +13 -4
  193. package/src/modules/workspace/utils/__tests__/display-file-name.test.ts +60 -0
  194. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +75 -0
  195. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +16 -0
  196. package/src/modules/workspace/utils/display-file-name.ts +102 -0
  197. package/src/modules/workspace/utils/fileTree.ts +49 -14
  198. package/src/modules/workspace/utils/treeConfirm.ts +15 -0
  199. package/src/shared/__tests__/no-builtin-confirm.test.ts +102 -0
  200. package/src/shared/components/ConfirmProvider.tsx +156 -0
  201. package/src/shared/components/Dialog.tsx +7 -0
  202. package/src/shared/components/__tests__/ConfirmProvider.test.tsx +198 -0
  203. package/src/shared/components/confirm-context.ts +94 -0
  204. package/src/shared/components/index.ts +3 -0
  205. package/src/modules/onboarding/components/WelcomeRoute.tsx +0 -57
  206. package/src/modules/onboarding/welcome-state.ts +0 -36
@@ -0,0 +1,128 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { configureEmbed, EMBED_HANDOFF_GLOBAL, readEmbedHandoff, resetEmbedConfig } from '../embed-config';
3
+ import { embedRawUrl, loadEmbed, lockEmbed, saveEmbed } from '../services/embed.api';
4
+ import { openThroughHost, resolveToAppUrl } from '../embed-host';
5
+
6
+ /**
7
+ * The embed runs on two surfaces — the SPA's `/embed` page and the MCP App
8
+ * view's sandbox — and `embed-config` is the one place that says which. These
9
+ * tests drive the difference through the modules that read it: the API
10
+ * client, the host bridge, and the handoff the view leaves on the window.
11
+ */
12
+
13
+ const BASE = 'https://hexis.example';
14
+ const KB = { kbDirName: 'knowledge-base', branch: 'main' };
15
+
16
+ afterEach(() => {
17
+ resetEmbedConfig();
18
+ vi.unstubAllGlobals();
19
+ vi.restoreAllMocks();
20
+ delete (window as unknown as Record<string, unknown>)[EMBED_HANDOFF_GLOBAL];
21
+ });
22
+
23
+ describe('unconfigured — the SPA /embed page', () => {
24
+ it('addresses the API relative to the page', () => {
25
+ expect(embedRawUrl('tok', '/Data/a.png')).toBe('/api/embed/raw?token=tok&path=%2FData%2Fa.png');
26
+ });
27
+
28
+ it('builds app addresses on the page own origin', () => {
29
+ expect(resolveToAppUrl('/workspace/main/x', '', null)).toBe(`${window.location.origin}/workspace/main/x`);
30
+ });
31
+ });
32
+
33
+ describe('handed the deployment address — the MCP App view', () => {
34
+ it('addresses the read routes on the deployment, still without cookies', async () => {
35
+ configureEmbed({ baseUrl: BASE, token: 'tok' });
36
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ nodeName: 'Thing' }) }));
37
+ vi.stubGlobal('fetch', fetchMock);
38
+ await loadEmbed('tok');
39
+ expect(fetchMock).toHaveBeenCalledWith(
40
+ `${BASE}/api/embed/load?token=tok`,
41
+ expect.objectContaining({ credentials: 'omit' }),
42
+ );
43
+ expect(embedRawUrl('tok', '/Data/a.png')).toBe(`${BASE}/api/embed/raw?token=tok&path=%2FData%2Fa.png`);
44
+ });
45
+
46
+ it('addresses the write routes on the deployment, still without cookies', async () => {
47
+ configureEmbed({ baseUrl: BASE, token: 'tok' });
48
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 204, json: async () => ({ acquired: true }) }));
49
+ vi.stubGlobal('fetch', fetchMock);
50
+ await lockEmbed('tok');
51
+ await saveEmbed('tok', '# changed');
52
+ expect(fetchMock).toHaveBeenNthCalledWith(
53
+ 1,
54
+ `${BASE}/api/embed/lock`,
55
+ expect.objectContaining({ method: 'POST', credentials: 'omit', body: JSON.stringify({ token: 'tok' }) }),
56
+ );
57
+ expect(fetchMock).toHaveBeenNthCalledWith(
58
+ 2,
59
+ `${BASE}/api/embed/save`,
60
+ expect.objectContaining({
61
+ method: 'POST',
62
+ credentials: 'omit',
63
+ body: JSON.stringify({ token: 'tok', content: '# changed' }),
64
+ }),
65
+ );
66
+ });
67
+
68
+ it('keeps a path prefix the deployment is served under', async () => {
69
+ configureEmbed({ baseUrl: `${BASE}/hexis`, token: 'tok' });
70
+ expect(embedRawUrl('tok')).toBe(`${BASE}/hexis/api/embed/raw?token=tok`);
71
+ expect(resolveToAppUrl('/workspace/main/x', '', null)).toBe(`${BASE}/hexis/workspace/main/x`);
72
+ });
73
+
74
+ it('builds app addresses on the deployment, not on the sandbox document', () => {
75
+ configureEmbed({ baseUrl: BASE, token: 'tok' });
76
+ expect(resolveToAppUrl('/workspace/main/x', '', null)).toBe(`${BASE}/workspace/main/x`);
77
+ expect(resolveToAppUrl('Other.md#goal', 'knowledge-base/Data/Thing.md', KB)).toBe(
78
+ `${BASE}/workspace/main/knowledge-base/Data/Other.md#goal`,
79
+ );
80
+ });
81
+
82
+ it('opens a link through the host, and nowhere else', () => {
83
+ const openLink = vi.fn();
84
+ configureEmbed({ baseUrl: BASE, token: 'tok', openLink });
85
+ const windowOpen = vi.spyOn(window, 'open').mockImplementation(() => null);
86
+ openThroughHost('Other.md', 'knowledge-base/Data/Thing.md', KB);
87
+ expect(openLink).toHaveBeenCalledWith(`${BASE}/workspace/main/knowledge-base/Data/Other.md`);
88
+ expect(windowOpen).not.toHaveBeenCalled();
89
+ });
90
+
91
+ it('refuses to hand the host a destination the link grammar refuses', () => {
92
+ const openLink = vi.fn();
93
+ configureEmbed({ baseUrl: BASE, token: 'tok', openLink });
94
+ openThroughHost('javascript:alert(1)', 'knowledge-base/Data/Thing.md', KB);
95
+ expect(openLink).not.toHaveBeenCalled();
96
+ });
97
+ });
98
+
99
+ describe('the handoff the view leaves on the window', () => {
100
+ const set = (value: unknown) => {
101
+ (window as unknown as Record<string, unknown>)[EMBED_HANDOFF_GLOBAL] = value;
102
+ };
103
+
104
+ it('is absent when the bundle was not loaded by the view', () => {
105
+ expect(readEmbedHandoff()).toBeNull();
106
+ });
107
+
108
+ it('is read with its address kept to origin and path, and the open-link kept', () => {
109
+ const openLink = () => undefined;
110
+ set({ baseUrl: `${BASE}/?x=1#y`, token: 'tok', openLink });
111
+ expect(readEmbedHandoff()).toEqual({ baseUrl: BASE, token: 'tok', openLink });
112
+ });
113
+
114
+ it('keeps the path prefix a deployment is served under', () => {
115
+ set({ baseUrl: `${BASE}/hexis/`, token: 'tok' });
116
+ expect(readEmbedHandoff()).toEqual({ baseUrl: `${BASE}/hexis`, token: 'tok' });
117
+ });
118
+
119
+ it.each([
120
+ ['no token', { baseUrl: BASE, token: '' }],
121
+ ['a non-http address', { baseUrl: 'javascript:alert(1)', token: 'tok' }],
122
+ ['a relative address', { baseUrl: '/api', token: 'tok' }],
123
+ ['not an object', 'https://hexis.example'],
124
+ ])('is refused with %s', (_label, value) => {
125
+ set(value);
126
+ expect(readEmbedHandoff()).toBeNull();
127
+ });
128
+ });
@@ -0,0 +1,111 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { EMBED_EXPIRED, EMBED_OPEN_MESSAGE, resolveToAppUrl } from '../embed-host';
3
+
4
+ const KB = { kbDirName: 'knowledge-base', branch: 'main' };
5
+ const ORIGIN = window.location.origin;
6
+ /**
7
+ * The file a link sits in, WORKSPACE-relative — which is the form the
8
+ * renderers pass (`FileRendererProps.filePath`, and the embed's
9
+ * `view.workspacePath`) and the form `resolveKbHref` resolves against.
10
+ */
11
+ const BASE = 'knowledge-base/Data/Thing.md';
12
+ const DEEP_BASE = 'knowledge-base/Data/Deep/Thing.md';
13
+
14
+ /**
15
+ * Where a link clicked inside the embedded view goes. The embed never
16
+ * navigates itself — it is one page deep by decision, and a token is minted
17
+ * for one file — so every destination becomes an absolute address the HOST
18
+ * opens in a new tab.
19
+ */
20
+ describe('resolveToAppUrl', () => {
21
+ it.each([
22
+ ['a sibling page', 'Other.md', BASE, `${ORIGIN}/workspace/main/knowledge-base/Data/Other.md`],
23
+ ['a page one level up', '../Top.md', DEEP_BASE, `${ORIGIN}/workspace/main/knowledge-base/Data/Top.md`],
24
+ [
25
+ 'a heading in another page',
26
+ 'Other.md#goal',
27
+ BASE,
28
+ `${ORIGIN}/workspace/main/knowledge-base/Data/Other.md#goal`,
29
+ ],
30
+ [
31
+ 'a percent-encoded name',
32
+ 'Some%20Page.md',
33
+ BASE,
34
+ `${ORIGIN}/workspace/main/knowledge-base/Data/Some%20Page.md`,
35
+ ],
36
+ ])('turns %s into the app address', (_label, href, basePath, expected) => {
37
+ expect(resolveToAppUrl(href, basePath, KB)).toBe(expected);
38
+ });
39
+
40
+ it('keeps the branch an absolute app link named, rather than the embed own', () => {
41
+ expect(resolveToAppUrl('/workspace/a-draft/knowledge-base/Data/X.md', BASE, KB)).toBe(
42
+ `${ORIGIN}/workspace/a-draft/knowledge-base/Data/X.md`,
43
+ );
44
+ });
45
+
46
+ /** External links leave the same way — a new tab, through the host. */
47
+ it.each([
48
+ ['an https address', 'https://example.test/docs'],
49
+ ['an http address', 'http://example.test/docs'],
50
+ ['a mailto: address', 'mailto:someone@example.test'],
51
+ ])('passes %s to the host', (_label, href) => {
52
+ expect(resolveToAppUrl(href, BASE, KB)).toBe(href);
53
+ });
54
+
55
+ /**
56
+ * The embed asks its HOST to open whatever it hands over, and a host
57
+ * obliges — so a scheme the app would never call `window.open` on must not
58
+ * reach it either. The pages these links come from may have been written by
59
+ * an agent.
60
+ */
61
+ it.each([
62
+ ['javascript:', 'javascript:alert(1)'],
63
+ ['a data: document', 'data:text/html,<script>alert(1)</script>'],
64
+ ['a vbscript: address', 'vbscript:msgbox(1)'],
65
+ ['javascript: with padding the normaliser strips', ' java\tscript:alert(1)'],
66
+ ])('refuses %s', (_label, href) => {
67
+ expect(resolveToAppUrl(href, BASE, KB)).toBeNull();
68
+ });
69
+
70
+ it('still makes an absolute address out of an app path with no page loaded yet', () => {
71
+ expect(resolveToAppUrl('/change-requests/7', '', null)).toBe(`${ORIGIN}/change-requests/7`);
72
+ });
73
+
74
+ /**
75
+ * The embed's OWN links — the account-link page, a change request, the
76
+ * app's page — arrive already absolute. Refusing them left the reader with
77
+ * a dead "Link your account".
78
+ */
79
+ it('passes an absolute address the embed built itself', () => {
80
+ expect(resolveToAppUrl(`${ORIGIN}/embed/link?token=t`, '', null)).toBe(`${ORIGIN}/embed/link?token=t`);
81
+ expect(resolveToAppUrl('https://elsewhere.example/x', '', null)).toBe('https://elsewhere.example/x');
82
+ });
83
+
84
+ it('still refuses a script address, a protocol-relative one, or an unresolved relative path, among the embed own links', () => {
85
+ expect(resolveToAppUrl('javascript:alert(1)', '', null)).toBeNull();
86
+ expect(resolveToAppUrl('//evil.example/x', '', null)).toBeNull();
87
+ expect(resolveToAppUrl('relative/path', '', null)).toBeNull();
88
+ });
89
+ });
90
+
91
+ describe('what the embed says when it has nothing to show', () => {
92
+ /**
93
+ * The acceptance criterion in words. One sentence, and the one thing the
94
+ * reader can act on — asking again — because only the agent can mint a
95
+ * fresh token.
96
+ */
97
+ it('is one plain sentence that says it expired and that the agent can open it again', () => {
98
+ expect(EMBED_EXPIRED).toBe('This view has expired. Ask the agent to open the page again.');
99
+ expect(EMBED_EXPIRED).toMatch(/expired/i);
100
+ expect(EMBED_EXPIRED).toMatch(/again/i);
101
+ });
102
+ });
103
+
104
+ describe('the relay message', () => {
105
+ it('has the name the view and the MCP App page agree on', () => {
106
+ // The HTML view in `core-backend/mcp-app/page.html` listens for exactly
107
+ // this and answers it with `ui/open-link`; the Forge panel answers it
108
+ // with `router.open`. One string, two hosts.
109
+ expect(EMBED_OPEN_MESSAGE).toBe('bevel-embed-open');
110
+ });
111
+ });
@@ -0,0 +1,295 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ /**
6
+ * The MCP App view the backend serves as `ui://hexis/page-<hash>.html`, RUN — not
7
+ * grepped. It lives in core-backend's packaged `mcp-app/` folder, and this
8
+ * package is the one with a DOM to run it in.
9
+ *
10
+ * What is pinned is the half of the extension protocol a host holds us to —
11
+ * the handshake's required fields, and the shape of the tool result the host
12
+ * delivers (the params ARE the CallToolResult) — and the contract between the
13
+ * view and the deployment's embed bundle: where the view finds the bundle,
14
+ * what it hands it, and what it says when the sandbox will not load it.
15
+ */
16
+ const PAGE = readFileSync(path.resolve(__dirname, '../../../../../core-backend/mcp-app/page.html'), 'utf8');
17
+ const SCRIPT = /<script>([\s\S]*)<\/script>/.exec(PAGE)![1];
18
+ const BODY = /<body>([\s\S]*?)<script>/.exec(PAGE)![1];
19
+ const STYLE = /<style>([\s\S]*?)<\/style>/.exec(PAGE)![1];
20
+
21
+ const ORIGIN = 'https://hexis.example';
22
+ const APP_URL = `${ORIGIN}/workspace/main/knowledge-base/Data/Thing.md`;
23
+
24
+ /** A Vite build manifest as the deployment serves it: the SPA entry, the embed entry, a shared chunk. */
25
+ const MANIFEST = {
26
+ 'index.html': { file: 'assets/index-1a.js', isEntry: true, name: 'main', css: ['assets/index-1a.css'] },
27
+ 'src/embed.tsx': {
28
+ file: 'assets/embed-9f.js',
29
+ isEntry: true,
30
+ name: 'embed',
31
+ css: ['assets/embed-9f.css'],
32
+ imports: ['_shared-3c.js'],
33
+ },
34
+ '_shared-3c.js': { file: 'assets/shared-3c.js', css: ['assets/shared-3c.css'] },
35
+ };
36
+
37
+ let host: { postMessage: ReturnType<typeof vi.fn> };
38
+ let fetchMock: ReturnType<typeof vi.fn>;
39
+ const realParent = Object.getOwnPropertyDescriptor(window, 'parent');
40
+ /**
41
+ * The listeners each run of the view's script registers on the one window
42
+ * these tests share. Removed after every test: left in place, every earlier
43
+ * run would answer the next test's messages too, against elements the
44
+ * document no longer holds.
45
+ */
46
+ const registered: EventListener[] = [];
47
+
48
+ type Handoff = { baseUrl: string; token: string; openLink: (url: string) => void };
49
+ const handoff = () => (window as unknown as { __HEXIS_EMBED__?: Handoff }).__HEXIS_EMBED__;
50
+
51
+ beforeEach(() => {
52
+ // The test is about WHAT the view loads, not about loading it.
53
+ const happyDOM = (
54
+ window as {
55
+ happyDOM?: {
56
+ settings: {
57
+ disableIframePageLoading: boolean;
58
+ disableJavaScriptFileLoading: boolean;
59
+ disableCSSFileLoading: boolean;
60
+ };
61
+ };
62
+ }
63
+ ).happyDOM;
64
+ if (happyDOM) {
65
+ happyDOM.settings.disableIframePageLoading = true;
66
+ happyDOM.settings.disableJavaScriptFileLoading = true;
67
+ happyDOM.settings.disableCSSFileLoading = true;
68
+ }
69
+ document.head.innerHTML = `<style>${STYLE}</style>`;
70
+ document.body.innerHTML = BODY;
71
+ host = { postMessage: vi.fn() };
72
+ Object.defineProperty(window, 'parent', { configurable: true, value: host });
73
+ fetchMock = vi.fn(async () => ({ ok: true, status: 200, json: async () => MANIFEST }));
74
+ vi.stubGlobal('fetch', fetchMock);
75
+ // happy-dom reports every script and stylesheet it was told not to load
76
+ // as a console error; the tests below dispatch the load and error events
77
+ // themselves, so those reports are noise.
78
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
79
+ const addEventListener = window.addEventListener.bind(window);
80
+ vi.spyOn(window, 'addEventListener').mockImplementation((type, listener, options) => {
81
+ if (type === 'message' && listener) registered.push(listener as EventListener);
82
+ addEventListener(type, listener as EventListener, options);
83
+ });
84
+ new Function(SCRIPT)();
85
+ });
86
+
87
+ afterEach(() => {
88
+ for (const listener of registered.splice(0)) window.removeEventListener('message', listener);
89
+ if (realParent) Object.defineProperty(window, 'parent', realParent);
90
+ else delete (window as { parent?: unknown }).parent;
91
+ vi.restoreAllMocks();
92
+ vi.unstubAllGlobals();
93
+ delete (window as unknown as { __HEXIS_EMBED__?: unknown }).__HEXIS_EMBED__;
94
+ });
95
+
96
+ function fromHost(data: unknown) {
97
+ window.dispatchEvent(new MessageEvent('message', { data, source: host as never, origin: 'https://host.example' }));
98
+ }
99
+
100
+ /** A tool result carrying an embed address, as `open_page` answers. */
101
+ function pageResult(structuredContent: Record<string, unknown> = {}) {
102
+ return {
103
+ jsonrpc: '2.0',
104
+ method: 'ui/notifications/tool-result',
105
+ params: {
106
+ content: [{ type: 'text', text: '{}' }],
107
+ structuredContent: { embedUrl: `${ORIGIN}/embed?token=t`, appUrl: APP_URL, ...structuredContent },
108
+ },
109
+ };
110
+ }
111
+
112
+ /** Let the manifest fetch and its continuations run. */
113
+ async function settled() {
114
+ for (let i = 0; i < 4; i += 1) await new Promise((r) => setTimeout(r, 0));
115
+ }
116
+
117
+ const sentMethods = () => host.postMessage.mock.calls.map((c) => (c[0] as { method?: string }).method);
118
+ const notice = () => document.getElementById('notice')!;
119
+ const root = () => document.getElementById('root')!;
120
+ const bundleScript = () => document.querySelector('script[type="module"]') as HTMLScriptElement | null;
121
+
122
+ describe('the MCP App view', () => {
123
+ it('opens with a ui/initialize carrying the app identity and capabilities a host requires', () => {
124
+ const [message] = host.postMessage.mock.calls[0] as [Record<string, unknown>];
125
+ expect(message).toMatchObject({ jsonrpc: '2.0', method: 'ui/initialize' });
126
+ const params = message.params as Record<string, unknown>;
127
+ expect(params.protocolVersion).toEqual(expect.any(String));
128
+ expect(params.appInfo).toMatchObject({ name: expect.any(String), version: expect.any(String) });
129
+ expect(params.appCapabilities).toEqual(expect.any(Object));
130
+ });
131
+
132
+ it('confirms the handshake with ui/notifications/initialized', () => {
133
+ const { id } = host.postMessage.mock.calls[0][0] as { id: string };
134
+ fromHost({ jsonrpc: '2.0', id, result: { protocolVersion: '2026-01-26' } });
135
+ expect(sentMethods()).toContain('ui/notifications/initialized');
136
+ });
137
+
138
+ it('does not confirm a handshake the host rejected', () => {
139
+ const { id } = host.postMessage.mock.calls[0][0] as { id: string };
140
+ fromHost({ jsonrpc: '2.0', id, error: { code: -32600, message: 'unsupported' } });
141
+ expect(sentMethods()).not.toContain('ui/notifications/initialized');
142
+ // And the reader is told, rather than left at "Opening the page…".
143
+ expect(notice().textContent).toBe('The chat app refused to open this page.');
144
+ });
145
+
146
+ /**
147
+ * The view frames nothing — a chat host's sandbox forbids it — so the page
148
+ * is drawn by the deployment's own embed bundle, loaded into the view's
149
+ * document. The bundle is found through the deployment's build manifest,
150
+ * its stylesheets first (its own and those of the chunks it imports), and
151
+ * everything comes from the one origin the embed address names.
152
+ */
153
+ it('loads the deployment embed bundle from its build manifest, with every stylesheet it needs', async () => {
154
+ fromHost(pageResult());
155
+ await settled();
156
+ expect(fetchMock).toHaveBeenCalledWith(`${ORIGIN}/embed-manifest.json`, expect.objectContaining({ credentials: 'omit' }));
157
+ expect(bundleScript()?.getAttribute('src')).toBe(`${ORIGIN}/assets/embed-9f.js`);
158
+ const styles = Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map((l) => l.getAttribute('href'));
159
+ expect(styles).toEqual([`${ORIGIN}/assets/embed-9f.css`, `${ORIGIN}/assets/shared-3c.css`]);
160
+ // Not the SPA's own entry: that one mounts the whole app.
161
+ expect(bundleScript()?.getAttribute('src')).not.toContain('index-1a');
162
+ expect(document.querySelector('iframe')).toBeNull();
163
+ });
164
+
165
+ /**
166
+ * A deployment served under a path prefix has its manifest, its bundle and
167
+ * its API under that prefix — all of which the embed address names, since
168
+ * it is `<public frontend URL>/embed?token=…`.
169
+ */
170
+ it('keeps the path prefix a deployment is served under', async () => {
171
+ fromHost(pageResult({ embedUrl: `${ORIGIN}/hexis/embed?token=t` }));
172
+ await settled();
173
+ expect(fetchMock).toHaveBeenCalledWith(`${ORIGIN}/hexis/embed-manifest.json`, expect.anything());
174
+ expect(bundleScript()?.getAttribute('src')).toBe(`${ORIGIN}/hexis/assets/embed-9f.js`);
175
+ expect(handoff()).toMatchObject({ baseUrl: `${ORIGIN}/hexis`, token: 't' });
176
+ });
177
+
178
+ it('shows one page per view: a second tool result does not load a second bundle', async () => {
179
+ fromHost(pageResult());
180
+ fromHost(pageResult({ embedUrl: `${ORIGIN}/embed?token=t2` }));
181
+ await settled();
182
+ expect(fetchMock).toHaveBeenCalledTimes(1);
183
+ expect(document.querySelectorAll('script[type="module"]')).toHaveLength(1);
184
+ expect(handoff()).toMatchObject({ token: 't' });
185
+ });
186
+
187
+ it('hands the bundle the token, the deployment address and the host way of opening a link, before it runs', async () => {
188
+ fromHost(pageResult());
189
+ await settled();
190
+ expect(handoff()).toMatchObject({ baseUrl: ORIGIN, token: 't' });
191
+ handoff()!.openLink(`${ORIGIN}/workspace/main/knowledge-base/Other.md`);
192
+ const opened = host.postMessage.mock.calls.map((c) => c[0] as { method?: string; params?: { url?: string } });
193
+ expect(opened.find((m) => m.method === 'ui/open-link')?.params?.url).toBe(
194
+ `${ORIGIN}/workspace/main/knowledge-base/Other.md`,
195
+ );
196
+ });
197
+
198
+ it('shows the page once the bundle has run, and the notice until then', async () => {
199
+ fromHost(pageResult());
200
+ await settled();
201
+ // The page's own stylesheet is applied: an id rule giving the root its
202
+ // display must not outrank the class that hides it.
203
+ expect(getComputedStyle(root()).display).toBe('none');
204
+ expect(getComputedStyle(notice()).display).not.toBe('none');
205
+ bundleScript()!.dispatchEvent(new Event('load'));
206
+ expect(getComputedStyle(root()).display).toBe('block');
207
+ expect(getComputedStyle(notice()).display).toBe('none');
208
+ });
209
+
210
+ /**
211
+ * A host starts an app view a few lines tall and grows it only when the
212
+ * view asks. The page scrolls inside the view, so the ask is a reading
213
+ * height, sent once the page is on screen — a notice needs no room.
214
+ */
215
+ it('asks the host for a reading height once the page is on screen, and not before', async () => {
216
+ const sizeRequests = () =>
217
+ host.postMessage.mock.calls
218
+ .map((c) => c[0] as { method?: string; params?: { height?: unknown } })
219
+ .filter((m) => m.method === 'ui/notifications/size-changed');
220
+ fromHost(pageResult());
221
+ await settled();
222
+ expect(sizeRequests()).toHaveLength(0);
223
+ bundleScript()!.dispatchEvent(new Event('load'));
224
+ // The one height the view asks for, pinned: a document pane's reading
225
+ // height, and the number the changeset documents.
226
+ expect(sizeRequests()).toEqual([
227
+ { jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 640 } },
228
+ ]);
229
+ });
230
+
231
+ it('asks for no room when there is only a sentence to show', async () => {
232
+ fetchMock.mockRejectedValue(new TypeError('Failed to fetch'));
233
+ fromHost(pageResult());
234
+ await settled();
235
+ expect(sentMethods()).not.toContain('ui/notifications/size-changed');
236
+ });
237
+
238
+ it.each([
239
+ ['the manifest cannot be fetched', () => fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))],
240
+ ['the manifest answers an error', () => fetchMock.mockResolvedValue({ ok: false, status: 404, json: async () => ({}) })],
241
+ [
242
+ 'the manifest names no embed entry',
243
+ () => fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ 'index.html': MANIFEST['index.html'] }) }),
244
+ ],
245
+ ])('says the page could not load and offers the app when %s', async (_label, arrange) => {
246
+ arrange();
247
+ fromHost(pageResult());
248
+ await settled();
249
+ expect(notice().textContent).toContain('did not let the page load');
250
+ const link = notice().querySelector('a')!;
251
+ expect(link.textContent).toBe('Open it in the knowledge base');
252
+ link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
253
+ const opened = host.postMessage.mock.calls.map((c) => c[0] as { method?: string; params?: { url?: string } });
254
+ expect(opened.find((m) => m.method === 'ui/open-link')?.params?.url).toBe(APP_URL);
255
+ expect(bundleScript()).toBeNull();
256
+ });
257
+
258
+ it('says the page could not load when the sandbox refuses the bundle script', async () => {
259
+ fromHost(pageResult());
260
+ await settled();
261
+ bundleScript()!.dispatchEvent(new Event('error'));
262
+ expect(notice().textContent).toContain('did not let the page load');
263
+ expect(getComputedStyle(root()).display).toBe('none');
264
+ });
265
+
266
+ it('says why there is no view when the result carries no embed address', () => {
267
+ fromHost({
268
+ jsonrpc: '2.0',
269
+ method: 'ui/notifications/tool-result',
270
+ params: { structuredContent: { note: 'The embedded view needs an https deployment.' } },
271
+ });
272
+ expect(notice().textContent).toContain('needs an https deployment');
273
+ expect(fetchMock).not.toHaveBeenCalled();
274
+ expect(getComputedStyle(root()).display).toBe('none');
275
+ });
276
+
277
+ it('shows the reason a refused call gave, from its text block', () => {
278
+ fromHost({
279
+ jsonrpc: '2.0',
280
+ method: 'ui/notifications/tool-result',
281
+ params: { isError: true, content: [{ type: 'text', text: 'File not found: Notes/missing.md' }] },
282
+ });
283
+ expect(notice().textContent).toBe('File not found: Notes/missing.md');
284
+ expect(fetchMock).not.toHaveBeenCalled();
285
+ });
286
+
287
+ it('ignores a message that did not come from the host', async () => {
288
+ window.dispatchEvent(
289
+ new MessageEvent('message', { data: pageResult(), source: null, origin: 'https://elsewhere.example' }),
290
+ );
291
+ await settled();
292
+ expect(fetchMock).not.toHaveBeenCalled();
293
+ expect(handoff()).toBeUndefined();
294
+ });
295
+ });