@bevel-software/platform-core-frontend 0.1.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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/package.json +70 -0
  3. package/src/core/CoreAppShell.tsx +444 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
  5. package/src/core/events.ts +29 -0
  6. package/src/core/registry.ts +336 -0
  7. package/src/css-side-effect-imports.d.ts +7 -0
  8. package/src/html-extensions.ts +12 -0
  9. package/src/index.css +49 -0
  10. package/src/index.ts +23 -0
  11. package/src/lib/api.ts +57 -0
  12. package/src/lib/utils.ts +138 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
  14. package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
  15. package/src/modules/access/api.ts +205 -0
  16. package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
  17. package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
  18. package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
  19. package/src/modules/access/hooks/useFileAccess.ts +151 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
  22. package/src/modules/admin/services/admin.api.ts +92 -0
  23. package/src/modules/admin/services/roles.api.ts +136 -0
  24. package/src/modules/admin/state/admin.context.tsx +223 -0
  25. package/src/modules/auth/components/LoginScreen.tsx +135 -0
  26. package/src/modules/auth/hooks/useAuthState.ts +59 -0
  27. package/src/modules/auth/services/auth.api.ts +24 -0
  28. package/src/modules/auth/services/microsoft-oauth.ts +57 -0
  29. package/src/modules/auth/state/auth.context.ts +18 -0
  30. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
  31. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
  32. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
  33. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
  34. package/src/modules/git/__tests__/git.api.test.ts +113 -0
  35. package/src/modules/git/__tests__/pr.api.test.ts +44 -0
  36. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
  37. package/src/modules/git/components/BranchSwitcher.tsx +527 -0
  38. package/src/modules/git/components/DiffView.tsx +30 -0
  39. package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
  40. package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
  41. package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
  42. package/src/modules/git/components/PullNeededBanner.tsx +204 -0
  43. package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
  44. package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
  45. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
  46. package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
  47. package/src/modules/git/hooks/useGitState.ts +335 -0
  48. package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
  49. package/src/modules/git/services/error-messages.ts +257 -0
  50. package/src/modules/git/services/git.api.ts +163 -0
  51. package/src/modules/git/services/pr-prompts.ts +159 -0
  52. package/src/modules/git/services/pr.api.ts +39 -0
  53. package/src/modules/git/state/auto-update.context.ts +21 -0
  54. package/src/modules/git/state/git.context.ts +82 -0
  55. package/src/modules/layout/components/AppLayout.tsx +40 -0
  56. package/src/modules/layout/components/DemoBanner.tsx +57 -0
  57. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
  58. package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
  59. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
  60. package/src/modules/layout/components/SlideOverlay.tsx +224 -0
  61. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
  62. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
  63. package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
  64. package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
  65. package/src/modules/layout/state/layout.context.ts +46 -0
  66. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
  67. package/src/modules/library/__tests__/diff.test.ts +62 -0
  68. package/src/modules/library/__tests__/loadout.test.tsx +72 -0
  69. package/src/modules/library/__tests__/status.test.ts +117 -0
  70. package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
  71. package/src/modules/library/components/CompareView.tsx +357 -0
  72. package/src/modules/library/components/DetailDialog.tsx +566 -0
  73. package/src/modules/library/components/GearIcon.tsx +12 -0
  74. package/src/modules/library/components/LibraryCard.tsx +132 -0
  75. package/src/modules/library/components/LibraryPage.tsx +254 -0
  76. package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
  77. package/src/modules/library/components/StatusGem.tsx +21 -0
  78. package/src/modules/library/components/SuggestChange.tsx +171 -0
  79. package/src/modules/library/components/particles.ts +50 -0
  80. package/src/modules/library/hooks/useLibraryData.ts +119 -0
  81. package/src/modules/library/hooks/useSkillDetail.ts +74 -0
  82. package/src/modules/library/library.css +320 -0
  83. package/src/modules/library/services/library.api.ts +164 -0
  84. package/src/modules/library/state/loadout.tsx +129 -0
  85. package/src/modules/library/state/toast.tsx +42 -0
  86. package/src/modules/library/utils/diff.ts +102 -0
  87. package/src/modules/library/utils/status.ts +116 -0
  88. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
  89. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
  90. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
  91. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
  92. package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
  93. package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
  94. package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
  96. package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
  97. package/src/modules/pr/components/PrCancelButton.tsx +99 -0
  98. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
  99. package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
  100. package/src/modules/pr/components/PrCommentThread.tsx +168 -0
  101. package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
  102. package/src/modules/pr/components/PrDiffPane.tsx +425 -0
  103. package/src/modules/pr/components/PrFileRow.tsx +164 -0
  104. package/src/modules/pr/components/PrFilesList.tsx +53 -0
  105. package/src/modules/pr/components/PrHeader.tsx +45 -0
  106. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
  107. package/src/modules/pr/components/PrMergeButton.tsx +268 -0
  108. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
  109. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
  110. package/src/modules/pr/components/PrViewer.tsx +364 -0
  111. package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
  112. package/src/modules/pr/services/pr-approvals.api.ts +31 -0
  113. package/src/modules/pr/services/pr-cancel.api.ts +19 -0
  114. package/src/modules/pr/services/pr-comments.api.ts +45 -0
  115. package/src/modules/pr/services/pr-detail.api.ts +17 -0
  116. package/src/modules/pr/services/pr-merge.api.ts +53 -0
  117. package/src/modules/pr/services/pr-open.api.ts +30 -0
  118. package/src/modules/pr/state/pr-viewer.context.ts +34 -0
  119. package/src/modules/pr/utils/bucketize-comments.ts +55 -0
  120. package/src/modules/pr/utils/parsePatch.ts +57 -0
  121. package/src/modules/review/__tests__/review.api.test.ts +121 -0
  122. package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
  123. package/src/modules/review/components/DiffViewer.tsx +78 -0
  124. package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
  125. package/src/modules/review/components/ReviewFileRow.tsx +114 -0
  126. package/src/modules/review/components/ReviewPanel.tsx +260 -0
  127. package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
  128. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
  129. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
  130. package/src/modules/review/hooks/useReviewState.ts +256 -0
  131. package/src/modules/review/services/review.api.ts +72 -0
  132. package/src/modules/review/state/ReviewProvider.tsx +28 -0
  133. package/src/modules/review/state/review.context.ts +29 -0
  134. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
  135. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
  136. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
  137. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
  138. package/src/modules/secrets-vault/services/connect.api.ts +113 -0
  139. package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
  140. package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
  141. package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
  142. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
  144. package/src/modules/toolbar/components/Toolbar.tsx +123 -0
  145. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
  146. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
  147. package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
  148. package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
  149. package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
  150. package/src/modules/workflow/hooks/useFileLock.ts +430 -0
  151. package/src/modules/workflow/services/lock.api.ts +139 -0
  152. package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
  153. package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
  154. package/src/modules/workflow/state/event-bus.context.ts +75 -0
  155. package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
  156. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
  157. package/src/modules/workspace/components/EditorTabs.tsx +384 -0
  158. package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
  159. package/src/modules/workspace/components/FileRoute.tsx +392 -0
  160. package/src/modules/workspace/components/FileViewer.tsx +906 -0
  161. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
  162. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
  163. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
  164. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
  165. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
  166. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
  167. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
  168. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
  169. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
  170. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
  171. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
  172. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
  173. package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
  174. package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
  175. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
  176. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
  177. package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
  178. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
  179. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
  180. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
  181. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
  182. package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
  183. package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
  184. package/src/modules/workspace/components/renderers/index.ts +39 -0
  185. package/src/modules/workspace/components/renderers/types.ts +27 -0
  186. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
  189. package/src/modules/workspace/routing/kb-routes.ts +266 -0
  190. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
  191. package/src/modules/workspace/services/workspace.api.ts +185 -0
  192. package/src/modules/workspace/state/workspace.context.ts +235 -0
  193. package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
  194. package/src/modules/workspace/utils/diff.ts +53 -0
  195. package/src/modules/workspace/utils/fileTree.ts +179 -0
  196. package/src/modules/workspace/utils/frontmatter.ts +80 -0
  197. package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
  198. package/src/modules/workspace/utils/tab-persistence.ts +23 -0
  199. package/src/shared/components/Dialog.tsx +198 -0
  200. package/src/shared/components/PageShell.tsx +51 -0
  201. package/src/shared/components/useModalLayer.ts +35 -0
  202. package/src/shared/markdown/Markdown.tsx +62 -0
  203. package/src/test-setup.ts +59 -0
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Sandboxing utilities for the HTML renderer.
3
+ *
4
+ * The threat model: agent-authored HTML in the workspace is treated as
5
+ * untrusted. It runs in an iframe with `sandbox="allow-scripts"` (no
6
+ * `allow-same-origin`, no `allow-popups`, no `allow-top-navigation`,
7
+ * no `allow-forms`) and a strict Content-Security-Policy that forbids
8
+ * outbound network of any kind. The only data channel between the iframe
9
+ * and the parent is `postMessage`, which the parent validates.
10
+ *
11
+ * This module provides two pieces:
12
+ *
13
+ * 1. `sanitizeAgentHtml` — defense-in-depth pre-processing that strips
14
+ * external URLs (and dangerous elements like <script src>, <link>,
15
+ * <iframe>, <object>, <embed>, <base>, <meta>) from the agent's HTML
16
+ * before it is bundled into the srcdoc. CSP would block these at runtime
17
+ * anyway, but stripping ahead of time makes the bundled document
18
+ * smaller, easier to audit, and removes any chance a future CSP
19
+ * misconfiguration accidentally leaks something through.
20
+ *
21
+ * 2. `buildSandboxedHtml` — wraps the sanitized body and the inlined
22
+ * knowledge-base JS library into a complete HTML document with the
23
+ * strict CSP and a single inline `<script type="module">` containing
24
+ * the library code (so `window.bevel.buildGraph()` is callable from
25
+ * the agent's own scripts).
26
+ */
27
+
28
+ const DROP_ELEMENTS = new Set([
29
+ 'link',
30
+ 'iframe',
31
+ 'object',
32
+ 'embed',
33
+ 'base',
34
+ 'applet',
35
+ 'frame',
36
+ 'frameset',
37
+ 'meta',
38
+ ]);
39
+
40
+ const URL_ATTRIBUTES = [
41
+ 'src',
42
+ 'href',
43
+ 'action',
44
+ 'formaction',
45
+ 'background',
46
+ 'poster',
47
+ 'cite',
48
+ 'data',
49
+ 'srcset',
50
+ 'ping',
51
+ 'manifest',
52
+ 'archive',
53
+ 'codebase',
54
+ 'longdesc',
55
+ 'profile',
56
+ 'usemap',
57
+ ];
58
+
59
+ /**
60
+ * Decide whether a URL value is allowed to remain on a sanitized element.
61
+ * Keep only fragment links and inline `data:image/*` URLs — every other
62
+ * shape (absolute URL, protocol-relative, scheme-bearing, or plain
63
+ * relative path that the browser would resolve against `about:srcdoc`)
64
+ * is stripped.
65
+ */
66
+ function isAllowedUrl(rawUrl: string): boolean {
67
+ const url = rawUrl.trim().toLowerCase();
68
+ if (url === '') return true;
69
+ if (url.startsWith('#')) return true;
70
+ if (url.startsWith('data:image/')) return true;
71
+ return false;
72
+ }
73
+
74
+ /**
75
+ * Decide whether an `<a href>` deep-links to a node in the knowledge graph:
76
+ * either a `.md` node path (optionally with a `#heading` anchor, e.g.
77
+ * `../NodeTypes/Process.md#goal`) or an absolute `/workspace/<branch>/<path>`
78
+ * citation URL — the same shapes the markdown renderer treats as internal
79
+ * links.
80
+ *
81
+ * These survive sanitization (unlike other relative URLs, which are stripped):
82
+ * the iframe sandbox forbids navigating the top window, so the runtime
83
+ * intercepts the click and asks the parent to navigate instead of letting the
84
+ * browser attempt — and error on — the navigation. Any scheme-bearing
85
+ * (`http:`, `javascript:`, …) or protocol-relative (`//host`) URL is rejected.
86
+ */
87
+ function isInternalNodeLink(rawUrl: string): boolean {
88
+ const url = rawUrl.trim();
89
+ if (url === '') return false;
90
+ if (url.startsWith('//')) return false; // protocol-relative
91
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url)) return false; // any URL scheme
92
+ if (url.startsWith('/workspace/')) return true;
93
+ return /\.md(#|$)/i.test(url);
94
+ }
95
+
96
+ /**
97
+ * Strip dangerous elements and external URL attributes from agent-authored
98
+ * HTML. Returns the cleaned-up `<body>` inner HTML — the bundler wraps it
99
+ * in our own `<html>` / `<head>` shell.
100
+ */
101
+ export function sanitizeAgentHtml(html: string): string {
102
+ const doc = new DOMParser().parseFromString(html, 'text/html');
103
+
104
+ // Hoist <style> and inline <script> from <head> into the start of <body>.
105
+ // The bundler emits its own <head> (CSP, charset, title), so we serialize
106
+ // only the body's inner HTML at the end. Without this hoist, agent-authored
107
+ // CSS in `<head><style>…</style></head>` — which is where most authors put
108
+ // it — would be silently dropped, producing an unstyled page.
109
+ const headHoist: Element[] = [];
110
+ for (const el of Array.from(doc.head.children)) {
111
+ const tag = el.tagName.toLowerCase();
112
+ if (tag === 'style' || (tag === 'script' && !el.hasAttribute('src'))) {
113
+ headHoist.push(el);
114
+ }
115
+ }
116
+ if (headHoist.length) doc.body.prepend(...headHoist);
117
+
118
+ // Drop disallowed elements outright.
119
+ for (const tag of DROP_ELEMENTS) {
120
+ const els = doc.querySelectorAll(tag);
121
+ for (let i = 0; i < els.length; i += 1) els[i].remove();
122
+ }
123
+
124
+ // Handle `<script>` tags. External `<script src>` is dropped outright (the
125
+ // CSP would block it anyway, but stripping keeps the bundled doc clean).
126
+ // Inline scripts are converted to `<script type="module">` so they execute
127
+ // in source order *after* the knowledge-base library module — this
128
+ // guarantees `window.bevel.buildGraph()` is defined by the time the agent's
129
+ // code runs. Module scripts also implicitly defer until the document is
130
+ // parsed, so DOM lookups like `document.getElementById('app')` work without
131
+ // an explicit `DOMContentLoaded` wait.
132
+ const scripts = doc.querySelectorAll('script');
133
+ for (let i = 0; i < scripts.length; i += 1) {
134
+ const el = scripts[i];
135
+ if (el.hasAttribute('src')) {
136
+ el.remove();
137
+ continue;
138
+ }
139
+ el.setAttribute('type', 'module');
140
+ }
141
+
142
+ // Strip every URL-bearing attribute that points anywhere external. We
143
+ // also strip relative paths because the iframe loads from `about:srcdoc`,
144
+ // where relative URLs resolve to nothing useful — leaving them in just
145
+ // produces broken-image icons and confuses the reader.
146
+ const all = doc.querySelectorAll('*');
147
+ for (let i = 0; i < all.length; i += 1) {
148
+ const el = all[i];
149
+ const isAnchor = el.tagName.toLowerCase() === 'a';
150
+ for (const attr of URL_ATTRIBUTES) {
151
+ if (!el.hasAttribute(attr)) continue;
152
+ const value = el.getAttribute(attr) ?? '';
153
+ // An anchor that deep-links to a KB node keeps its href — the runtime
154
+ // intercepts the click and routes navigation through the parent (see
155
+ // the nav-bridge script in `buildSandboxedHtml`).
156
+ if (isAnchor && attr === 'href' && isInternalNodeLink(value)) continue;
157
+ if (!isAllowedUrl(value)) el.removeAttribute(attr);
158
+ }
159
+ }
160
+
161
+ return doc.body.innerHTML;
162
+ }
163
+
164
+ /**
165
+ * The Content-Security-Policy applied to the iframe document. Pinned in code
166
+ * so the rules cannot drift between renderer and audit.
167
+ *
168
+ * - `default-src 'none'` everything is denied unless explicitly allowed
169
+ * - `script-src 'unsafe-inline'` only inline scripts (no src= loads)
170
+ * - `style-src 'unsafe-inline'` only inline styles
171
+ * - `img-src data:` only data: URIs (no remote pixels)
172
+ * - `font-src data:` only data: URIs (no font CDNs)
173
+ * - `connect-src 'none'` no fetch/XHR/EventSource/WebSocket/sendBeacon
174
+ * - `form-action 'none'` forms cannot submit anywhere
175
+ * - `base-uri 'none'` <base> cannot redirect relative URLs
176
+ * - `frame-src 'none'` no nested iframes
177
+ *
178
+ * `frame-ancestors` is intentionally omitted — browsers ignore it when
179
+ * delivered via `<meta>`, and the parent already chose to embed this iframe
180
+ * by setting its `srcDoc`, so the directive would be redundant anyway.
181
+ */
182
+ const CSP_DIRECTIVES = [
183
+ "default-src 'none'",
184
+ "script-src 'unsafe-inline'",
185
+ "style-src 'unsafe-inline'",
186
+ 'img-src data:',
187
+ 'font-src data:',
188
+ "connect-src 'none'",
189
+ "form-action 'none'",
190
+ "base-uri 'none'",
191
+ "frame-src 'none'",
192
+ ].join('; ');
193
+
194
+ /**
195
+ * Names exposed on `window.bevel` inside the iframe. Each name MUST be a
196
+ * top-level identifier in the concatenated source, or the
197
+ * `globalThis.bevel = {...}` literal throws `ReferenceError` and aborts before
198
+ * assignment. Core inlines no library sources, so this is empty — the
199
+ * enterprise build adds `buildGraph` (the KB-graph client's entry point) here
200
+ * alongside its inlined d3/mermaid/graph-client sources.
201
+ */
202
+ const BEVEL_GLOBAL_EXPORTS: string[] = [];
203
+
204
+ /**
205
+ * Strip relative-path `import` statements between concatenated library files.
206
+ * After concatenation every named symbol is in the same module scope, so the
207
+ * imports are redundant — and they would otherwise re-declare bindings that
208
+ * already exist (causing "Identifier already declared" parse errors).
209
+ *
210
+ * Handles both single-line and multi-line forms:
211
+ * import { Foo } from './bar.js';
212
+ * import {
213
+ * Foo,
214
+ * Bar,
215
+ * } from './baz.js';
216
+ * import './side-effect.js';
217
+ *
218
+ * `[^;]*?` is non-greedy and matches across newlines (the negated character
219
+ * class includes `\n`), so the whole statement up to the terminating `;` is
220
+ * consumed even when it spans multiple source lines.
221
+ */
222
+ function stripRelativeImports(source: string): string {
223
+ return source.replace(
224
+ /^[ \t]*import\s[^;]*?['"]\.{1,2}\/[^'"\n]+['"][^;]*;?/gm,
225
+ '',
226
+ );
227
+ }
228
+
229
+ /**
230
+ * Encode a string so it is safe to embed inside an HTML `<script>` tag body.
231
+ * The only sequence we have to break is the literal `</script>` (or
232
+ * variants), which would otherwise close the script element early — even
233
+ * when the literal sits inside a JS string.
234
+ *
235
+ * Escaping the slash inside the closing tag preserves the JS source
236
+ * semantics (string contents are unchanged after JS parsing) while
237
+ * preventing the HTML tokenizer from finishing the script element.
238
+ */
239
+ function escapeForScriptBody(source: string): string {
240
+ return source.replace(/<\/(script)/gi, '<\\/$1');
241
+ }
242
+
243
+ /**
244
+ * Runtime appended to the iframe's inline module so agent HTML can deep-link
245
+ * into the knowledge graph. The iframe is sandboxed without
246
+ * `allow-top-navigation`, so it can't navigate the host window itself — any
247
+ * attempt throws "Unsafe attempt to initiate navigation … sandboxed …". Instead
248
+ * we hand the target to the parent via `postMessage`; the parent
249
+ * (`HtmlRenderer` / the embed) decides whether and how to navigate.
250
+ *
251
+ * Two entry points:
252
+ * - `window.bevel.openNode(href)` — for programmatic viewers (e.g. a d3 graph
253
+ * whose node `click` handler wants to open the underlying node).
254
+ * - A delegated click listener on `<a href>` — for plain HTML links. Pure
255
+ * in-page anchors (`#…`) are left alone so they still scroll the document.
256
+ */
257
+ const NAV_BRIDGE = `
258
+ ;(function () {
259
+ function navigate(target) {
260
+ if (typeof target !== 'string' || target === '') return;
261
+ parent.postMessage({ type: 'bevel.navigate', href: target }, '*');
262
+ }
263
+ globalThis.bevel.openNode = navigate;
264
+ globalThis.bevel.navigate = navigate;
265
+ if (typeof document !== 'undefined') {
266
+ document.addEventListener('click', function (e) {
267
+ var el = e.target;
268
+ var a = el && el.closest ? el.closest('a[href]') : null;
269
+ if (!a) return;
270
+ var href = a.getAttribute('href');
271
+ if (!href || href.charAt(0) === '#') return;
272
+ e.preventDefault();
273
+ navigate(href);
274
+ });
275
+ }
276
+ })();
277
+ `;
278
+
279
+ interface BuildSandboxedHtmlOptions {
280
+ /** Display title (rendered in the iframe doc's <title>). */
281
+ title: string;
282
+ /** knowledge-base JS library files, in dependency order. */
283
+ libModuleSources: string[];
284
+ /** Sanitized agent HTML, body content only. */
285
+ bodyHtml: string;
286
+ }
287
+
288
+ /**
289
+ * Bundle the inlined library + sanitized agent body into a complete HTML
290
+ * document suitable for `<iframe srcDoc>`. The output makes zero network
291
+ * requests: the library is inlined, the CSP forbids outbound fetches, and
292
+ * the sanitizer has already stripped any external URLs from the body.
293
+ */
294
+ export function buildSandboxedHtml(opts: BuildSandboxedHtmlOptions): string {
295
+ const lib = opts.libModuleSources.map(stripRelativeImports).join('\n\n');
296
+ const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\n`;
297
+ const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE);
298
+
299
+ // Title and body are content-only — `srcDoc` already isolates them, but we
300
+ // still want to escape the few characters that would terminate the parent
301
+ // attribute or the script element early.
302
+ const safeTitle = opts.title.replace(/[<>&"]/g, (c) => {
303
+ switch (c) {
304
+ case '<':
305
+ return '&lt;';
306
+ case '>':
307
+ return '&gt;';
308
+ case '&':
309
+ return '&amp;';
310
+ case '"':
311
+ return '&quot;';
312
+ default:
313
+ return c;
314
+ }
315
+ });
316
+
317
+ return `<!doctype html>
318
+ <html lang="en">
319
+ <head>
320
+ <meta charset="utf-8">
321
+ <meta http-equiv="Content-Security-Policy" content="${CSP_DIRECTIVES}">
322
+ <meta name="referrer" content="no-referrer">
323
+ <title>${safeTitle}</title>
324
+ </head>
325
+ <body>
326
+ <script type="module">
327
+ ${inlineLib}
328
+ </script>
329
+ ${opts.bodyHtml}
330
+ </body>
331
+ </html>`;
332
+ }
@@ -0,0 +1,39 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { FileRendererProps } from './types';
3
+ import { MarkdownRenderer } from './MarkdownRenderer';
4
+ import { TextRenderer } from './TextRenderer';
5
+ import { ImageRenderer } from './ImageRenderer';
6
+ import { HtmlRenderer } from './HtmlRenderer';
7
+ import { PdfRenderer } from './PdfRenderer';
8
+ import { DocxRenderer } from './DocxRenderer';
9
+ import { XlsxRenderer } from './XlsxRenderer';
10
+ import { CsvRenderer } from './CsvRenderer';
11
+ import { ToolRenderer } from './ToolRenderer';
12
+
13
+ export type { FileRendererProps, RendererSaveState } from './types';
14
+
15
+ const renderersByExtension: Record<string, ComponentType<FileRendererProps>> = {
16
+ '.md': MarkdownRenderer,
17
+ '.html': HtmlRenderer,
18
+ '.htm': HtmlRenderer,
19
+ '.png': ImageRenderer,
20
+ '.jpg': ImageRenderer,
21
+ '.jpeg': ImageRenderer,
22
+ '.gif': ImageRenderer,
23
+ '.webp': ImageRenderer,
24
+ '.svg': ImageRenderer,
25
+ '.bmp': ImageRenderer,
26
+ '.ico': ImageRenderer,
27
+ '.pdf': PdfRenderer,
28
+ '.docx': DocxRenderer,
29
+ '.xlsx': XlsxRenderer,
30
+ '.csv': CsvRenderer,
31
+ '.tool': ToolRenderer,
32
+ };
33
+
34
+ const fallbackRenderer = TextRenderer;
35
+
36
+ export function getFileRenderer(filePath: string): ComponentType<FileRendererProps> {
37
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
38
+ return renderersByExtension[ext] ?? fallbackRenderer;
39
+ }
@@ -0,0 +1,27 @@
1
+ export type RendererSaveState = 'idle' | 'saving' | 'error';
2
+
3
+ export interface FileRendererProps {
4
+ /**
5
+ * The current value to display in the renderer. May include in-flight user
6
+ * edits that haven't been saved yet (kept across tab switches by the
7
+ * workspace hook).
8
+ */
9
+ content: string;
10
+ /**
11
+ * The bytes currently on disk. The renderer derives `dirty = content !==
12
+ * savedContent`. When omitted, falls back to `content` (matching the
13
+ * single-file legacy behavior). Required for multi-tab + cache-per-tab to
14
+ * compute dirty correctly after a tab remount.
15
+ */
16
+ savedContent?: string;
17
+ filePath: string;
18
+ onSave: (content: string) => Promise<void>;
19
+ onDirtyChange?: (dirty: boolean) => void;
20
+ /**
21
+ * Fires whenever the user-edited value changes. The hook caches this on the
22
+ * active tab so typed-but-unsaved bytes survive a tab switch.
23
+ */
24
+ onValueChange?: (value: string) => void;
25
+ onSaveStateChange?: (state: RendererSaveState) => void;
26
+ readOnly?: boolean;
27
+ }