@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
@@ -6,6 +6,7 @@ import type {
6
6
  import { authFetch } from '../../../lib/api';
7
7
  import { handleApiResponse } from '../../git/services/git.api';
8
8
  import { getOrCreateWorkspace, readFile } from '../../workspace/services/workspace.api';
9
+ import { BranchUnavailableError } from '../utils/readFailure';
9
10
 
10
11
  /**
11
12
  * The change-request module's data access — the reads every review surface
@@ -70,9 +71,21 @@ export async function removeFolderFromChangeRequests(folder: string): Promise<Fo
70
71
  return data.results;
71
72
  }
72
73
 
73
- /** Read a file from a branch's shared workspace (bootstraps the clone if needed). */
74
+ /**
75
+ * Read a file from a branch's shared workspace (bootstraps the clone if
76
+ * needed). A failure to open the branch is answered as
77
+ * {@link BranchUnavailableError}, never as the file read's own error: both
78
+ * answer 404 for different reasons, and a caller that reads a file-read 404
79
+ * as "the branch has no such file" must not be told that about a branch that
80
+ * could not be opened.
81
+ */
74
82
  export async function readFileOnBranch(branch: string, repoRelativePath: string): Promise<string> {
75
- const { workspace } = await getOrCreateWorkspace(branch);
83
+ let workspace: Awaited<ReturnType<typeof getOrCreateWorkspace>>['workspace'];
84
+ try {
85
+ ({ workspace } = await getOrCreateWorkspace(branch));
86
+ } catch (err: unknown) {
87
+ throw new BranchUnavailableError(branch, err);
88
+ }
76
89
  return readFile(workspace.id, `${workspace.kbDirName}/${repoRelativePath}`);
77
90
  }
78
91
 
@@ -27,6 +27,28 @@ export function statusOf(err: unknown): number | null {
27
27
  return typeof status === 'number' ? status : null;
28
28
  }
29
29
 
30
+ /**
31
+ * A read that never reached the file: opening the BRANCH failed, so nothing
32
+ * was said about the path. Kept apart from the file read's own errors because
33
+ * the two share a status and mean opposite things — a 404 from the file read
34
+ * says "this branch has no such file", which a request that removes the file
35
+ * is exactly expected to answer; a 404 from the branch says the branch itself
36
+ * is gone, which says nothing about the file at all. `status` is the cause's,
37
+ * so a refusal to open the branch still reads as a refusal.
38
+ */
39
+ export class BranchUnavailableError extends Error {
40
+ readonly branch: string;
41
+ readonly cause: unknown;
42
+ readonly status: number | null;
43
+ constructor(branch: string, cause: unknown) {
44
+ super(`the branch ${branch} couldn't be opened (${failureReason(cause)})`);
45
+ this.name = 'BranchUnavailableError';
46
+ this.branch = branch;
47
+ this.cause = cause;
48
+ this.status = statusOf(cause);
49
+ }
50
+ }
51
+
30
52
  /** A read the server refused because the caller may not see the path. */
31
53
  export function isDenial(err: unknown): boolean {
32
54
  return statusOf(err) === 403;
@@ -0,0 +1,74 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+
5
+ const mocks = vi.hoisted(() => ({
6
+ linkEmbedAccount: vi.fn(),
7
+ auth: {
8
+ user: { id: 'u-1', email: 'alice@bevel.software', name: 'Alice' } as unknown,
9
+ isLoading: false,
10
+ },
11
+ }));
12
+ vi.mock('../services/embed.api', () => ({ linkEmbedAccount: mocks.linkEmbedAccount }));
13
+ vi.mock('../../auth/hooks/useAuthState', () => ({ useAuthState: () => mocks.auth }));
14
+ vi.mock('../../auth/components/LoginScreen', () => ({ LoginScreen: () => <p>Sign in</p> }));
15
+ vi.mock('../../../lib/api', () => ({ getToken: () => 'session-bearer' }));
16
+
17
+ import { EmbedLinkPage } from '../components/EmbedLinkPage';
18
+ import { outsideAccountOf } from '../services/embed-token';
19
+
20
+ /** A token shaped like the server's: only the payload is read, for display. */
21
+ function tokenFor(claims: Record<string, unknown>): string {
22
+ const payload = btoa(JSON.stringify(claims)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
23
+ return `eyJhbGciOiJIUzI1NiJ9.${payload}.sig`;
24
+ }
25
+
26
+ const TOKEN = tokenFor({ scope: 'embed', kind: 'atlassian', sub: '557058:abc-def', repoRelative: 'Data/x.md' });
27
+
28
+ beforeEach(() => {
29
+ mocks.linkEmbedAccount.mockReset();
30
+ window.history.replaceState({}, '', `/embed/link?token=${TOKEN}`);
31
+ });
32
+
33
+ /**
34
+ * Anybody holding a token for their OWN outside account can craft a link to
35
+ * this page. Followed by a signed-in victim, a silent link would bind the
36
+ * attacker's account to the victim's — so nothing is linked until the person
37
+ * signed in confirms it, seeing both accounts named.
38
+ */
39
+ describe('the account-link page', () => {
40
+ it('links nothing on arrival — it asks first, naming both accounts', async () => {
41
+ render(<EmbedLinkPage />);
42
+ expect(await screen.findByText('Link your Atlassian account?')).toBeTruthy();
43
+ expect(screen.getByText('557058:abc-def')).toBeTruthy();
44
+ expect(screen.getByText('alice@bevel.software')).toBeTruthy();
45
+ expect(mocks.linkEmbedAccount).not.toHaveBeenCalled();
46
+ });
47
+
48
+ it('links when the signed-in person confirms', async () => {
49
+ mocks.linkEmbedAccount.mockResolvedValue(undefined);
50
+ render(<EmbedLinkPage />);
51
+ await userEvent.click(await screen.findByRole('button', { name: 'Link accounts' }));
52
+ await waitFor(() => expect(mocks.linkEmbedAccount).toHaveBeenCalledWith(TOKEN, 'session-bearer'));
53
+ expect(await screen.findByText('Account linked')).toBeTruthy();
54
+ });
55
+
56
+ it('links nothing when they cancel', async () => {
57
+ render(<EmbedLinkPage />);
58
+ await userEvent.click(await screen.findByRole('button', { name: 'Cancel' }));
59
+ expect(await screen.findByText(/Nothing was linked/)).toBeTruthy();
60
+ expect(mocks.linkEmbedAccount).not.toHaveBeenCalled();
61
+ });
62
+ });
63
+
64
+ describe('outsideAccountOf', () => {
65
+ it('reads the outside account a token names', () => {
66
+ expect(outsideAccountOf(TOKEN)).toBe('557058:abc-def');
67
+ });
68
+
69
+ it('answers null for a token minted for a Hexis user, or one it cannot read', () => {
70
+ expect(outsideAccountOf(tokenFor({ kind: 'user', sub: 'u-1' }))).toBeNull();
71
+ expect(outsideAccountOf('not-a-jwt')).toBeNull();
72
+ expect(outsideAccountOf('')).toBeNull();
73
+ });
74
+ });
@@ -0,0 +1,473 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { MemoryRouter } from 'react-router-dom';
5
+ import { AppRegistryContext, type AppRegistry } from '../../../core/registry';
6
+ import type { EmbedFileView } from '../services/embed.api';
7
+ import { EMBED_EXPIRED } from '../embed-host';
8
+
9
+ /**
10
+ * The HTTP surface, stubbed. The error CLASS is hoisted with the rest: the
11
+ * view tells an expired token from any other failure by `status`, so the
12
+ * class the view does `instanceof` against has to be the one the stub
13
+ * throws — and a `vi.mock` factory is hoisted above every declaration in the
14
+ * file, so a class declared below it would not exist yet.
15
+ */
16
+ const api = vi.hoisted(() => {
17
+ class FakeEmbedApiError extends Error {
18
+ readonly status: number;
19
+ constructor(status: number, message: string) {
20
+ super(message);
21
+ this.name = 'EmbedApiError';
22
+ this.status = status;
23
+ }
24
+ }
25
+ return {
26
+ EmbedApiError: FakeEmbedApiError,
27
+ loadEmbed: vi.fn(),
28
+ lockEmbed: vi.fn(),
29
+ heartbeatEmbed: vi.fn(),
30
+ cancelEmbed: vi.fn(),
31
+ saveEmbed: vi.fn(),
32
+ proposeEmbed: vi.fn(),
33
+ embedRawUrl: vi.fn(
34
+ (token: string, path?: string) => `/api/embed/raw?token=${token}${path ? `&path=${path}` : ''}`,
35
+ ),
36
+ };
37
+ });
38
+ vi.mock('../services/embed.api', () => api);
39
+ const { EmbedApiError: FakeEmbedApiError } = api;
40
+
41
+ import { EmbedView } from '../components/EmbedView';
42
+
43
+ const KB = 'knowledge-base';
44
+ const PAGE = '# Thing\n\nWhat it is.\n';
45
+
46
+ function view(overrides: Partial<EmbedFileView> = {}): EmbedFileView {
47
+ return {
48
+ nodeName: 'Thing',
49
+ repoRelative: 'Data/Thing.md',
50
+ workspacePath: `${KB}/Data/Thing.md`,
51
+ kbDirName: KB,
52
+ branch: 'main',
53
+ appUrl: 'https://hexis.example/workspace/main/knowledge-base/Data/Thing.md',
54
+ content: PAGE,
55
+ contentIsText: true,
56
+ linked: true,
57
+ canRead: true,
58
+ canWrite: true,
59
+ linkUrl: 'https://hexis.example/embed/link?token=tok',
60
+ ...overrides,
61
+ };
62
+ }
63
+
64
+ const EMPTY_REGISTRY = {
65
+ apps: [],
66
+ panes: [],
67
+ topLevelRoutes: [],
68
+ viewerRoutes: [],
69
+ renderers: [],
70
+ banners: [],
71
+ fileViewerPanels: [],
72
+ adminMenuItems: [],
73
+ explorerItems: [],
74
+ folderMenuItems: [],
75
+ settingsNavItems: [],
76
+ } as unknown as AppRegistry;
77
+
78
+ function mount(registry: AppRegistry = EMPTY_REGISTRY) {
79
+ return render(
80
+ <AppRegistryContext.Provider value={registry}>
81
+ <MemoryRouter>
82
+ <EmbedView />
83
+ </MemoryRouter>
84
+ </AppRegistryContext.Provider>,
85
+ );
86
+ }
87
+
88
+ beforeEach(() => {
89
+ for (const fn of Object.values(api)) (fn as { mockReset?: () => void }).mockReset?.();
90
+ api.embedRawUrl.mockImplementation(
91
+ (token: string, path?: string) => `/api/embed/raw?token=${token}${path ? `&path=${path}` : ''}`,
92
+ );
93
+ // The lock is let go on the way out too (unmount), so a test that ends
94
+ // mid-edit sees a cancel it never arranged — answered, like the real call.
95
+ api.cancelEmbed.mockResolvedValue(undefined);
96
+ window.history.replaceState({}, '', '/embed?token=tok');
97
+ });
98
+
99
+ afterEach(() => {
100
+ // Unmount BEFORE the mocks are restored: the view lets go of a held lock
101
+ // on its way out, and that call must still meet the stubbed API.
102
+ cleanup();
103
+ vi.restoreAllMocks();
104
+ });
105
+
106
+ describe('a view with no usable token', () => {
107
+ /**
108
+ * The one state that shows NO content, ever — and it must be reachable
109
+ * without a request, because a view opened with no token at all has
110
+ * nothing to ask.
111
+ */
112
+ it('says it expired, asks nothing, and shows no content when the token is absent', async () => {
113
+ window.history.replaceState({}, '', '/embed');
114
+ mount();
115
+ expect(await screen.findByText(EMBED_EXPIRED)).toBeTruthy();
116
+ expect(api.loadEmbed).not.toHaveBeenCalled();
117
+ expect(screen.queryByText(/What it is/)).toBeNull();
118
+ });
119
+
120
+ it('says it expired when the token is rejected, and shows no content', async () => {
121
+ api.loadEmbed.mockRejectedValue(new FakeEmbedApiError(401, 'Invalid or expired embed token'));
122
+ mount();
123
+ expect(await screen.findByText(EMBED_EXPIRED)).toBeTruthy();
124
+ expect(screen.queryByText(/What it is/)).toBeNull();
125
+ // Not the Edit control either: there is no page to edit.
126
+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
127
+ });
128
+
129
+ it('does NOT claim expiry for a failure that is not about the token', async () => {
130
+ api.loadEmbed.mockRejectedValue(new FakeEmbedApiError(500, 'Something went wrong.'));
131
+ mount();
132
+ expect(await screen.findByRole('alert')).toHaveProperty('textContent', 'Something went wrong.');
133
+ expect(screen.queryByText(EMBED_EXPIRED)).toBeNull();
134
+ });
135
+ });
136
+
137
+ describe('a writer', () => {
138
+ it('sees Edit, and saving writes the page', async () => {
139
+ api.loadEmbed.mockResolvedValue(view());
140
+ api.lockEmbed.mockResolvedValue({ acquired: true });
141
+ api.saveEmbed.mockResolvedValue(undefined);
142
+ mount();
143
+
144
+ const edit = await screen.findByRole('button', { name: 'Edit' });
145
+ expect(screen.queryByRole('button', { name: 'Propose changes' })).toBeNull();
146
+ await userEvent.click(edit);
147
+
148
+ await waitFor(() => expect(api.lockEmbed).toHaveBeenCalledWith('tok'));
149
+ const save = await screen.findByRole('button', { name: 'Save' });
150
+ await userEvent.click(save);
151
+ await waitFor(() => expect(api.saveEmbed).toHaveBeenCalledWith('tok', PAGE));
152
+ // A save goes to the default branch; it is never a proposal.
153
+ expect(api.proposeEmbed).not.toHaveBeenCalled();
154
+ });
155
+
156
+ it('says who holds the lock rather than opening an editor', async () => {
157
+ api.loadEmbed.mockResolvedValue(view());
158
+ api.lockEmbed.mockResolvedValue({ acquired: false, holderName: 'Bob' });
159
+ mount();
160
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit' }));
161
+ expect(await screen.findByRole('alert')).toHaveProperty(
162
+ 'textContent',
163
+ 'Bob is editing this page — try again shortly.',
164
+ );
165
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull();
166
+ });
167
+
168
+ /**
169
+ * Hidden is not closed. The lock is let go while the frame is hidden — and
170
+ * taken AGAIN when it comes back, before Save can mean anything. Somebody
171
+ * who took it meanwhile keeps it, and Save is refused.
172
+ */
173
+ it('takes the lock again after a tab switch, and refuses Save if someone else took it', async () => {
174
+ api.loadEmbed.mockResolvedValue(view());
175
+ api.lockEmbed.mockResolvedValueOnce({ acquired: true });
176
+ api.cancelEmbed.mockResolvedValue(undefined);
177
+ mount();
178
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit' }));
179
+ await screen.findByRole('button', { name: 'Save' });
180
+
181
+ const setVisibility = (state: 'hidden' | 'visible') => {
182
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });
183
+ document.dispatchEvent(new Event('visibilitychange'));
184
+ };
185
+ setVisibility('hidden');
186
+ await waitFor(() => expect(api.cancelEmbed).toHaveBeenCalledWith('tok'));
187
+ api.lockEmbed.mockResolvedValueOnce({ acquired: false, holderName: 'Bob' });
188
+ setVisibility('visible');
189
+
190
+ await waitFor(() => expect(api.lockEmbed).toHaveBeenCalledTimes(2));
191
+ expect(await screen.findByText(/Bob started editing this page/)).toBeTruthy();
192
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
193
+ expect(api.saveEmbed).not.toHaveBeenCalled();
194
+ });
195
+
196
+ it('keeps Save when the lock is taken back cleanly', async () => {
197
+ api.loadEmbed.mockResolvedValue(view());
198
+ api.lockEmbed.mockResolvedValue({ acquired: true });
199
+ api.cancelEmbed.mockResolvedValue(undefined);
200
+ mount();
201
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit' }));
202
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
203
+ document.dispatchEvent(new Event('visibilitychange'));
204
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
205
+ document.dispatchEvent(new Event('visibilitychange'));
206
+ await waitFor(() => expect(api.lockEmbed).toHaveBeenCalledTimes(2));
207
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
208
+ });
209
+
210
+ /**
211
+ * Write access withdrawn mid-edit: the heartbeat answers 403. The editor
212
+ * stays open with the draft, Save becomes Send proposal, and the reader is
213
+ * told why — never an editor that quietly stopped saving.
214
+ */
215
+ /** Heartbeats captured instead of scheduled, so a test can fire one. */
216
+ function captureHeartbeats(): Array<() => void> {
217
+ const ticks: Array<() => void> = [];
218
+ const realSetInterval = window.setInterval.bind(window);
219
+ vi.spyOn(window, 'setInterval').mockImplementation(((fn: () => void, ms?: number) => {
220
+ if (ms === 30_000) {
221
+ ticks.push(fn);
222
+ return 0;
223
+ }
224
+ return realSetInterval(fn, ms);
225
+ }) as typeof window.setInterval);
226
+ return ticks;
227
+ }
228
+
229
+ const EDITED = '# Thing\n\nWhat it is, edited.\n';
230
+
231
+ async function editThenLoseWrite() {
232
+ const ticks = captureHeartbeats();
233
+ api.loadEmbed.mockResolvedValueOnce(view());
234
+ api.lockEmbed.mockResolvedValue({ acquired: true });
235
+ api.cancelEmbed.mockResolvedValue(undefined);
236
+ api.heartbeatEmbed.mockRejectedValue(new FakeEmbedApiError(403, 'Forbidden'));
237
+ api.proposeEmbed.mockResolvedValue({ url: 'https://hexis.example/change-requests/3' });
238
+ mount();
239
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit' }));
240
+ await screen.findByRole('button', { name: 'Save' });
241
+ // The draft differs from the page, so a reload that dropped it would show.
242
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: EDITED } });
243
+ return ticks;
244
+ }
245
+
246
+ /**
247
+ * Write access withdrawn mid-edit: the heartbeat answers 403. The editor
248
+ * stays open with the draft, Save becomes Send proposal, and the reader is
249
+ * told why — never an editor that quietly stopped saving.
250
+ */
251
+ it('turns Save into Send proposal, keeping the draft, when a heartbeat finds write access withdrawn', async () => {
252
+ const ticks = await editThenLoseWrite();
253
+ api.loadEmbed.mockResolvedValueOnce(view({ canWrite: false }));
254
+ ticks.at(-1)!();
255
+
256
+ expect(await screen.findByText(/You can no longer edit this page directly/)).toBeTruthy();
257
+ // A proposal takes no lock, so the edit lock is released straight away.
258
+ expect(api.cancelEmbed).toHaveBeenCalledWith('tok');
259
+ const send = await screen.findByRole('button', { name: 'Send proposal' });
260
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(EDITED);
261
+ await userEvent.click(send);
262
+ await waitFor(() => expect(api.proposeEmbed).toHaveBeenCalledWith('tok', EDITED));
263
+ expect(api.saveEmbed).not.toHaveBeenCalled();
264
+ });
265
+
266
+ /**
267
+ * The same 403 when READ access went too. The no-access screen would strand
268
+ * the draft, so the editor stays on it with nothing sendable, and says why;
269
+ * Discard then lands on what the reader may now see.
270
+ */
271
+ it('keeps the draft on screen but sends nothing when a heartbeat finds read access withdrawn', async () => {
272
+ const ticks = await editThenLoseWrite();
273
+ api.loadEmbed.mockResolvedValue(view({ canRead: false, canWrite: false }));
274
+ ticks.at(-1)!();
275
+
276
+ expect(await screen.findByText(/You no longer have access to this page/)).toBeTruthy();
277
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(EDITED);
278
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
279
+ // The lock is let go at once, not left to block other writers until TTL.
280
+ expect(api.cancelEmbed).toHaveBeenCalledWith('tok');
281
+ api.cancelEmbed.mockClear();
282
+
283
+ await userEvent.click(screen.getByRole('button', { name: 'Discard' }));
284
+ // And Discard releases again regardless — a no-op if it is already free.
285
+ await waitFor(() => expect(api.cancelEmbed).toHaveBeenCalledWith('tok'));
286
+ expect(await screen.findByText(/You don.t have access to this page/)).toBeTruthy();
287
+ expect(screen.queryByText(/What it is/)).toBeNull();
288
+ expect(api.saveEmbed).not.toHaveBeenCalled();
289
+ expect(api.proposeEmbed).not.toHaveBeenCalled();
290
+ });
291
+
292
+ it('releases the lock on Discard', async () => {
293
+ api.loadEmbed.mockResolvedValue(view());
294
+ api.lockEmbed.mockResolvedValue({ acquired: true });
295
+ api.cancelEmbed.mockResolvedValue(undefined);
296
+ mount();
297
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit' }));
298
+ await userEvent.click(await screen.findByRole('button', { name: 'Discard' }));
299
+ await waitFor(() => expect(api.cancelEmbed).toHaveBeenCalledWith('tok'));
300
+ expect(await screen.findByRole('button', { name: 'Edit' })).toBeTruthy();
301
+ });
302
+ });
303
+
304
+ describe('a viewer without write access', () => {
305
+ /**
306
+ * NOT a "no access" notice where a control should be. The enterprise panel
307
+ * this replaced told such a reader they had no edit access and left them a
308
+ * link out; the rule now is that there is always something they can do.
309
+ */
310
+ it('sees Propose changes, and never a no-access notice', async () => {
311
+ api.loadEmbed.mockResolvedValue(view({ canWrite: false }));
312
+ mount();
313
+ expect(await screen.findByRole('button', { name: 'Propose changes' })).toBeTruthy();
314
+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
315
+ expect(screen.queryByText(/don't have edit access/i)).toBeNull();
316
+ expect(screen.queryByText(/no access/i)).toBeNull();
317
+ });
318
+
319
+ it('sends the proposal, takes no lock, and points at the change request', async () => {
320
+ api.loadEmbed.mockResolvedValue(view({ canWrite: false }));
321
+ api.proposeEmbed.mockResolvedValue({ branch: 'suggestions/a-1/knowledge', number: 7, url: '/change-requests/7' });
322
+ mount();
323
+ await userEvent.click(await screen.findByRole('button', { name: 'Propose changes' }));
324
+ // No round trip to open the editor: a proposal touches nothing on the
325
+ // default branch, so there is no lock to take.
326
+ expect(api.lockEmbed).not.toHaveBeenCalled();
327
+ await userEvent.click(await screen.findByRole('button', { name: 'Send proposal' }));
328
+ await waitFor(() => expect(api.proposeEmbed).toHaveBeenCalledWith('tok', PAGE));
329
+ expect(await screen.findByText(/sent for approval/i)).toBeTruthy();
330
+ expect(screen.getByRole('link', { name: 'Open the change request' })).toBeTruthy();
331
+ // And nothing landed on the default branch.
332
+ expect(api.saveEmbed).not.toHaveBeenCalled();
333
+ });
334
+ });
335
+
336
+ describe('a viewer who cannot read the page, or is not linked', () => {
337
+ it('is sent to sign in, with no content shown', async () => {
338
+ api.loadEmbed.mockResolvedValue(view({ linked: false, canRead: false, content: '' }));
339
+ mount();
340
+ expect(await screen.findByRole('link', { name: 'Link your account' })).toBeTruthy();
341
+ expect(screen.queryByText(/What it is/)).toBeNull();
342
+ });
343
+
344
+ it('is told to ask an owner, with no content shown', async () => {
345
+ api.loadEmbed.mockResolvedValue(view({ canRead: false, canWrite: false, content: '' }));
346
+ mount();
347
+ expect(await screen.findByText(/don't have access to this page/i)).toBeTruthy();
348
+ expect(screen.queryByText(/What it is/)).toBeNull();
349
+ });
350
+ });
351
+
352
+ describe('a file with no editing surface', () => {
353
+ /**
354
+ * An image, a PDF, a workbook: the app's file page offers no write action
355
+ * for these either, because there is no text behind the control. Nothing is
356
+ * implied about access.
357
+ */
358
+ it.each([
359
+ ['an image', 'Shots/x.png', false],
360
+ ['a PDF', 'Docs/x.pdf', false],
361
+ ['a Word document', 'Docs/x.docx', false],
362
+ ])('offers no write action for %s', async (_label, repo, contentIsText) => {
363
+ api.loadEmbed.mockResolvedValue(
364
+ view({ repoRelative: repo, workspacePath: `${KB}/${repo}`, content: '', contentIsText }),
365
+ );
366
+ mount();
367
+ await waitFor(() => expect(api.loadEmbed).toHaveBeenCalled());
368
+ await waitFor(() => expect(screen.queryByText('Thing')).toBeTruthy());
369
+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
370
+ expect(screen.queryByRole('button', { name: 'Propose changes' })).toBeNull();
371
+ });
372
+ });
373
+
374
+ describe('the renderer', () => {
375
+ /**
376
+ * The page is drawn by the APP's renderer for its type, through the same
377
+ * lookup the file page uses — so a renderer a deployment REGISTERS reaches
378
+ * the embed on the day it is added.
379
+ */
380
+ it('uses a deployment registered override when there is one', async () => {
381
+ api.loadEmbed.mockResolvedValue(
382
+ view({ repoRelative: 'Pages/Report.html', workspacePath: `${KB}/Pages/Report.html`, content: '<p>hi</p>' }),
383
+ );
384
+ const registry = {
385
+ ...EMPTY_REGISTRY,
386
+ renderers: [
387
+ {
388
+ extensions: ['.html', '.htm'],
389
+ Component: () => <div data-testid="enterprise-html">the enterprise renderer</div>,
390
+ },
391
+ ],
392
+ } as unknown as AppRegistry;
393
+ mount(registry);
394
+ expect(await screen.findByTestId('enterprise-html')).toBeTruthy();
395
+ });
396
+
397
+ it('falls back to the built-in renderer for the type when nothing is registered', async () => {
398
+ api.loadEmbed.mockResolvedValue(view());
399
+ mount();
400
+ // The markdown renderer's read view renders the heading as a heading.
401
+ expect(await screen.findByRole('heading', { name: 'Thing' })).toBeTruthy();
402
+ });
403
+
404
+ /**
405
+ * End to end for the link rule: the page the embed mounts must hand EVERY
406
+ * outgoing link to the host, never leave one as an anchor the sandbox will
407
+ * follow in place. An external link reaching the reader as
408
+ * `target="_blank"` is the shape that navigated the frame away on a real
409
+ * boot — `target` is ignored without `allow-popups`.
410
+ */
411
+ it('gives the app renderer the surface link policy, so no link navigates the frame', async () => {
412
+ api.loadEmbed.mockResolvedValue(
413
+ view({ content: '# Thing\n\n[docs](https://example.test/docs) and [other](Other.md)\n' }),
414
+ );
415
+ mount();
416
+ const external = await screen.findByRole('link', { name: 'docs' });
417
+ const internal = screen.getByRole('link', { name: 'other' });
418
+ expect(external.getAttribute('target')).toBeNull();
419
+ expect(internal.getAttribute('target')).toBeNull();
420
+
421
+ // And a click on either is HANDED OVER: the frame's own navigation is
422
+ // prevented, and the host path is what opens it (standalone, as here,
423
+ // that path is a new tab).
424
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
425
+ expect(fireEvent.click(external)).toBe(false);
426
+ expect(fireEvent.click(internal)).toBe(false);
427
+ expect(open.mock.calls.map((c) => c[0])).toEqual([
428
+ 'https://example.test/docs',
429
+ `${window.location.origin}/workspace/main/${KB}/Data/Other.md`,
430
+ ]);
431
+ expect(open.mock.calls.every((c) => c[1] === '_blank')).toBe(true);
432
+ });
433
+
434
+ /**
435
+ * A picture in a markdown page is fetched under the token from the
436
+ * repository root — the renderer hands the surface a WORKSPACE path, and
437
+ * sent as written the server resolved it beside the page a second time
438
+ * (`Data/knowledge-base/Data/shot.png`), so every image 404'd.
439
+ */
440
+ it('asks for a picture beside the page by its repository path', async () => {
441
+ api.loadEmbed.mockResolvedValue(view({ content: '# Thing\n\n![shot](shot.png)\n' }));
442
+ mount();
443
+ const img = await screen.findByRole('img', { name: 'shot' });
444
+ expect(img.getAttribute('src')).toBe('/api/embed/raw?token=tok&path=/Data/shot.png');
445
+ expect(api.embedRawUrl).toHaveBeenCalledWith('tok', '/Data/shot.png', expect.anything());
446
+ });
447
+
448
+ /**
449
+ * A heading's copy-link is the page's canonical address plus the heading.
450
+ * A view opened AT a heading carries that heading in its app address; the
451
+ * canonical address drops it, or every copied link would carry two.
452
+ */
453
+ it('copies a heading link from the page address without the heading the view opened at', async () => {
454
+ const writeText = vi.fn().mockResolvedValue(undefined);
455
+ // A stub `vi.restoreAllMocks` does not know about: removed by hand, so
456
+ // no later test in this file meets a clipboard this one left behind.
457
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
458
+ try {
459
+ api.loadEmbed.mockResolvedValue(
460
+ view({
461
+ appUrl: 'https://hexis.example/workspace/main/knowledge-base/Data/Thing.md#what-it-is',
462
+ heading: 'what-it-is',
463
+ }),
464
+ );
465
+ mount();
466
+ const btn = await screen.findByRole('button', { name: /copy link to this heading/i });
467
+ fireEvent.click(btn);
468
+ expect(writeText).toHaveBeenCalledWith('https://hexis.example/workspace/main/knowledge-base/Data/Thing.md#thing');
469
+ } finally {
470
+ Reflect.deleteProperty(navigator, 'clipboard');
471
+ }
472
+ });
473
+ });