@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,87 @@
1
+ import { useEffect, useState } from 'react';
2
+ // mammoth's package.json declares a `browser` field that swaps out the two
3
+ // Node-only modules (unzip / files) for browser equivalents, so a plain
4
+ // `import 'mammoth'` works under Vite. No published types; we keep the
5
+ // import untyped and cast inside the effect.
6
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7
+ // @ts-expect-error — mammoth ships no .d.ts
8
+ import mammoth from 'mammoth/mammoth.browser.js';
9
+ import { useWorkspace } from '../../state/workspace.context';
10
+ import { authFetch } from '../../../../lib/api';
11
+ import type { FileRendererProps } from './types';
12
+
13
+ /**
14
+ * Inline .docx viewer. Fetches the binary from `/api/workspace/:id/file/raw`,
15
+ * runs it through mammoth's browser bundle to convert OOXML → HTML, then
16
+ * drops the HTML straight into a Tailwind `prose` block. mammoth strips
17
+ * scripts and unknown elements when it builds the HTML so the output is
18
+ * safe to inject — the same approach `react-markdown` uses for sanitised
19
+ * HTML in the markdown renderer.
20
+ *
21
+ * View-only: there is no edit mode for binary office formats. The renderer
22
+ * ignores `onSave` / `onValueChange` / `readOnly`.
23
+ */
24
+ export function DocxRenderer({ filePath }: FileRendererProps) {
25
+ const { workspaceId } = useWorkspace();
26
+ const [html, setHtml] = useState<string | null>(null);
27
+ const [error, setError] = useState<string | null>(null);
28
+
29
+ useEffect(() => {
30
+ setHtml(null);
31
+ setError(null);
32
+ if (!workspaceId) return;
33
+
34
+ let cancelled = false;
35
+ (async () => {
36
+ try {
37
+ const res = await authFetch(
38
+ `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}`,
39
+ );
40
+ if (cancelled) return;
41
+ if (!res.ok) {
42
+ setError(`Failed to load Word document (HTTP ${res.status})`);
43
+ return;
44
+ }
45
+ const buffer = await res.arrayBuffer();
46
+ if (cancelled) return;
47
+ const result = (await mammoth.convertToHtml({ arrayBuffer: buffer })) as {
48
+ value: string;
49
+ };
50
+ if (cancelled) return;
51
+ setHtml(result.value);
52
+ } catch (e) {
53
+ if (cancelled) return;
54
+ setError(e instanceof Error ? e.message : String(e));
55
+ }
56
+ })();
57
+
58
+ return () => {
59
+ cancelled = true;
60
+ };
61
+ }, [workspaceId, filePath]);
62
+
63
+ if (error) {
64
+ return (
65
+ <div className="flex items-center justify-center h-full text-red-600 text-sm">
66
+ {error}
67
+ </div>
68
+ );
69
+ }
70
+
71
+ if (html === null) {
72
+ return (
73
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
74
+ Loading Word document...
75
+ </div>
76
+ );
77
+ }
78
+
79
+ return (
80
+ <div className="h-full overflow-auto">
81
+ <div
82
+ className="prose prose-sm max-w-none"
83
+ dangerouslySetInnerHTML={{ __html: html }}
84
+ />
85
+ </div>
86
+ );
87
+ }
@@ -0,0 +1,231 @@
1
+ import { useState, useCallback, useEffect, useRef } from 'react';
2
+ import { Pencil, Eye, RotateCw } from 'lucide-react';
3
+ import { useFileNav, KB_ROUTE_PREFIX, resolveRelativePath } from '../../routing/kb-routes';
4
+ import type { FileRendererProps, RendererSaveState } from './types';
5
+ import { buildSandboxedHtml, sanitizeAgentHtml } from './htmlSandbox';
6
+
7
+ export function HtmlRenderer({
8
+ content,
9
+ savedContent,
10
+ filePath,
11
+ onSave,
12
+ onDirtyChange,
13
+ onValueChange,
14
+ onSaveStateChange,
15
+ readOnly = false,
16
+ }: FileRendererProps) {
17
+ const { openFile } = useFileNav();
18
+ const [mode, setMode] = useState<'preview' | 'edit'>('preview');
19
+ const [value, setValue] = useState(content);
20
+ const [savedValue, setSavedValue] = useState(savedContent ?? content);
21
+ const [saveState, setSaveState] = useState<RendererSaveState>('idle');
22
+ const [saveError, setSaveError] = useState<string | null>(null);
23
+ const [bundledSrcdoc, setBundledSrcdoc] = useState<string | null>(null);
24
+ const [previewError, setPreviewError] = useState<string | null>(null);
25
+ const [reloadKey, setReloadKey] = useState(0);
26
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
27
+ const prevFilePathRef = useRef(filePath);
28
+
29
+ const dirty = !readOnly && value !== savedValue;
30
+
31
+ useEffect(() => {
32
+ const fileChanged = prevFilePathRef.current !== filePath;
33
+ prevFilePathRef.current = filePath;
34
+ setValue(content);
35
+ setSavedValue(savedContent ?? content);
36
+ setSaveState('idle');
37
+ setSaveError(null);
38
+ if (fileChanged) {
39
+ setMode('preview');
40
+ setReloadKey((k) => k + 1);
41
+ }
42
+ }, [content, savedContent, filePath]);
43
+
44
+ useEffect(() => {
45
+ onDirtyChange?.(dirty);
46
+ }, [dirty, onDirtyChange]);
47
+
48
+ useEffect(() => {
49
+ onSaveStateChange?.(saveState);
50
+ }, [saveState, onSaveStateChange]);
51
+
52
+ // Build the iframe document whenever we enter preview mode or the saved
53
+ // content changes. The agent's HTML is sanitized to strip any external URLs
54
+ // (defense in depth — CSP also blocks them at runtime), then bundled with
55
+ // the KB's JS library inlined as a `<script type="module">`. The result is a
56
+ // fully self-contained srcdoc — the iframe makes no network calls of any kind.
57
+ useEffect(() => {
58
+ if (mode !== 'preview') return;
59
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- safe transient reset before rebuild
60
+ setPreviewError(null);
61
+ try {
62
+ const doc = buildSandboxedHtml({
63
+ title: filePath,
64
+ // Core ships no inlined vendor libraries. (The enterprise build inlines
65
+ // d3 + mermaid and the KB graph client here — the knowledge system,
66
+ // including the graph API the client talks to, is an enterprise
67
+ // extension.)
68
+ libModuleSources: [],
69
+ bodyHtml: sanitizeAgentHtml(savedValue),
70
+ });
71
+ setBundledSrcdoc(doc);
72
+ } catch (err) {
73
+ setPreviewError(err instanceof Error ? err.message : 'Failed to build preview');
74
+ }
75
+ }, [mode, savedValue, filePath, reloadKey]);
76
+
77
+ // (The enterprise build additionally installs a postMessage bridge here that
78
+ // serves the iframe's KB-graph client from `/api/workspace/:id/graph` — the
79
+ // knowledge system is an enterprise extension, so the core renderer has no
80
+ // graph bridge.)
81
+
82
+ // Navigation bridge: agent HTML deep-links into the KB by calling
83
+ // `window.bevel.openNode(href)` or clicking an `<a>` whose href points at a
84
+ // node — both post a `bevel.navigate` message (the iframe sandbox can't
85
+ // navigate the host window itself). We resolve the href the same way the
86
+ // markdown renderer does (absolute `/workspace/…` URLs pass through; relative
87
+ // `.md` paths resolve against this file) and route it through the in-app
88
+ // navigation so the URL reflects what's on screen.
89
+ useEffect(() => {
90
+ function onNavMessage(event: MessageEvent) {
91
+ const iframeWin = iframeRef.current?.contentWindow;
92
+ if (!iframeWin || event.source !== iframeWin) return;
93
+ const msg = event.data as { type?: unknown; href?: unknown } | null;
94
+ if (!msg || typeof msg !== 'object' || msg.type !== 'bevel.navigate') return;
95
+ const href = typeof msg.href === 'string' ? msg.href : null;
96
+ if (!href) return;
97
+ if (href.startsWith(`${KB_ROUTE_PREFIX}/`)) {
98
+ openFile(href);
99
+ return;
100
+ }
101
+ let decoded = href;
102
+ try { decoded = decodeURIComponent(href); } catch { /* leave as-is */ }
103
+ openFile(resolveRelativePath(filePath, decoded));
104
+ }
105
+ window.addEventListener('message', onNavMessage);
106
+ return () => window.removeEventListener('message', onNavMessage);
107
+ }, [openFile, filePath]);
108
+
109
+ const save = useCallback(async (): Promise<boolean> => {
110
+ if (readOnly || value === savedValue) return true;
111
+ setSaveState('saving');
112
+ setSaveError(null);
113
+ try {
114
+ await onSave(value);
115
+ setSavedValue(value);
116
+ setSaveState('idle');
117
+ setReloadKey((k) => k + 1);
118
+ return true;
119
+ } catch (err) {
120
+ setSaveState('error');
121
+ setSaveError(err instanceof Error ? err.message : 'Failed to save');
122
+ return false;
123
+ }
124
+ }, [readOnly, value, savedValue, onSave]);
125
+
126
+ const switchToPreview = useCallback(() => {
127
+ void (async () => {
128
+ const ok = await save();
129
+ if (ok) setMode('preview');
130
+ })();
131
+ }, [save]);
132
+
133
+ const switchToEdit = useCallback(() => {
134
+ if (!readOnly) setMode('edit');
135
+ }, [readOnly]);
136
+
137
+ const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
138
+ const next = e.target.value;
139
+ setValue(next);
140
+ onValueChange?.(next);
141
+ }, [onValueChange]);
142
+
143
+ const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
144
+ if ((e.ctrlKey || e.metaKey) && e.key === 's') {
145
+ e.preventDefault();
146
+ void save();
147
+ }
148
+ }, [save]);
149
+
150
+ return (
151
+ <div className="flex flex-col h-full">
152
+ <div className="flex items-center gap-1 pb-3 border-b border-slate-200 mb-3 shrink-0">
153
+ {!readOnly && (
154
+ <button
155
+ onClick={switchToEdit}
156
+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium transition-colors ${
157
+ mode === 'edit'
158
+ ? 'bg-slate-200 text-slate-900'
159
+ : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100'
160
+ }`}
161
+ >
162
+ <Pencil size={12} />
163
+ Edit
164
+ </button>
165
+ )}
166
+ <button
167
+ onClick={switchToPreview}
168
+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium transition-colors ${
169
+ mode === 'preview'
170
+ ? 'bg-slate-200 text-slate-900'
171
+ : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100'
172
+ }`}
173
+ >
174
+ <Eye size={12} />
175
+ Preview
176
+ </button>
177
+ {mode === 'preview' && (
178
+ <button
179
+ onClick={() => setReloadKey((k) => k + 1)}
180
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors"
181
+ title="Reload preview"
182
+ >
183
+ <RotateCw size={12} />
184
+ Refresh
185
+ </button>
186
+ )}
187
+ {saveState === 'saving' && (
188
+ <span className="ml-2 text-xs text-slate-600">Saving…</span>
189
+ )}
190
+ {saveState === 'error' && saveError && (
191
+ <span className="ml-2 text-xs text-red-600 truncate" title={saveError}>
192
+ {saveError}
193
+ </span>
194
+ )}
195
+ </div>
196
+
197
+ {mode === 'edit' && !readOnly ? (
198
+ <textarea
199
+ className="flex-1 w-full bg-transparent text-sm text-slate-700 font-mono whitespace-pre-wrap break-words leading-relaxed resize-none outline-none"
200
+ value={value}
201
+ onChange={handleChange}
202
+ onKeyDown={handleKeyDown}
203
+ spellCheck={false}
204
+ autoFocus
205
+ />
206
+ ) : previewError ? (
207
+ <div className="flex items-center justify-center h-full text-sm text-red-600 px-4 text-center">
208
+ {previewError}
209
+ </div>
210
+ ) : bundledSrcdoc ? (
211
+ <iframe
212
+ key={reloadKey}
213
+ ref={iframeRef}
214
+ srcDoc={bundledSrcdoc}
215
+ title={filePath}
216
+ // `allow-scripts` only — without `allow-same-origin` the iframe's
217
+ // origin is opaque/null. Combined with the document's CSP
218
+ // (`connect-src 'none'`) and the postMessage-only data channel, the
219
+ // iframe cannot exfiltrate, navigate, popup, or fetch.
220
+ sandbox="allow-scripts"
221
+ referrerPolicy="no-referrer"
222
+ className="flex-1 w-full bg-white rounded border border-slate-200"
223
+ />
224
+ ) : (
225
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
226
+ Loading preview…
227
+ </div>
228
+ )}
229
+ </div>
230
+ );
231
+ }
@@ -0,0 +1,50 @@
1
+ import { useState, useEffect } from 'react';
2
+ import { useWorkspace } from '../../state/workspace.context';
3
+ import { authFetch } from '../../../../lib/api';
4
+ import type { FileRendererProps } from './types';
5
+
6
+ export function ImageRenderer({ filePath }: FileRendererProps) {
7
+ const { workspaceId } = useWorkspace();
8
+ const [objectUrl, setObjectUrl] = useState<string | null>(null);
9
+
10
+ useEffect(() => {
11
+ if (!workspaceId) return;
12
+
13
+ let revoked = false;
14
+ (async () => {
15
+ const res = await authFetch(
16
+ `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}`,
17
+ );
18
+ if (!res.ok || revoked) return;
19
+ const blob = await res.blob();
20
+ if (revoked) return;
21
+ setObjectUrl(URL.createObjectURL(blob));
22
+ })();
23
+
24
+ return () => {
25
+ revoked = true;
26
+ setObjectUrl((prev) => {
27
+ if (prev) URL.revokeObjectURL(prev);
28
+ return null;
29
+ });
30
+ };
31
+ }, [workspaceId, filePath]);
32
+
33
+ if (!objectUrl) {
34
+ return (
35
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
36
+ Loading image...
37
+ </div>
38
+ );
39
+ }
40
+
41
+ return (
42
+ <div className="flex items-center justify-center h-full overflow-auto">
43
+ <img
44
+ src={objectUrl}
45
+ alt={filePath}
46
+ className="max-w-full max-h-full object-contain rounded"
47
+ />
48
+ </div>
49
+ );
50
+ }
@@ -0,0 +1,287 @@
1
+ import { useMemo, useState, type Ref } from 'react';
2
+ import { Link2, Check } from 'lucide-react';
3
+ import Markdown from 'react-markdown';
4
+ import remarkGfm from 'remark-gfm';
5
+ import remarkFrontmatter from 'remark-frontmatter';
6
+ import rehypeRaw from 'rehype-raw';
7
+ import rehypeSanitize from 'rehype-sanitize';
8
+ import rehypeSlug from 'rehype-slug';
9
+ import { parseFrontmatter, labelFor } from '../../utils/frontmatter';
10
+ import { escapeSpacesInLinkDestinations } from '../../../../shared/markdown/Markdown';
11
+ import { MermaidDiagram } from './MermaidDiagram';
12
+
13
+ // A frontmatter value that is a single markdown link, e.g.
14
+ // `nodeType: [Process](../../NodeTypes/Process.md)` (parseFrontmatter strips
15
+ // the surrounding quotes). The destination may be angle-bracketed
16
+ // (`(<path with spaces.md>)`) so paths with spaces resolve. Anchored so only a
17
+ // whole-value link matches; everything else stays plain text.
18
+ const FRONTMATTER_LINK_RE = /^\[([^\]]+)\]\(<?([^)>]+)>?\)$/;
19
+
20
+ /**
21
+ * Copy text to the clipboard. Prefers the async Clipboard API; falls back to a
22
+ * hidden-textarea `execCommand('copy')` for contexts where the Clipboard API is
23
+ * blocked by Permissions Policy (e.g. some embedded iframes).
24
+ */
25
+ async function copyToClipboard(text: string): Promise<boolean> {
26
+ try {
27
+ await navigator.clipboard.writeText(text);
28
+ return true;
29
+ } catch {
30
+ let ta: HTMLTextAreaElement | null = null;
31
+ try {
32
+ ta = document.createElement('textarea');
33
+ ta.value = text;
34
+ ta.style.position = 'fixed';
35
+ ta.style.opacity = '0';
36
+ document.body.appendChild(ta);
37
+ ta.select();
38
+ return document.execCommand('copy');
39
+ } catch {
40
+ return false;
41
+ } finally {
42
+ // Always remove the textarea, even if select()/execCommand threw.
43
+ if (ta?.parentNode) document.body.removeChild(ta);
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Hover-revealed "copy link to this heading" button — mirrors the FileViewer's
50
+ * "copy link to this file" affordance (same `Link2` icon + 1.5s copied state),
51
+ * but copies the heading's deep-link (URL + `#slug`) so a reader can cite a
52
+ * specific section.
53
+ */
54
+ function CopyAnchorButton({ url }: { url: string }) {
55
+ const [copied, setCopied] = useState(false);
56
+ return (
57
+ <button
58
+ type="button"
59
+ onClick={async (e) => {
60
+ e.preventDefault();
61
+ if (await copyToClipboard(url)) {
62
+ setCopied(true);
63
+ window.setTimeout(() => setCopied(false), 1500);
64
+ } else {
65
+ console.error('Failed to copy heading link');
66
+ }
67
+ }}
68
+ // `align-middle` keeps it on the heading baseline; hidden until the
69
+ // heading is hovered (or the button is focused for keyboard users).
70
+ className="ml-1.5 inline-flex align-middle p-0.5 rounded text-slate-400 no-underline opacity-0 transition-opacity hover:bg-slate-100 hover:text-slate-700 focus:opacity-100 group-hover/anchor:opacity-100"
71
+ title={copied ? 'Link copied' : 'Copy link to this heading'}
72
+ aria-label="Copy link to this heading"
73
+ >
74
+ {copied ? <Check size={13} /> : <Link2 size={13} />}
75
+ </button>
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Render a single frontmatter value. A value that is a markdown link (notably
81
+ * `nodeType`) renders as a clickable link; everything else is plain text.
82
+ * `onOpenFile` receives the raw href — the caller decides how to resolve and
83
+ * open it (in-workspace navigation, or a new tab for the embed).
84
+ */
85
+ function FrontmatterValue({
86
+ value,
87
+ onOpenFile,
88
+ }: {
89
+ value: string;
90
+ onOpenFile: (href: string) => void;
91
+ }) {
92
+ const match = value.match(FRONTMATTER_LINK_RE);
93
+ if (match) {
94
+ const [, label, href] = match;
95
+ return (
96
+ <a
97
+ href={href}
98
+ onClick={(e) => {
99
+ e.preventDefault();
100
+ onOpenFile(href);
101
+ }}
102
+ className="text-bevel hover:text-bevel-deep hover:underline cursor-pointer"
103
+ >
104
+ {label}
105
+ </a>
106
+ );
107
+ }
108
+ return <>{value}</>;
109
+ }
110
+
111
+ function FrontmatterPanel({
112
+ data,
113
+ onOpenFile,
114
+ }: {
115
+ data: Record<string, string | string[]>;
116
+ onOpenFile: (href: string) => void;
117
+ }) {
118
+ const entries = Object.entries(data).filter(([, v]) => {
119
+ if (Array.isArray(v)) return v.length > 0;
120
+ return v !== '';
121
+ });
122
+ if (entries.length === 0) return null;
123
+
124
+ return (
125
+ <div className="mb-4 rounded-lg border border-slate-300 bg-slate-100/70 divide-y divide-slate-200/60">
126
+ {entries.map(([key, value]) => (
127
+ <div key={key} className="flex items-start gap-3 px-3 py-2 text-xs">
128
+ <span className="shrink-0 text-slate-600 w-28">{labelFor(key)}</span>
129
+ <span className="text-slate-900 break-words">
130
+ {Array.isArray(value) ? (
131
+ value.join(', ')
132
+ ) : (
133
+ <FrontmatterValue value={value} onOpenFile={onOpenFile} />
134
+ )}
135
+ </span>
136
+ </div>
137
+ ))}
138
+ </div>
139
+ );
140
+ }
141
+
142
+ interface KbMarkdownViewProps {
143
+ /** Raw markdown (may include YAML frontmatter). */
144
+ source: string;
145
+ /**
146
+ * Called with the raw href of an internal `.md` link (body or link-valued
147
+ * frontmatter). The caller resolves it relative to the current node and
148
+ * decides how to open it.
149
+ */
150
+ onOpenFile: (href: string) => void;
151
+ /**
152
+ * Called with the bare node `id` of an id-link (`[text](some-id)` — the
153
+ * post-migration link form). The caller resolves the id to a node location and
154
+ * navigates. When omitted, id-links render as inert text (e.g. the embed,
155
+ * which has no in-app navigation).
156
+ */
157
+ onOpenNodeId?: (id: string) => void;
158
+ /**
159
+ * When provided, each heading gets a hover-revealed copy button that copies
160
+ * `headingLink(slug)` — the heading's citation deep-link. `slug` is the
161
+ * rehype-slug anchor id. Omit it (e.g. in the embed) to hide the buttons.
162
+ */
163
+ headingLink?: (slug: string) => string;
164
+ /** Optional scroll container ref (used by the file viewer for deep-link scroll). */
165
+ containerRef?: Ref<HTMLDivElement>;
166
+ className?: string;
167
+ }
168
+
169
+ /**
170
+ * Presentational KB markdown renderer — the read-mode view shared by the file
171
+ * viewer's `MarkdownRenderer` and the Atlassian embed. Holds the canonical
172
+ * plugin pipeline (GFM + frontmatter + raw/sanitize/slug + Mermaid) and the
173
+ * frontmatter panel, with navigation injected via `onOpenFile` so it carries no
174
+ * dependency on workspace routing or context.
175
+ */
176
+ export function KbMarkdownView({ source, onOpenFile, onOpenNodeId, headingLink, containerRef, className }: KbMarkdownViewProps) {
177
+ const { data: frontmatter, body } = useMemo(() => parseFrontmatter(source), [source]);
178
+ // CommonMark rejects unescaped spaces in link destinations, so a KB link like
179
+ // `[Foo](Some File.md)` would render as plain text. Wrap space-bearing
180
+ // destinations in `<...>` so links to files with spaces resolve.
181
+ const normalizedBody = useMemo(() => escapeSpacesInLinkDestinations(body), [body]);
182
+
183
+ const components = useMemo(() => {
184
+ // One renderer for h1–h6: reads its level from the hast node's tagName,
185
+ // re-attaches the rehype-slug `id`, and appends the copy-anchor button.
186
+ const Heading = ({ node, id, children, className: cls, ...props }: {
187
+ node?: { tagName?: string };
188
+ id?: string;
189
+ children?: React.ReactNode;
190
+ className?: string;
191
+ }) => {
192
+ const Tag = (node?.tagName ?? 'h2') as keyof React.JSX.IntrinsicElements;
193
+ return (
194
+ <Tag id={id} className={`group/anchor ${cls ?? ''}`.trim()} {...props}>
195
+ {children}
196
+ {headingLink && id ? <CopyAnchorButton url={headingLink(id)} /> : null}
197
+ </Tag>
198
+ );
199
+ };
200
+ return {
201
+ h1: Heading, h2: Heading, h3: Heading, h4: Heading, h5: Heading, h6: Heading,
202
+ a({ href, children, ...props }: { href?: string; children?: React.ReactNode }) {
203
+ // id-link: `[text](some-id)` or `[text](some-id#heading)` — a bare node
204
+ // id (the post-migration link form), optionally with a heading anchor
205
+ // (the `cite_kb_node` citation form). Resolve via onOpenNodeId, which
206
+ // splits off the heading. id grammar = lowercase alphanumeric + hyphens
207
+ // + underscores (snake_case tool/skill ids resolve too); the `#…` tail
208
+ // forbids `/` so a `.md` path link never matches. Keep in sync with
209
+ // `NODE_ID_LINK_RE` in kb-routes (kept inline here to avoid pulling the
210
+ // routing/hooks module into the embed bundle).
211
+ if (href && /^[a-z0-9][a-z0-9_-]*(#[^/]+)?$/.test(href)) {
212
+ // No resolver (e.g. the embed) → render inert, never a navigable
213
+ // anchor, so a bare id can't fall through as a relative-URL link.
214
+ if (!onOpenNodeId) return <span {...props}>{children}</span>;
215
+ return (
216
+ <a
217
+ {...props}
218
+ href={href}
219
+ onClick={(e) => {
220
+ e.preventDefault();
221
+ onOpenNodeId(href);
222
+ }}
223
+ className="cursor-pointer"
224
+ >
225
+ {children}
226
+ </a>
227
+ );
228
+ }
229
+ // Legacy/internal path link: a `.md` destination, optionally with a
230
+ // heading anchor (`Node.md#goal`) — still used by frontmatter `nodeType`.
231
+ // External (`http…`) and same-page (`#…`) links fall through to <a>.
232
+ if (href && !href.startsWith('http') && !href.startsWith('#') && /\.md(#|$)/.test(href)) {
233
+ return (
234
+ <a
235
+ {...props}
236
+ href={href}
237
+ onClick={(e) => {
238
+ e.preventDefault();
239
+ onOpenFile(href);
240
+ }}
241
+ className="cursor-pointer"
242
+ >
243
+ {children}
244
+ </a>
245
+ );
246
+ }
247
+ if (href && /^https?:\/\//i.test(href)) {
248
+ return <a href={href} {...props} target="_blank" rel="noopener noreferrer">{children}</a>;
249
+ }
250
+ return <a href={href} {...props}>{children}</a>;
251
+ },
252
+ pre({ children, ...props }: { children?: React.ReactNode }) {
253
+ // Render a mermaid code block as a diagram.
254
+ const child = Array.isArray(children) ? children[0] : children;
255
+ if (
256
+ child && typeof child === 'object' && 'props' in child &&
257
+ typeof child.props.className === 'string' &&
258
+ child.props.className.includes('language-mermaid')
259
+ ) {
260
+ const code = String(child.props.children).replace(/\n$/, '');
261
+ return <MermaidDiagram code={code} />;
262
+ }
263
+ return <pre {...props}>{children}</pre>;
264
+ },
265
+ };
266
+ }, [onOpenFile, onOpenNodeId, headingLink]);
267
+
268
+ return (
269
+ <div className={`flex-1 overflow-auto ${className ?? ''}`} ref={containerRef}>
270
+ <FrontmatterPanel data={frontmatter} onOpenFile={onOpenFile} />
271
+ <div className="prose prose-sm max-w-none">
272
+ <Markdown
273
+ remarkPlugins={[remarkGfm, remarkFrontmatter]}
274
+ // rehype-raw parses inline HTML (e.g. the `<details>` "Source of
275
+ // Information" blocks in KB nodes) into real elements; rehype-sanitize
276
+ // runs after so enabling HTML doesn't open an XSS hole. rehype-slug
277
+ // runs LAST so the heading ids it adds survive sanitize's
278
+ // `user-content-` clobber prefix (which would break citation anchors).
279
+ rehypePlugins={[rehypeRaw, rehypeSanitize, rehypeSlug]}
280
+ components={components}
281
+ >
282
+ {normalizedBody}
283
+ </Markdown>
284
+ </div>
285
+ </div>
286
+ );
287
+ }