@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,545 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useLocation, useNavigate } from 'react-router-dom';
3
+ import { Button } from '../../../shared/components';
4
+ import { useAppRegistry } from '../../../core/registry';
5
+ import { isViewOnlyFile, pickFileRenderer } from '../../workspace/components/renderers';
6
+ import { CanDownloadContext } from '../../workspace/components/renderers/DownloadFileButton';
7
+ import {
8
+ RendererSurfaceContext,
9
+ type RendererSurface,
10
+ } from '../../workspace/components/renderers/rendererSurface';
11
+ import { RendererWorkspaceContext } from '../../workspace/components/renderers/rendererWorkspace';
12
+ import {
13
+ cancelEmbed,
14
+ embedRawUrl,
15
+ EmbedApiError,
16
+ heartbeatEmbed,
17
+ loadEmbed,
18
+ lockEmbed,
19
+ proposeEmbed,
20
+ saveEmbed,
21
+ type EmbedFileView,
22
+ } from '../services/embed.api';
23
+ import { EMBED_EXPIRED, openThroughHost } from '../embed-host';
24
+ import { embedBaseUrl, embedToken } from '../embed-config';
25
+ import { kbFileUrl } from '../../workspace/routing/kb-routes';
26
+
27
+ /** How often a held lock is kept alive while somebody is editing. */
28
+ const HEARTBEAT_MS = 30_000;
29
+
30
+ /** Said when a save arrives while the lock is being taken again after a hidden tab. */
31
+ const REACQUIRING = 'Taking the edit lock again after the tab was hidden — try saving in a moment.';
32
+
33
+ /** Said when a heartbeat finds the viewer's write access withdrawn mid-edit. */
34
+ const WRITE_WITHDRAWN =
35
+ 'You can no longer edit this page directly. Your changes are still here — send them as a proposal instead.';
36
+
37
+ /** Said when a heartbeat finds the viewer's READ access withdrawn too. */
38
+ const READ_WITHDRAWN =
39
+ "You no longer have access to this page, so these changes can't be saved or proposed. " +
40
+ 'Copy anything you want to keep before you discard them.';
41
+
42
+ function lockLostMessage(holder: string): string {
43
+ return `${holder} started editing this page while it was in the background — your draft can't be saved over theirs.`;
44
+ }
45
+
46
+ /**
47
+ * An app path as an absolute URL on the deployment, so a host can open it
48
+ * cross-site — the deployment's address, not this document's, which inside a
49
+ * chat host's sandbox is the sandbox's own.
50
+ */
51
+ function absolute(pathOrUrl: string): string {
52
+ return /^https?:\/\//i.test(pathOrUrl) ? pathOrUrl : `${embedBaseUrl()}${pathOrUrl}`;
53
+ }
54
+
55
+ /**
56
+ * ONE knowledge-base page, rendered inside somebody else's frame — an MCP
57
+ * App's sandbox in a chat, an Atlassian issue panel.
58
+ *
59
+ * What it renders is the APP'S OWN renderer for the file's type: markdown
60
+ * through the markdown renderer, an HTML page through the sandboxed HTML one,
61
+ * a document, a workbook, a deck, an image, each through the viewer the file
62
+ * page uses. Not a second rendering path — a second one would have to be kept
63
+ * in step with the app's, and would be the one that is wrong. What makes that
64
+ * possible without the app around it is the renderer SURFACE (see
65
+ * `rendererSurface.ts`): the renderers ask their surroundings where bytes come
66
+ * from and what a link click does, and here both answers are the embed's.
67
+ *
68
+ * Who the reader is comes from the token and only the token. A viewer who may
69
+ * write the file on the default branch gets Edit, under the platform's file
70
+ * lock, writing to the default branch exactly as the file page does. A viewer
71
+ * who may not gets Propose changes, which lands a change request authored by
72
+ * them. Neither of them is ever shown a "no access" notice where a control
73
+ * should be: there is always something they can do.
74
+ */
75
+ /**
76
+ * A workspace path, as every renderer hands the surface one, in the form the
77
+ * embed's raw route reads: omitted for the embedded file itself, and
78
+ * `/<repo-relative>` for any other file — the leading slash is what makes the
79
+ * server take it from the repository root rather than beside the page. Sending
80
+ * the workspace path as written made the server look for
81
+ * `<page folder>/<kbDir>/<page folder>/shot.png`, and every picture 404'd.
82
+ *
83
+ * A path outside the knowledge-base folder has no file in the repository; it
84
+ * goes as `/..`, which the server refuses as outside the knowledge base.
85
+ */
86
+ function embedRawPath(
87
+ path: string,
88
+ view: Pick<EmbedFileView, 'workspacePath' | 'kbDirName'>,
89
+ ): string | undefined {
90
+ if (path === view.workspacePath) return undefined;
91
+ const prefix = `${view.kbDirName}/`;
92
+ return path.startsWith(prefix) ? `/${path.slice(prefix.length)}` : '/..';
93
+ }
94
+
95
+ export function EmbedView() {
96
+ // Handed over by the MCP App view that mounted this, or read from the
97
+ // page URL on the SPA's `/embed` route — see `embed-config`.
98
+ const token = embedToken();
99
+ const registry = useAppRegistry();
100
+ const [view, setView] = useState<EmbedFileView | null>(null);
101
+ /** An expired/absent/rejected token — the one state that shows no content. */
102
+ const [expired, setExpired] = useState(!token);
103
+ const [loadError, setLoadError] = useState<string | null>(null);
104
+ const [mode, setMode] = useState<'read' | 'write'>('read');
105
+ const [draft, setDraft] = useState('');
106
+ const [notice, setNotice] = useState<string | null>(null);
107
+ const [sent, setSent] = useState<{ url?: string } | null>(null);
108
+ const [busy, setBusy] = useState(false);
109
+ const [awaitingLink, setAwaitingLink] = useState(false);
110
+ /** Who took the lock while this frame was hidden — null while we hold it. */
111
+ const [lockLost, setLockLost] = useState<string | null>(null);
112
+ /** The frame is hidden: the lock was let go, and the heartbeat has nothing to keep alive. */
113
+ const [hidden, setHidden] = useState(false);
114
+ /** Back from hidden, the lock is being taken again: Save waits for the answer. */
115
+ const [reacquiring, setReacquiring] = useState(false);
116
+ // Read access withdrawn mid-edit. The editor stays open on the draft so
117
+ // nothing typed vanishes, but nothing can be sent from it.
118
+ const [accessLost, setAccessLost] = useState(false);
119
+
120
+ const reload = useCallback(() => {
121
+ if (!token) {
122
+ setExpired(true);
123
+ return;
124
+ }
125
+ setNotice(null);
126
+ loadEmbed(token)
127
+ .then((next) => {
128
+ setView(next);
129
+ setExpired(false);
130
+ setLoadError(null);
131
+ setMode('read');
132
+ setLockLost(null);
133
+ setAccessLost(false);
134
+ setSent(null);
135
+ if (next.linked) setAwaitingLink(false);
136
+ })
137
+ .catch((err: unknown) => {
138
+ // 401 is the token: absent, malformed, or past its hour. That is
139
+ // the expired view — a plain sentence and NO content, ever.
140
+ if (err instanceof EmbedApiError && err.status === 401) {
141
+ setExpired(true);
142
+ setView(null);
143
+ return;
144
+ }
145
+ setLoadError(err instanceof Error ? err.message : 'This page could not be loaded.');
146
+ });
147
+ }, [token]);
148
+
149
+ useEffect(() => reload(), [reload]);
150
+
151
+ // The heading the agent named opens the view there: the renderer's deep
152
+ // link reads the location's hash, and the embed's own address carries
153
+ // none — so the heading is put there, once, before that effect runs.
154
+ const location = useLocation();
155
+ const navigate = useNavigate();
156
+ const heading = view?.heading;
157
+ useEffect(() => {
158
+ if (!heading || location.hash) return;
159
+ navigate({ search: location.search, hash: `#${encodeURIComponent(heading)}` }, { replace: true });
160
+ }, [heading, location.hash, location.search, navigate]);
161
+
162
+ // Keep the held lock alive while somebody is editing. Not while proposing:
163
+ // a proposal takes no lock, because nothing it does touches the default
164
+ // branch.
165
+ //
166
+ // A heartbeat refused with 403 means access was withdrawn mid-edit. The page
167
+ // is read again to learn how much: with read access left it now offers a
168
+ // proposal, not a save; with none, the view is NOT swapped for the
169
+ // no-access screen — the editor keeps the draft on screen, nothing can be
170
+ // sent, and the reader is told why. Either way the edits are not lost. Any
171
+ // other failure is left to the lock's TTL and to Save, which refuses with
172
+ // its own reason.
173
+ const holdsLock = mode === 'write' && (view?.canWrite ?? false) && !accessLost;
174
+ useEffect(() => {
175
+ // Nothing to keep alive while the frame is hidden: the lock was let go on
176
+ // the way out, and a heartbeat now would only renew somebody else's.
177
+ if (!holdsLock || hidden) return;
178
+ const id = window.setInterval(() => {
179
+ heartbeatEmbed(token).catch((err: unknown) => {
180
+ if (!(err instanceof EmbedApiError && err.status === 403)) return;
181
+ // The edit lock goes NOW, whichever access went: nothing from this
182
+ // editor can be saved any more, and holding it would block every
183
+ // other writer until the TTL. Releasing needs no access — the
184
+ // server lets go only of a lock this identity holds.
185
+ cancelEmbed(token).catch(() => undefined);
186
+ loadEmbed(token)
187
+ .then((next) => {
188
+ if (!next.linked || !next.canRead) {
189
+ setAccessLost(true);
190
+ setNotice(READ_WITHDRAWN);
191
+ return;
192
+ }
193
+ setNotice(WRITE_WITHDRAWN);
194
+ setView(next);
195
+ })
196
+ .catch((loadErr: unknown) => {
197
+ // A 401 here is the token running out, which Save reports anyway.
198
+ setNotice(loadErr instanceof Error ? loadErr.message : 'Your access to this page changed.');
199
+ });
200
+ });
201
+ }, HEARTBEAT_MS);
202
+ return () => window.clearInterval(id);
203
+ }, [holdsLock, hidden, token]);
204
+
205
+ // Best-effort lock release when the frame is hidden or closed mid-edit. The
206
+ // server's lock TTL plus the heartbeat above is the real backstop — a
207
+ // cross-origin iframe cannot promise an unload signal fires.
208
+ //
209
+ // Hidden is not closed: a reader who switches tabs comes back to the same
210
+ // open editor. So on the way back the lock is TAKEN AGAIN before Save can
211
+ // mean anything — and if somebody else took it meanwhile, the reader is
212
+ // told so and Save is refused (the server refuses it too: it saves only
213
+ // under a lock this reader holds).
214
+ const holdsLockRef = useRef(holdsLock);
215
+ useEffect(() => {
216
+ holdsLockRef.current = holdsLock;
217
+ }, [holdsLock]);
218
+ useEffect(() => {
219
+ const release = () => {
220
+ if (holdsLockRef.current) cancelEmbed(token).catch(() => undefined);
221
+ };
222
+ const onVisibility = () => {
223
+ if (document.visibilityState === 'hidden') {
224
+ setHidden(true);
225
+ release();
226
+ return;
227
+ }
228
+ setHidden(false);
229
+ if (!holdsLockRef.current) return;
230
+ // Until the lock is held again, Save is refused here rather than by
231
+ // the server: the editor is on screen, but the claim behind it is not.
232
+ setReacquiring(true);
233
+ lockEmbed(token)
234
+ .then((result) => {
235
+ setLockLost(result.acquired ? null : (result.holderName ?? 'Someone else'));
236
+ })
237
+ .catch(() => setLockLost('Someone else'))
238
+ .finally(() => setReacquiring(false));
239
+ };
240
+ window.addEventListener('pagehide', release);
241
+ document.addEventListener('visibilitychange', onVisibility);
242
+ return () => {
243
+ window.removeEventListener('pagehide', release);
244
+ document.removeEventListener('visibilitychange', onVisibility);
245
+ // Taken down mid-edit — a chat view replaced by another mount, a
246
+ // route left — the lock goes with it, rather than shutting the file
247
+ // to other writers until the TTL. Nothing the page did fires for a
248
+ // React unmount, so this is where it has to happen.
249
+ release();
250
+ };
251
+ }, [token]);
252
+
253
+ /**
254
+ * The surface the app's renderers are mounted on. Rebuilt only when the
255
+ * page changes: the renderers take it as a context, and a fresh object per
256
+ * render would re-run every read effect that depends on it.
257
+ */
258
+ const surface = useMemo<RendererSurface | null>(() => {
259
+ if (!view) return null;
260
+ const open = (href: string, basePath: string) =>
261
+ openThroughHost(href, basePath, { kbDirName: view.kbDirName, branch: view.branch });
262
+ return {
263
+ kbDirName: view.kbDirName,
264
+ openLink: open,
265
+ // A path from a tree, verbatim — never through the link grammar, which
266
+ // would read a `#` in a file name as an anchor.
267
+ openWorkspacePath: (path) => openThroughHost(absolute(kbFileUrl(view.branch, path)), '', null),
268
+ // A node id is handed to the host as the app's own copy-link address;
269
+ // the app resolves it with the reader's session, which is the only
270
+ // place that resolution can be done.
271
+ openNodeId: (idOrLink) => open(`/workspace/${encodeURIComponent(view.branch)}/${idOrLink}`, ''),
272
+ // The page's address without the heading the view opened at: a heading
273
+ // link appends its own fragment, and two fragments is no address.
274
+ canonicalUrlFor: () => absolute(view.appUrl).split('#', 1)[0],
275
+ rawUrl: (path, options) => embedRawUrl(token, embedRawPath(path, view), options),
276
+ rawFetch: (path, options) =>
277
+ fetch(embedRawUrl(token, embedRawPath(path, view), options), {
278
+ credentials: 'omit',
279
+ signal: options?.signal,
280
+ }),
281
+ // No download route under the token: `download:` is its own verb, which
282
+ // the embed has nothing to resolve it with.
283
+ offersDownload: false,
284
+ };
285
+ }, [view, token]);
286
+
287
+ /**
288
+ * The workspace the renderers believe they are reading from. Never dialled:
289
+ * every byte comes through the surface above. It is here because
290
+ * `useRendererWorkspaceId` has to ANSWER rather than throw, and the honest
291
+ * answer is the default branch — the branch the embed renders.
292
+ */
293
+ const rendererWorkspace = useMemo(
294
+ () => ({ workspaceId: view ? encodeURIComponent(view.branch) : null }),
295
+ [view],
296
+ );
297
+
298
+ const onEdit = useCallback(async () => {
299
+ if (!view) return;
300
+ setBusy(true);
301
+ setNotice(null);
302
+ try {
303
+ const result = await lockEmbed(token);
304
+ if (!result.acquired) {
305
+ setNotice(`${result.holderName ?? 'Someone else'} is editing this page — try again shortly.`);
306
+ return;
307
+ }
308
+ setDraft(view.content);
309
+ setLockLost(null);
310
+ setMode('write');
311
+ } catch (err) {
312
+ setNotice(err instanceof Error ? err.message : 'Could not start editing.');
313
+ } finally {
314
+ setBusy(false);
315
+ }
316
+ }, [view, token]);
317
+
318
+ const onPropose = useCallback(() => {
319
+ if (!view) return;
320
+ // No lock, no round trip: a proposal touches nothing on the default
321
+ // branch, so the editor can open on the spot.
322
+ setNotice(null);
323
+ setDraft(view.content);
324
+ setMode('write');
325
+ }, [view]);
326
+
327
+ const onSave = useCallback(
328
+ async (content: string) => {
329
+ if (!view) return;
330
+ // Already on screen beside the editor; the refusal is for the
331
+ // renderer's own save shortcut, which does not see the disabled button.
332
+ if (accessLost) throw new Error(READ_WITHDRAWN);
333
+ if (view.canWrite && lockLost) throw new Error(lockLostMessage(lockLost));
334
+ // Back from a hidden tab, the lock is being taken again: a save sent
335
+ // now would race the answer, and the server would refuse it anyway.
336
+ if (view.canWrite && reacquiring) throw new Error(REACQUIRING);
337
+ setBusy(true);
338
+ setNotice(null);
339
+ try {
340
+ if (view.canWrite) {
341
+ await saveEmbed(token, content);
342
+ reload();
343
+ } else {
344
+ const result = await proposeEmbed(token, content);
345
+ setSent({ url: result.url });
346
+ setMode('read');
347
+ }
348
+ } catch (err) {
349
+ setNotice(err instanceof Error ? err.message : 'That could not be saved.');
350
+ throw err;
351
+ } finally {
352
+ setBusy(false);
353
+ }
354
+ },
355
+ [view, token, reload, lockLost, accessLost, reacquiring],
356
+ );
357
+
358
+ const onCancel = useCallback(async () => {
359
+ setBusy(true);
360
+ try {
361
+ // Released even after access was withdrawn (see the heartbeat above):
362
+ // a second release is a no-op, a skipped one blocks other writers.
363
+ if (view?.canWrite) await cancelEmbed(token).catch(() => undefined);
364
+ } finally {
365
+ setBusy(false);
366
+ setMode('read');
367
+ setLockLost(null);
368
+ setNotice(null);
369
+ // The view on screen predates the withdrawal; read it again so the
370
+ // reader lands on what they may now see, not on the old content.
371
+ if (accessLost) reload();
372
+ }
373
+ }, [view, token, accessLost, reload]);
374
+
375
+ // ── the states that show no content ──────────────────────────────────────
376
+
377
+ if (expired) {
378
+ return (
379
+ <EmbedNotice>
380
+ {EMBED_EXPIRED}
381
+ </EmbedNotice>
382
+ );
383
+ }
384
+ if (loadError) return <EmbedNotice tone="danger">{loadError}</EmbedNotice>;
385
+ if (!view || !surface) return <EmbedNotice>Opening this page…</EmbedNotice>;
386
+ if (!view.linked) {
387
+ return (
388
+ <EmbedNotice>
389
+ Sign in to see this page.{' '}
390
+ <EmbedLink href={view.linkUrl} onOpen={() => setAwaitingLink(true)}>
391
+ Link your account
392
+ </EmbedLink>
393
+ {awaitingLink && (
394
+ <span className="mt-2 block">
395
+ <Button variant="outline" size="tiny" onClick={reload}>
396
+ I&apos;ve signed in — reload
397
+ </Button>
398
+ </span>
399
+ )}
400
+ </EmbedNotice>
401
+ );
402
+ }
403
+ if (!view.canRead) {
404
+ return (
405
+ <EmbedNotice>
406
+ You don&apos;t have access to this page.{' '}
407
+ <EmbedLink href={view.appUrl}>Open the knowledge base</EmbedLink> to ask an owner for it.
408
+ </EmbedNotice>
409
+ );
410
+ }
411
+
412
+ // ── the page ─────────────────────────────────────────────────────────────
413
+
414
+ // The app's renderer for this file's type, through the SAME lookup the file
415
+ // page uses — a deployment's registered override first, the built-in map
416
+ // after — so a renderer the enterprise contributes reaches the embed on the
417
+ // day it is added.
418
+ const Renderer = pickFileRenderer(view.workspacePath, registry.renderers);
419
+ // A file with no editing surface behind the control — an image, a PDF, a
420
+ // workbook — offers no write action, exactly as the file page offers none.
421
+ // Nothing is implied about access; there is simply no text to change.
422
+ const viewOnly = isViewOnlyFile(view.workspacePath) || !view.contentIsText;
423
+ const writing = mode === 'write';
424
+
425
+ return (
426
+ <div className="flex h-full min-w-0 flex-col gap-2 p-3">
427
+ <div className="flex min-w-0 shrink-0 items-center gap-2">
428
+ <span className="min-w-0 flex-1 truncate text-detail font-semibold text-ink">
429
+ {view.nodeName}
430
+ </span>
431
+ {!viewOnly &&
432
+ (writing ? (
433
+ <>
434
+ <Button variant="quiet" size="tiny" onClick={() => void onCancel()} disabled={busy}>
435
+ Discard
436
+ </Button>
437
+ <Button
438
+ variant="primary"
439
+ size="tiny"
440
+ onClick={() => void onSave(draft).catch(() => undefined)}
441
+ disabled={busy || accessLost || (view.canWrite && lockLost !== null)}
442
+ >
443
+ {busy ? 'Sending…' : view.canWrite ? 'Save' : 'Send proposal'}
444
+ </Button>
445
+ </>
446
+ ) : view.canWrite ? (
447
+ <Button variant="outline" size="tiny" onClick={() => void onEdit()} disabled={busy}>
448
+ {busy ? 'Loading…' : 'Edit'}
449
+ </Button>
450
+ ) : (
451
+ <Button
452
+ variant="outline"
453
+ size="tiny"
454
+ onClick={onPropose}
455
+ disabled={busy}
456
+ title="You can't edit this page directly. Propose a change for its owners to approve"
457
+ >
458
+ Propose changes
459
+ </Button>
460
+ ))}
461
+ </div>
462
+
463
+ {writing && view.canWrite && lockLost && (
464
+ <p role="alert" className="shrink-0 text-detail text-danger">
465
+ {lockLostMessage(lockLost)}
466
+ </p>
467
+ )}
468
+ {notice && (
469
+ <p role="alert" className="shrink-0 text-detail text-danger">
470
+ {notice}
471
+ </p>
472
+ )}
473
+ {sent && (
474
+ <p className="shrink-0 text-detail text-ink-muted">
475
+ Your proposal was sent for approval.{' '}
476
+ {sent.url && <EmbedLink href={sent.url}>Open the change request</EmbedLink>}
477
+ </p>
478
+ )}
479
+
480
+ <div className="min-h-0 min-w-0 flex-1 overflow-auto">
481
+ <RendererSurfaceContext.Provider value={surface}>
482
+ {/* The renderers read bytes through the surface above, so the
483
+ workspace id here is never dialled — it is the default branch's,
484
+ which is the branch the embed renders, and it keeps
485
+ `useRendererWorkspaceId` answering rather than throwing. */}
486
+ <RendererWorkspaceContext.Provider value={rendererWorkspace}>
487
+ <CanDownloadContext.Provider value={false}>
488
+ <Renderer
489
+ content={writing ? draft : view.content}
490
+ savedContent={view.content}
491
+ filePath={view.workspacePath}
492
+ onSave={onSave}
493
+ onValueChange={writing ? setDraft : undefined}
494
+ readOnly={!writing}
495
+ />
496
+ </CanDownloadContext.Provider>
497
+ </RendererWorkspaceContext.Provider>
498
+ </RendererSurfaceContext.Provider>
499
+ </div>
500
+ </div>
501
+ );
502
+ }
503
+
504
+ /** A plain sentence, which is all some states have to say. */
505
+ function EmbedNotice({
506
+ children,
507
+ tone = 'muted',
508
+ }: {
509
+ children: React.ReactNode;
510
+ tone?: 'muted' | 'danger';
511
+ }) {
512
+ return (
513
+ <p
514
+ className={`p-3 text-detail ${tone === 'danger' ? 'text-danger' : 'text-ink-muted'}`}
515
+ {...(tone === 'danger' ? { role: 'alert' } : {})}
516
+ >
517
+ {children}
518
+ </p>
519
+ );
520
+ }
521
+
522
+ /** A link out of the embed: always a new tab, through the host. */
523
+ function EmbedLink({
524
+ href,
525
+ onOpen,
526
+ children,
527
+ }: {
528
+ href: string;
529
+ onOpen?: () => void;
530
+ children: React.ReactNode;
531
+ }) {
532
+ return (
533
+ <a
534
+ className="cursor-pointer text-accent underline"
535
+ href={absolute(href)}
536
+ onClick={(event) => {
537
+ event.preventDefault();
538
+ openThroughHost(absolute(href), '', null);
539
+ onOpen?.();
540
+ }}
541
+ >
542
+ {children}
543
+ </a>
544
+ );
545
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Where the embed is RUNNING, and what it was handed to run with.
3
+ *
4
+ * The embed's components run on two surfaces that answer three questions
5
+ * differently — where the API is, which token this is, and how a link gets
6
+ * out:
7
+ *
8
+ * - The SPA's `/embed` page, inside a frame of a host that may frame it (an
9
+ * Atlassian issue panel, a developer's own tab). The token is in this
10
+ * page's URL, the API is this page's own origin, and a link out goes to
11
+ * the parent window, or to a new tab when there is no parent.
12
+ * - The MCP App view's sandbox in a chat. No frame to the deployment is
13
+ * allowed there — Claude pins the sandbox's `frame-src` to `'self'` and
14
+ * drops the `frameDomains` a view declares — so the view loads the
15
+ * deployment's embed bundle into ITS OWN document, tells it the
16
+ * deployment's address and the token, and lends it the host's
17
+ * `ui/open-link`.
18
+ *
19
+ * This module is that handoff, in one place. The API client, the host
20
+ * bridge and the view read it; nothing else needs to know which surface it
21
+ * is on. Unconfigured, every answer is the SPA page's own, so the `/embed`
22
+ * route behaves exactly as it always has.
23
+ */
24
+
25
+ export interface EmbedRuntimeConfig {
26
+ /**
27
+ * The deployment's public address — origin plus the path prefix it is
28
+ * served under, if any (`https://hexis.example`,
29
+ * `https://hexis.example/hexis`), with no trailing slash — when the embed
30
+ * runs somewhere other than the deployment's own pages. Empty in the app,
31
+ * where every address is relative to the page.
32
+ */
33
+ baseUrl: string;
34
+ /** The embed token, when it was handed over; null means "read the page URL". */
35
+ token: string | null;
36
+ /** How a link leaves the view, when the host lent a way; null means parent window or a new tab. */
37
+ openLink: ((url: string) => void) | null;
38
+ }
39
+
40
+ const UNCONFIGURED: EmbedRuntimeConfig = { baseUrl: '', token: null, openLink: null };
41
+
42
+ let current: EmbedRuntimeConfig = UNCONFIGURED;
43
+
44
+ /** Hand the embed its runtime: called by {@link mountEmbed} before anything renders. */
45
+ export function configureEmbed(config: Partial<EmbedRuntimeConfig>): void {
46
+ current = { ...current, ...config };
47
+ }
48
+
49
+ /** Back to the SPA page's own answers — on unmount, and in tests. */
50
+ export function resetEmbedConfig(): void {
51
+ current = UNCONFIGURED;
52
+ }
53
+
54
+ /**
55
+ * Where this deployment is mounted, read from the page's own address when the
56
+ * embed was not handed a base: the path before `/embed` (or `/embed/link`).
57
+ * Empty for a deployment at the origin root; `/hexis` for one served under a
58
+ * prefix, whose API and app links must keep it.
59
+ */
60
+ function pagePrefix(): string {
61
+ return window.location.pathname.replace(/\/embed(?:\/link)?\/?$/, '').replace(/\/+$/, '');
62
+ }
63
+
64
+ /**
65
+ * The prefix every embed API path gets. The deployment's address when the
66
+ * embed runs elsewhere; in the app, the deployment's mount prefix (usually
67
+ * empty), so a relative address stays on this page's own origin and path.
68
+ */
69
+ export function embedApiBase(): string {
70
+ return current.baseUrl || pagePrefix();
71
+ }
72
+
73
+ /** The deployment's address, for the absolute app links a host opens. */
74
+ export function embedBaseUrl(): string {
75
+ return current.baseUrl || `${window.location.origin}${pagePrefix()}`;
76
+ }
77
+
78
+ /** The token this view was minted with: handed over, or read from the page URL. */
79
+ export function embedToken(): string {
80
+ return current.token ?? new URLSearchParams(window.location.search).get('token') ?? '';
81
+ }
82
+
83
+ /** The host's way of opening a link, when it lent one. */
84
+ export function embedOpenLink(): ((url: string) => void) | null {
85
+ return current.openLink;
86
+ }
87
+
88
+ /**
89
+ * The global the MCP App view sets on its window before it loads the
90
+ * deployment's embed bundle — the one contract between the view (a static
91
+ * page shipped by core-backend) and the bundle (built by the deployment's
92
+ * web app). The view writes it; {@link readEmbedHandoff} reads it.
93
+ */
94
+ export const EMBED_HANDOFF_GLOBAL = '__HEXIS_EMBED__';
95
+
96
+ /** What the view hands the bundle. */
97
+ export interface EmbedHandoff {
98
+ /** The deployment's address, prefix included: where the API is and where app links point. */
99
+ baseUrl: string;
100
+ /** The embed token `open_page` minted. */
101
+ token: string;
102
+ /** Opens an address in a new tab through the host (`ui/open-link`). */
103
+ openLink?: (url: string) => void;
104
+ }
105
+
106
+ /**
107
+ * The handoff the view left on the window, or null when this bundle was not
108
+ * loaded by the view (a developer opening the file directly). Only a
109
+ * well-formed one counts: an `http(s)` address and a non-empty token. The
110
+ * address is kept to its origin and path — a query, a fragment or a trailing
111
+ * slash in it would make every API address wrong — and the path stays,
112
+ * because a deployment served under a prefix has its API under that prefix.
113
+ */
114
+ export function readEmbedHandoff(): EmbedHandoff | null {
115
+ const raw = (window as unknown as Record<string, unknown>)[EMBED_HANDOFF_GLOBAL];
116
+ if (!raw || typeof raw !== 'object') return null;
117
+ const h = raw as { baseUrl?: unknown; token?: unknown; openLink?: unknown };
118
+ if (typeof h.baseUrl !== 'string' || !/^https?:\/\//i.test(h.baseUrl)) return null;
119
+ if (typeof h.token !== 'string' || h.token === '') return null;
120
+ let baseUrl: string;
121
+ try {
122
+ const url = new URL(h.baseUrl);
123
+ baseUrl = `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
124
+ } catch {
125
+ return null;
126
+ }
127
+ return {
128
+ baseUrl,
129
+ token: h.token,
130
+ ...(typeof h.openLink === 'function' ? { openLink: h.openLink as (url: string) => void } : {}),
131
+ };
132
+ }