@bevel-software/platform-core-frontend 0.26.0 → 0.27.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.
- package/package.json +2 -2
- package/src/core/CoreAppShell.tsx +87 -25
- package/src/core/ProductName.tsx +49 -0
- package/src/core/__tests__/ShellRoutes.test.tsx +22 -0
- package/src/core/__tests__/core-contributions.test.ts +16 -0
- package/src/core/core-contributions.ts +17 -0
- package/src/core/registry.ts +51 -1
- package/src/index.css +23 -5
- package/src/index.ts +5 -0
- package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +1 -1
- package/src/modules/access/components/ManageAccessDialog.tsx +1 -1
- package/src/modules/admin/__tests__/RolesCorruptedBanner.test.tsx +70 -0
- package/src/modules/admin/components/RolesCorruptedBanner.tsx +9 -4
- package/src/modules/auth/components/LoginScreen.tsx +4 -1
- package/src/modules/auth/services/account.api.ts +28 -1
- package/src/modules/auth/services/sso.ts +1 -2
- package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +176 -0
- package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +68 -0
- package/src/modules/change-requests/__tests__/ChangeRequestLink.test.tsx +182 -0
- package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +1 -1
- package/src/modules/change-requests/__tests__/readFileOnBranch.test.ts +79 -0
- package/src/modules/change-requests/components/ChangeBox.tsx +6 -1
- package/src/modules/change-requests/components/ChangeRequestDialog.tsx +45 -15
- package/src/modules/change-requests/components/ChangeRequestLink.tsx +151 -0
- package/src/modules/change-requests/components/CrFileTree.tsx +2 -1
- package/src/modules/change-requests/components/FileChangeBoxes.tsx +4 -2
- package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +6 -3
- package/src/modules/change-requests/services/change-requests.api.ts +15 -2
- package/src/modules/change-requests/utils/readFailure.ts +22 -0
- package/src/modules/embed/__tests__/EmbedLinkPage.test.tsx +74 -0
- package/src/modules/embed/__tests__/EmbedView.test.tsx +473 -0
- package/src/modules/embed/__tests__/embed-config.test.ts +128 -0
- package/src/modules/embed/__tests__/embed-host.test.ts +111 -0
- package/src/modules/embed/__tests__/mcp-app-view.test.ts +295 -0
- package/src/modules/embed/__tests__/mount.test.tsx +157 -0
- package/src/modules/embed/components/EmbedLinkPage.tsx +109 -0
- package/src/modules/embed/components/EmbedView.tsx +545 -0
- package/src/modules/embed/embed-config.ts +132 -0
- package/src/modules/embed/embed-host.ts +120 -0
- package/src/modules/embed/mount.tsx +80 -0
- package/src/modules/embed/services/embed-token.ts +22 -0
- package/src/modules/embed/services/embed.api.ts +158 -0
- package/src/modules/git/__tests__/BranchSwitcher.test.tsx +202 -4
- package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +59 -1
- package/src/modules/git/__tests__/PullNeededBanner.test.tsx +39 -22
- package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +7 -2
- package/src/modules/git/branch-delete-menu-item.tsx +24 -0
- package/src/modules/git/components/BranchSwitcher.tsx +29 -5
- package/src/modules/git/components/GitSyncFailedBanner.tsx +53 -15
- package/src/modules/git/components/HistoryVersionPreview.tsx +5 -3
- package/src/modules/git/components/PullNeededBanner.tsx +15 -49
- package/src/modules/git/hooks/useAutoPullUpdates.ts +9 -5
- package/src/modules/git/index.ts +15 -0
- package/src/modules/git/services/__tests__/error-messages.test.ts +67 -0
- package/src/modules/git/services/__tests__/pull-failure.test.ts +36 -0
- package/src/modules/git/services/error-messages.ts +58 -1
- package/src/modules/git/services/pull-failure.ts +68 -0
- package/src/modules/git/state/branch-delete-confirm.ts +46 -0
- package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +1 -0
- package/src/modules/layout/__tests__/breakpoints.test.ts +7 -1
- package/src/modules/layout/breakpoints.ts +8 -0
- package/src/modules/library/__tests__/PluginExtras.test.tsx +9 -9
- package/src/modules/library/__tests__/PluginPage.test.tsx +8 -1
- package/src/modules/library/__tests__/SkillsTree.test.tsx +13 -4
- package/src/modules/library/components/LibraryPage.tsx +22 -0
- package/src/modules/library/components/PluginExtras.tsx +23 -6
- package/src/modules/library/components/PluginPage.tsx +6 -1
- package/src/modules/library/routes/LibraryRoutes.tsx +8 -7
- package/src/modules/library/services/plugins.api.ts +4 -1
- package/src/modules/library/state/plugins-revision.ts +28 -0
- package/src/modules/onboarding/__tests__/agent-connection-api.test.ts +55 -0
- package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +87 -82
- package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +109 -0
- package/src/modules/onboarding/__tests__/get-started-column.test.tsx +1001 -0
- package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +392 -0
- package/src/modules/onboarding/__tests__/onboarding.test.tsx +226 -193
- package/src/modules/onboarding/__tests__/starter-pack-card.test.tsx +136 -0
- package/src/modules/onboarding/components/CreatorWelcomePage.tsx +7 -11
- package/src/modules/onboarding/components/EmailChipsInput.tsx +138 -0
- package/src/modules/onboarding/components/GetStartedColumn.tsx +651 -0
- package/src/modules/onboarding/components/InviteButton.tsx +35 -0
- package/src/modules/onboarding/components/InviteDialog.tsx +424 -0
- package/src/modules/onboarding/components/RootLanding.tsx +8 -24
- package/src/modules/onboarding/components/StarterPackCard.tsx +98 -0
- package/src/modules/onboarding/components/WelcomePage.tsx +65 -154
- package/src/modules/onboarding/first-page-prompt.ts +89 -0
- package/src/modules/onboarding/invite-emails.ts +175 -0
- package/src/modules/onboarding/services/agent-connection.api.ts +53 -0
- package/src/modules/onboarding/services/starter-packs.api.ts +83 -0
- package/src/modules/onboarding/state/agent-connection.ts +167 -0
- package/src/modules/onboarding/state/invite-dialog.context.ts +32 -0
- package/src/modules/onboarding/state/invite-dialog.tsx +31 -0
- package/src/modules/onboarding/state/onboarding.ts +133 -59
- package/src/modules/onboarding/state/starter-packs.ts +169 -0
- package/src/modules/settings/settings-nav-items.tsx +8 -3
- package/src/modules/setup/__tests__/setup.first-run-storage.test.tsx +389 -0
- package/src/modules/setup/__tests__/setup.github.test.tsx +5 -5
- package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +1 -1
- package/src/modules/setup/__tests__/setup.repository-change.test.tsx +1 -1
- package/src/modules/setup/__tests__/setup.repository.test.tsx +21 -21
- package/src/modules/setup/__tests__/setup.test.tsx +56 -15
- package/src/modules/setup/__tests__/useConnectionProbe.test.tsx +123 -0
- package/src/modules/setup/components/FirstRunStorage.tsx +560 -0
- package/src/modules/setup/components/SetupGate.tsx +46 -1
- package/src/modules/setup/components/SetupScreen.tsx +81 -84
- package/src/modules/setup/hooks/useConnectionProbe.ts +93 -0
- package/src/modules/setup/services/setup.api.ts +3 -3
- package/src/modules/setup/utils/suggested-branch.ts +27 -0
- package/src/modules/toolbar/commands/__tests__/actions.test.tsx +210 -0
- package/src/modules/toolbar/commands/actions.tsx +324 -0
- package/src/modules/toolbar/commands/command-menu.ts +44 -0
- package/src/modules/toolbar/commands/useCommandActions.ts +69 -0
- package/src/modules/toolbar/commands/useCommandShortcuts.ts +121 -0
- package/src/modules/toolbar/components/AppSwitcher.tsx +106 -22
- package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +1 -1
- package/src/modules/toolbar/components/ProfileMenu.tsx +9 -4
- package/src/modules/toolbar/components/SearchPalette.tsx +540 -0
- package/src/modules/toolbar/components/Toolbar.tsx +10 -0
- package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +187 -54
- package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +64 -0
- package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +832 -0
- package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +57 -2
- package/src/modules/toolbar/search/__tests__/rank.test.ts +93 -0
- package/src/modules/toolbar/search/__tests__/sources.test.ts +131 -0
- package/src/modules/toolbar/search/rank.ts +111 -0
- package/src/modules/toolbar/search/sources.ts +169 -0
- package/src/modules/workflow/hooks/useFileLock.ts +10 -7
- package/src/modules/workflow/services/__tests__/lock.api.test.ts +41 -0
- package/src/modules/workflow/services/lock.api.ts +17 -2
- package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +49 -1
- package/src/modules/workspace/components/EditorTabs.tsx +39 -15
- package/src/modules/workspace/components/FileExplorer.tsx +39 -6
- package/src/modules/workspace/components/FilePaneCard.tsx +6 -2
- package/src/modules/workspace/components/FileRoute.tsx +12 -7
- package/src/modules/workspace/components/FileViewer.tsx +271 -74
- package/src/modules/workspace/components/KbPageHeader.tsx +13 -6
- package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +88 -21
- package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +92 -4
- package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +23 -3
- package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +330 -6
- package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +17 -2
- package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -16
- package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +6 -0
- package/src/modules/workspace/components/renderers/EmailRenderer.tsx +23 -21
- package/src/modules/workspace/components/renderers/ImageRenderer.tsx +13 -29
- package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +9 -2
- package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +8 -0
- package/src/modules/workspace/components/renderers/PdfRenderer.tsx +14 -19
- package/src/modules/workspace/components/renderers/PptxRenderer.tsx +11 -17
- package/src/modules/workspace/components/renderers/ToolRenderer.tsx +35 -7
- package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -17
- package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.links.test.tsx +73 -0
- package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.scaffold.test.tsx +64 -0
- package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +82 -0
- package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +99 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +129 -35
- package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +149 -0
- package/src/modules/workspace/components/renderers/__tests__/kbMarkdownLinkPolicy.test.tsx +100 -0
- package/src/modules/workspace/components/renderers/htmlSandbox.ts +76 -20
- package/src/modules/workspace/components/renderers/index.ts +26 -0
- package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +51 -1
- package/src/modules/workspace/components/renderers/rendererRawRead.ts +53 -0
- package/src/modules/workspace/components/renderers/rendererSurface.ts +109 -0
- package/src/modules/workspace/components/renderers/rendererWorkspace.ts +8 -2
- package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +126 -21
- package/src/modules/workspace/hooks/useCreatePage.ts +116 -0
- package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +24 -7
- package/src/modules/workspace/hooks/useWorkspaceState.ts +42 -8
- package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +10 -0
- package/src/modules/workspace/routing/__tests__/md-links-parity.test.tsx +113 -0
- package/src/modules/workspace/routing/kb-routes.ts +66 -12
- package/src/modules/workspace/state/editable-page.ts +42 -0
- package/src/modules/workspace/state/workspace.context.ts +13 -4
- package/src/modules/workspace/utils/__tests__/display-file-name.test.ts +60 -0
- package/src/modules/workspace/utils/__tests__/fileTree.test.ts +75 -0
- package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +16 -0
- package/src/modules/workspace/utils/display-file-name.ts +102 -0
- package/src/modules/workspace/utils/fileTree.ts +49 -14
- package/src/modules/workspace/utils/treeConfirm.ts +15 -0
- package/src/shared/__tests__/no-builtin-confirm.test.ts +102 -0
- package/src/shared/components/ConfirmProvider.tsx +156 -0
- package/src/shared/components/Dialog.tsx +7 -0
- package/src/shared/components/__tests__/ConfirmProvider.test.tsx +198 -0
- package/src/shared/components/confirm-context.ts +94 -0
- package/src/shared/components/index.ts +3 -0
- package/src/modules/onboarding/components/WelcomeRoute.tsx +0 -57
- package/src/modules/onboarding/welcome-state.ts +0 -36
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
|
3
|
+
import type { AppRegistry } from '../../../core/registry';
|
|
4
|
+
import type { EmbedFileView } from '../services/embed.api';
|
|
5
|
+
import { embedApiBase, resetEmbedConfig } from '../embed-config';
|
|
6
|
+
|
|
7
|
+
/** The HTTP surface, stubbed — the mount is about wiring, not about the API. */
|
|
8
|
+
const api = vi.hoisted(() => {
|
|
9
|
+
class FakeEmbedApiError extends Error {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
constructor(status: number, message: string) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'EmbedApiError';
|
|
14
|
+
this.status = status;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
EmbedApiError: FakeEmbedApiError,
|
|
19
|
+
loadEmbed: vi.fn(),
|
|
20
|
+
lockEmbed: vi.fn(),
|
|
21
|
+
heartbeatEmbed: vi.fn(),
|
|
22
|
+
cancelEmbed: vi.fn(),
|
|
23
|
+
saveEmbed: vi.fn(),
|
|
24
|
+
proposeEmbed: vi.fn(),
|
|
25
|
+
embedRawUrl: vi.fn((token: string, path?: string) => `/api/embed/raw?token=${token}${path ? `&path=${path}` : ''}`),
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
vi.mock('../services/embed.api', () => api);
|
|
29
|
+
|
|
30
|
+
import { mountEmbed } from '../mount';
|
|
31
|
+
|
|
32
|
+
const ORIGIN = 'https://hexis.example';
|
|
33
|
+
|
|
34
|
+
const VIEW: EmbedFileView = {
|
|
35
|
+
nodeName: 'Thing',
|
|
36
|
+
repoRelative: 'Data/Thing.md',
|
|
37
|
+
workspacePath: 'knowledge-base/Data/Thing.md',
|
|
38
|
+
kbDirName: 'knowledge-base',
|
|
39
|
+
branch: 'main',
|
|
40
|
+
appUrl: `${ORIGIN}/workspace/main/knowledge-base/Data/Thing.md`,
|
|
41
|
+
content: '# Thing\n\nWhat it is.\n',
|
|
42
|
+
contentIsText: true,
|
|
43
|
+
linked: true,
|
|
44
|
+
canRead: true,
|
|
45
|
+
canWrite: false,
|
|
46
|
+
linkUrl: `${ORIGIN}/embed/link?token=tok`,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const EMPTY_REGISTRY = {
|
|
50
|
+
apps: [],
|
|
51
|
+
panes: [],
|
|
52
|
+
topLevelRoutes: [],
|
|
53
|
+
viewerRoutes: [],
|
|
54
|
+
renderers: [],
|
|
55
|
+
banners: [],
|
|
56
|
+
fileViewerPanels: [],
|
|
57
|
+
adminMenuItems: [],
|
|
58
|
+
explorerItems: [],
|
|
59
|
+
folderMenuItems: [],
|
|
60
|
+
settingsNavItems: [],
|
|
61
|
+
} as unknown as AppRegistry;
|
|
62
|
+
|
|
63
|
+
let el: HTMLElement;
|
|
64
|
+
let handle: { unmount(): void } | null = null;
|
|
65
|
+
|
|
66
|
+
beforeEach(() => {
|
|
67
|
+
for (const fn of Object.values(api)) (fn as { mockReset?: () => void }).mockReset?.();
|
|
68
|
+
api.loadEmbed.mockResolvedValue(VIEW);
|
|
69
|
+
el = document.createElement('div');
|
|
70
|
+
document.body.appendChild(el);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
handle?.unmount();
|
|
75
|
+
handle = null;
|
|
76
|
+
el.remove();
|
|
77
|
+
resetEmbedConfig();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* What the MCP App view calls after loading the deployment's embed bundle
|
|
82
|
+
* into a chat host's sandbox: the same embed the `/embed` route renders,
|
|
83
|
+
* mounted outside the app, with the token handed in rather than read from a
|
|
84
|
+
* page URL the sandbox does not have.
|
|
85
|
+
*/
|
|
86
|
+
describe('mountEmbed', () => {
|
|
87
|
+
it('renders the page for the token it was handed, with the app renderer for the type', async () => {
|
|
88
|
+
handle = mountEmbed(el, { registry: EMPTY_REGISTRY, baseUrl: ORIGIN, token: 'tok' });
|
|
89
|
+
expect(await screen.findByRole('heading', { name: 'Thing' })).toBeTruthy();
|
|
90
|
+
expect(api.loadEmbed).toHaveBeenCalledWith('tok');
|
|
91
|
+
// A reader who may not write is offered a proposal, as on the file page.
|
|
92
|
+
expect(screen.getByRole('button', { name: 'Propose changes' })).toBeTruthy();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('mounts a renderer the deployment registered, so the chat shows what the file page shows', async () => {
|
|
96
|
+
const registry = {
|
|
97
|
+
...EMPTY_REGISTRY,
|
|
98
|
+
renderers: [{ extensions: ['.md'], Component: () => <div data-testid="deployment-md">the deployment renderer</div> }],
|
|
99
|
+
} as unknown as AppRegistry;
|
|
100
|
+
handle = mountEmbed(el, { registry, baseUrl: ORIGIN, token: 'tok' });
|
|
101
|
+
expect(await screen.findByTestId('deployment-md')).toBeTruthy();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The runtime the embed reads is per document, so one mount owns it at a
|
|
106
|
+
* time: a second mount takes the first down, and the one that owns the
|
|
107
|
+
* runtime hands it back on unmount — a replaced handle does not reset what
|
|
108
|
+
* its successor configured.
|
|
109
|
+
*/
|
|
110
|
+
it('holds one embed per document, and hands the runtime back on unmount', async () => {
|
|
111
|
+
const first = mountEmbed(el, { registry: EMPTY_REGISTRY, baseUrl: ORIGIN, token: 'tok' });
|
|
112
|
+
await screen.findByRole('heading', { name: 'Thing' });
|
|
113
|
+
const second = document.createElement('div');
|
|
114
|
+
document.body.appendChild(second);
|
|
115
|
+
handle = mountEmbed(second, { registry: EMPTY_REGISTRY, baseUrl: 'https://other.example', token: 'tok2' });
|
|
116
|
+
await screen.findByRole('heading', { name: 'Thing' });
|
|
117
|
+
expect(el.textContent).toBe('');
|
|
118
|
+
expect(embedApiBase()).toBe('https://other.example');
|
|
119
|
+
expect(api.loadEmbed).toHaveBeenLastCalledWith('tok2');
|
|
120
|
+
// The replaced handle is inert.
|
|
121
|
+
first.unmount();
|
|
122
|
+
expect(embedApiBase()).toBe('https://other.example');
|
|
123
|
+
handle.unmount();
|
|
124
|
+
handle = null;
|
|
125
|
+
expect(embedApiBase()).toBe('');
|
|
126
|
+
second.remove();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A view taken down mid-edit — replaced by a second mount, or unmounted
|
|
131
|
+
* outright — lets go of its edit lock on the way out, rather than leaving
|
|
132
|
+
* the file shut to other writers until the lock's TTL.
|
|
133
|
+
*/
|
|
134
|
+
it('releases an edit lock the view holds when it is taken down', async () => {
|
|
135
|
+
api.loadEmbed.mockResolvedValue({ ...VIEW, canWrite: true });
|
|
136
|
+
api.lockEmbed.mockResolvedValue({ acquired: true });
|
|
137
|
+
api.cancelEmbed.mockResolvedValue(undefined);
|
|
138
|
+
const first = mountEmbed(el, { registry: EMPTY_REGISTRY, baseUrl: ORIGIN, token: 'tok' });
|
|
139
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
|
|
140
|
+
await screen.findByRole('button', { name: 'Save' });
|
|
141
|
+
expect(api.cancelEmbed).not.toHaveBeenCalled();
|
|
142
|
+
const second = document.createElement('div');
|
|
143
|
+
document.body.appendChild(second);
|
|
144
|
+
handle = mountEmbed(second, { registry: EMPTY_REGISTRY, baseUrl: ORIGIN, token: 'tok2' });
|
|
145
|
+
await waitFor(() => expect(api.cancelEmbed).toHaveBeenCalledWith('tok'));
|
|
146
|
+
expect(first).toBeDefined();
|
|
147
|
+
second.remove();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('unmounts cleanly', async () => {
|
|
151
|
+
handle = mountEmbed(el, { registry: EMPTY_REGISTRY, baseUrl: ORIGIN, token: 'tok' });
|
|
152
|
+
await screen.findByRole('heading', { name: 'Thing' });
|
|
153
|
+
handle.unmount();
|
|
154
|
+
handle = null;
|
|
155
|
+
expect(el.textContent).toBe('');
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { useCallback, useState, type ReactNode } from 'react';
|
|
2
|
+
import { Button } from '../../../shared/components';
|
|
3
|
+
import { AuthContext } from '../../auth/state/auth.context';
|
|
4
|
+
import { useAuthState } from '../../auth/hooks/useAuthState';
|
|
5
|
+
import { LoginScreen } from '../../auth/components/LoginScreen';
|
|
6
|
+
import { getToken } from '../../../lib/api';
|
|
7
|
+
import { linkEmbedAccount } from '../services/embed.api';
|
|
8
|
+
import { outsideAccountOf } from '../services/embed-token';
|
|
9
|
+
|
|
10
|
+
function tokenFromUrl(): string {
|
|
11
|
+
return new URLSearchParams(window.location.search).get('token') ?? '';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function Centered({ children }: { children: ReactNode }) {
|
|
15
|
+
return (
|
|
16
|
+
<div className="flex h-full items-center justify-center bg-white px-6 text-center text-sm text-ink">
|
|
17
|
+
<div className="max-w-sm">{children}</div>
|
|
18
|
+
</div>
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The account-link page, opened in a new tab when an embed viewer whose
|
|
24
|
+
* outside account is not yet linked clicks Edit. It signs them in the ordinary
|
|
25
|
+
* way and then — once they CONFIRM it, naming both accounts — links the
|
|
26
|
+
* account the embed token carries to the user they just authenticated as.
|
|
27
|
+
*
|
|
28
|
+
* The confirmation is not a courtesy. A link to this page can be crafted by
|
|
29
|
+
* anybody holding a token for their own outside account; followed silently by
|
|
30
|
+
* a signed-in victim, it would bind the attacker's account to the victim's,
|
|
31
|
+
* and hand the attacker the victim's knowledge-base access from then on.
|
|
32
|
+
* Refusing to be framed does nothing against a top-level link, so nothing is
|
|
33
|
+
* linked until the person who is signed in says so.
|
|
34
|
+
*
|
|
35
|
+
* THIS PAGE IS NEVER FRAMED, and that is the whole reason it is a page of its
|
|
36
|
+
* own rather than a step inside the embed. It acts under the signed-in
|
|
37
|
+
* session, so a page that could frame it could link a foreign account to
|
|
38
|
+
* whoever happened to be signed in — and from then on read and write the
|
|
39
|
+
* knowledge base as them. The server sends `frame-ancestors 'none'` and
|
|
40
|
+
* `X-Frame-Options: DENY` for exactly this route; the embed page, which acts
|
|
41
|
+
* under a token alone, sends no framing restriction at all.
|
|
42
|
+
*/
|
|
43
|
+
export function EmbedLinkPage() {
|
|
44
|
+
const auth = useAuthState();
|
|
45
|
+
const token = tokenFromUrl();
|
|
46
|
+
const [status, setStatus] = useState<'idle' | 'linking' | 'done' | 'declined' | 'error'>('idle');
|
|
47
|
+
const [error, setError] = useState<string | null>(null);
|
|
48
|
+
const outside = outsideAccountOf(token);
|
|
49
|
+
|
|
50
|
+
const onLink = useCallback(() => {
|
|
51
|
+
setStatus('linking');
|
|
52
|
+
linkEmbedAccount(token, getToken())
|
|
53
|
+
.then(() => setStatus('done'))
|
|
54
|
+
.catch((err: unknown) => {
|
|
55
|
+
setError(err instanceof Error ? err.message : 'Linking failed.');
|
|
56
|
+
setStatus('error');
|
|
57
|
+
});
|
|
58
|
+
}, [token]);
|
|
59
|
+
|
|
60
|
+
return (
|
|
61
|
+
<AuthContext.Provider value={auth}>
|
|
62
|
+
{auth.isLoading ? (
|
|
63
|
+
<Centered>Loading…</Centered>
|
|
64
|
+
) : !auth.user ? (
|
|
65
|
+
<LoginScreen />
|
|
66
|
+
) : !token ? (
|
|
67
|
+
<Centered>This link has no token. Open it again from the page in your chat.</Centered>
|
|
68
|
+
) : status === 'done' ? (
|
|
69
|
+
<Centered>
|
|
70
|
+
<p className="mb-1 text-base font-semibold text-ink">Account linked</p>
|
|
71
|
+
<p>
|
|
72
|
+
{/* Not "click Edit": whether the page offers Edit or Propose
|
|
73
|
+
changes depends on this person's access, which this page
|
|
74
|
+
does not know. */}
|
|
75
|
+
Your account is connected. Close this tab and reload the page you came from.
|
|
76
|
+
</p>
|
|
77
|
+
</Centered>
|
|
78
|
+
) : status === 'error' ? (
|
|
79
|
+
<Centered>
|
|
80
|
+
<p role="alert" className="text-danger">
|
|
81
|
+
Could not link your account: {error}
|
|
82
|
+
</p>
|
|
83
|
+
</Centered>
|
|
84
|
+
) : status === 'declined' ? (
|
|
85
|
+
<Centered>Nothing was linked. You can close this tab.</Centered>
|
|
86
|
+
) : status === 'linking' ? (
|
|
87
|
+
<Centered>Linking your account…</Centered>
|
|
88
|
+
) : (
|
|
89
|
+
<Centered>
|
|
90
|
+
<p className="mb-1 text-base font-semibold text-ink">Link your Atlassian account?</p>
|
|
91
|
+
<p className="mb-3">
|
|
92
|
+
The Atlassian account{' '}
|
|
93
|
+
{outside ? <code className="break-all">{outside}</code> : 'in this link'} will read and edit
|
|
94
|
+
this knowledge base as <strong>{auth.user.email}</strong>. Only continue if you opened this
|
|
95
|
+
link yourself, from a page in Jira or Confluence.
|
|
96
|
+
</p>
|
|
97
|
+
<span className="flex justify-center gap-2">
|
|
98
|
+
<Button variant="quiet" size="sm" onClick={() => setStatus('declined')}>
|
|
99
|
+
Cancel
|
|
100
|
+
</Button>
|
|
101
|
+
<Button variant="primary" size="sm" onClick={onLink}>
|
|
102
|
+
Link accounts
|
|
103
|
+
</Button>
|
|
104
|
+
</span>
|
|
105
|
+
</Centered>
|
|
106
|
+
)}
|
|
107
|
+
</AuthContext.Provider>
|
|
108
|
+
);
|
|
109
|
+
}
|