@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,99 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { renderHook } from '@testing-library/react';
3
+ import { GitContext, type GitContextValue } from '../../../git/state/git.context';
4
+ import { WorkspaceContext } from '../../state/workspace.context';
5
+ import { makeWorkspaceFixture } from '../../__tests__/testFixtures';
6
+ import { useFileNav } from '../kb-routes';
7
+
8
+ // Capture what openFile navigates to.
9
+ const navigateMock = vi.hoisted(() => vi.fn());
10
+ vi.mock('react-router-dom', () => ({
11
+ useNavigate: () => navigateMock,
12
+ }));
13
+
14
+ function gitOnBranch(branch: string): GitContextValue {
15
+ return {
16
+ status: { branch, hasUpstream: true, unmergedFromUpstream: false },
17
+ branches: [],
18
+ availability: 'ready',
19
+ lastError: null,
20
+ refreshStatus: async () => null,
21
+ refreshBranches: async () => {},
22
+ createBranch: async () => {},
23
+ deleteBranch: async () => {},
24
+ pull: async () => {},
25
+ fetchForkBase: async () => null,
26
+ revert: async () => ({ sha: 'a', authorName: 'n', authorEmail: 'e', subject: 's', committedAt: '2026-04-20T00:00:00.000Z' }),
27
+ fetchFileHistory: async () => [],
28
+ fetchFileDiff: async () => '',
29
+ fetchFileComparison: async () => '',
30
+ };
31
+ }
32
+
33
+ function renderNav(branch: string, kbDirName: string | null = 'knowledge-base') {
34
+ return renderHook(() => useFileNav(), {
35
+ wrapper: ({ children }) => (
36
+ <GitContext.Provider value={gitOnBranch(branch)}>
37
+ <WorkspaceContext.Provider value={makeWorkspaceFixture({ kbDirName })}>
38
+ {children}
39
+ </WorkspaceContext.Provider>
40
+ </GitContext.Provider>
41
+ ),
42
+ });
43
+ }
44
+
45
+ describe('useFileNav.openFile', () => {
46
+ it('preserves a heading anchor on a relative path instead of encoding the #', () => {
47
+ navigateMock.mockClear();
48
+ const { result } = renderNav('alice/draft');
49
+ result.current.openFile('Knowledge/Node.md#goal');
50
+ // The `#goal` survives as a real URL fragment; only the path segments are encoded.
51
+ expect(navigateMock).toHaveBeenCalledWith('/workspace/alice%2Fdraft/Knowledge/Node.md#goal');
52
+ });
53
+
54
+ it('preserves a heading anchor on an absolute workspace citation URL (with its own branch)', () => {
55
+ navigateMock.mockClear();
56
+ const { result } = renderNav('alice/draft');
57
+ result.current.openFile(
58
+ '/workspace/target-company-state/knowledge-base/GTM/NodeTypes/Bundle.md#status',
59
+ );
60
+ expect(navigateMock).toHaveBeenCalledWith(
61
+ '/workspace/target-company-state/knowledge-base/GTM/NodeTypes/Bundle.md#status',
62
+ );
63
+ });
64
+
65
+ it('routes an absolute workspace URL with no anchor unchanged', () => {
66
+ navigateMock.mockClear();
67
+ const { result } = renderNav('alice/draft');
68
+ result.current.openFile('/workspace/target-company-state/knowledge-base/x.md');
69
+ expect(navigateMock).toHaveBeenCalledWith(
70
+ '/workspace/target-company-state/knowledge-base/x.md',
71
+ );
72
+ });
73
+
74
+ // The model sometimes mangles a citation URL by inserting a junk segment
75
+ // before the KB dir (a blend of the branch + dir names). Self-heal by
76
+ // dropping everything before the `<kbDirName>/` segment so the link still
77
+ // resolves instead of 404ing.
78
+ it('strips a hallucinated junk segment before the kbDirName (absolute URL)', () => {
79
+ navigateMock.mockClear();
80
+ const { result } = renderNav('single-source-of-truth');
81
+ result.current.openFile(
82
+ '/workspace/single-source-of-truth/bevel-process-of-truth/knowledge-base/KnowledgeBase/Product/Knowledge/Bundles/functional/bdl-cpb-service-terms.md#id',
83
+ );
84
+ expect(navigateMock).toHaveBeenCalledWith(
85
+ '/workspace/single-source-of-truth/knowledge-base/KnowledgeBase/Product/Knowledge/Bundles/functional/bdl-cpb-service-terms.md#id',
86
+ );
87
+ });
88
+
89
+ it('leaves a well-formed path untouched and ignores a kbDirName substring match', () => {
90
+ navigateMock.mockClear();
91
+ const { result } = renderNav('alice/draft');
92
+ // `knowledge-base-backup` is NOT the repo dir — segment-exact match must
93
+ // not treat it as the marker, so the path is passed through unchanged.
94
+ result.current.openFile('/workspace/alice%2Fdraft/knowledge-base-backup/x.md');
95
+ expect(navigateMock).toHaveBeenCalledWith(
96
+ '/workspace/alice%2Fdraft/knowledge-base-backup/x.md',
97
+ );
98
+ });
99
+ });
@@ -0,0 +1,266 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { useNavigate } from 'react-router-dom';
3
+ import { useGit } from '../../git/state/git.context';
4
+ import { useWorkspace } from '../state/workspace.context';
5
+ import { authFetch } from '../../../lib/api';
6
+
7
+ export const KB_ROUTE_PREFIX = '/workspace';
8
+
9
+ /**
10
+ * Matches an id-link destination: a bare frontmatter id (`bdl-cpb-service-terms`,
11
+ * or a snake_case tool/skill id like `my_tool`), optionally followed by a heading
12
+ * anchor (`#id`, `#offer`). The id grammar (lowercase alphanumeric + hyphens +
13
+ * underscores) can't collide with a `.md` path, an `http(s):` URL, or a same-page
14
+ * `#anchor`; the anchor tail forbids `/` so a path link never matches.
15
+ */
16
+ export const NODE_ID_LINK_RE = /^[a-z0-9][a-z0-9_-]*(#[^/]+)?$/;
17
+
18
+ /**
19
+ * Self-heal a workspace-relative path the model may have mangled when it wrote
20
+ * a citation link. The LLM sometimes corrupts the URL by inserting a junk
21
+ * segment before the KB dir — e.g. `bevel-process-of-truth/knowledge-base/…`,
22
+ * a blend of the branch name and the dir name — which then 404s. A well-formed
23
+ * KB path has `<kbDirName>/` as its first segment, so when that segment shows up
24
+ * *later* in the path we drop everything before it. No-op when the path is
25
+ * already well-formed (kbDirName first) or has no `<kbDirName>` segment at all
26
+ * (a non-repo file like `my-notes.txt`). Segment-exact match avoids the
27
+ * `<kbDirName>-backup/…` substring foot-gun.
28
+ */
29
+ export function stripJunkBeforeKbDir(path: string, kbDirName: string | null): string {
30
+ if (!kbDirName) return path;
31
+ const segs = path.split('/');
32
+ const idx = segs.indexOf(kbDirName);
33
+ return idx > 0 ? segs.slice(idx).join('/') : path;
34
+ }
35
+
36
+ export function kbFileUrl(branch: string, relativePath: string = ''): string {
37
+ const branchPart = encodeURIComponent(branch);
38
+ if (!relativePath) return `${KB_ROUTE_PREFIX}/${branchPart}`;
39
+ const pathPart = relativePath
40
+ .split('/')
41
+ .map(encodeURIComponent)
42
+ .join('/');
43
+ return `${KB_ROUTE_PREFIX}/${branchPart}/${pathPart}`;
44
+ }
45
+
46
+ /**
47
+ * The canonical URL for a node: `/workspace/<branch>/<id>`. A bare id segment is
48
+ * disjoint from a `.md` path (no slash/dot — see `NODE_ID_LINK_RE`), so the route
49
+ * tells the two forms apart. `FileRoute` resolves the id to the underlying file.
50
+ */
51
+ export function kbNodeUrl(branch: string, id: string): string {
52
+ return `${KB_ROUTE_PREFIX}/${encodeURIComponent(branch)}/${encodeURIComponent(id)}`;
53
+ }
54
+
55
+ /**
56
+ * Resolve a node id → its workspace file path via the backend, or null when no
57
+ * readable node has that id (dangling/forbidden — the route 404s fail-closed).
58
+ */
59
+ export async function fetchNodeWorkspacePath(branch: string, id: string): Promise<string | null> {
60
+ try {
61
+ const r = await authFetch(
62
+ `/api/workspace/${encodeURIComponent(branch)}/resolve-id/${encodeURIComponent(id)}`,
63
+ );
64
+ if (!r.ok) return null;
65
+ const { workspacePath } = (await r.json()) as { workspacePath: string };
66
+ return workspacePath;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Short-lived memo for {@link fetchNodeId}. Its callers are per-render hooks
74
+ * (`useCanonicalFileUrl` in FileViewer + MarkdownRenderer) that remount on
75
+ * every content refresh — uncached, browsing fired the SAME `resolve-path`
76
+ * request over and over (visible as 404 spam for non-node files, which are a
77
+ * perfectly normal "no id" answer). The in-flight promise is shared so
78
+ * concurrent mounts dedupe, and a resolved answer — including the stable
79
+ * "not a node" null — is reused for the TTL. Network failures are evicted
80
+ * immediately so an offline blip doesn't stick.
81
+ */
82
+ const NODE_ID_TTL_MS = 30_000;
83
+ const nodeIdCache = new Map<string, { at: number; value: Promise<string | null> }>();
84
+
85
+ /**
86
+ * Reverse of {@link fetchNodeWorkspacePath}: a file's frontmatter id, or null when
87
+ * the file isn't an id-bearing node (or the caller may not read it). Used to
88
+ * canonicalize a path URL to the node's id URL.
89
+ */
90
+ export function fetchNodeId(branch: string, workspacePath: string): Promise<string | null> {
91
+ const key = `${branch}\n${workspacePath}`;
92
+ const now = Date.now();
93
+ const hit = nodeIdCache.get(key);
94
+ if (hit && now - hit.at < NODE_ID_TTL_MS) return hit.value;
95
+ const value = (async (): Promise<string | null> => {
96
+ const r = await authFetch(
97
+ `/api/workspace/${encodeURIComponent(branch)}/resolve-path?path=${encodeURIComponent(workspacePath)}`,
98
+ );
99
+ if (!r.ok) return null; // 404 = "not a node" — a stable, cacheable answer
100
+ const { id } = (await r.json()) as { id: string };
101
+ return id;
102
+ })();
103
+ const guarded = value.catch(() => {
104
+ nodeIdCache.delete(key);
105
+ return null;
106
+ });
107
+ nodeIdCache.set(key, { at: now, value: guarded });
108
+ return guarded;
109
+ }
110
+
111
+ /**
112
+ * The canonical absolute URL for a file, for the "copy link" affordances: a node's
113
+ * id URL (`<origin>/workspace/<branch>/<id>`) when the file is an id-bearing node,
114
+ * else its path URL. Resolves the id in the background and falls back to the path
115
+ * URL until it resolves (and permanently for non-node files). Null when there's no
116
+ * branch or path yet. Callers append any `#heading` themselves. This makes copied
117
+ * links id-based on their own, independent of the `FileRoute` path→id redirect.
118
+ */
119
+ export function useCanonicalFileUrl(workspacePath: string | null): string | null {
120
+ const git = useGit();
121
+ const branch = git.status?.branch ?? null;
122
+ // Tie the resolved id to the exact (branch, path) it was fetched for. Inputs
123
+ // change a render before the effect re-resolves, so without this key the URL
124
+ // would briefly pair the new path with the *previous* node's id.
125
+ const key = branch && workspacePath ? `${branch}\n${workspacePath}` : null;
126
+ const [resolved, setResolved] = useState<{ key: string; id: string | null } | null>(null);
127
+
128
+ useEffect(() => {
129
+ if (!key || !branch || !workspacePath) return;
130
+ let cancelled = false;
131
+ (async () => {
132
+ const id = await fetchNodeId(branch, workspacePath);
133
+ if (!cancelled) setResolved({ key, id });
134
+ })();
135
+ return () => {
136
+ cancelled = true;
137
+ };
138
+ }, [key, branch, workspacePath]);
139
+
140
+ if (!branch || !workspacePath) return null;
141
+ const nodeId = resolved && resolved.key === key ? resolved.id : null;
142
+ const relative = nodeId ? kbNodeUrl(branch, nodeId) : kbFileUrl(branch, workspacePath);
143
+ return `${window.location.origin}${relative}`;
144
+ }
145
+
146
+ function safeDecode(s: string): string {
147
+ try {
148
+ return decodeURIComponent(s);
149
+ } catch {
150
+ return s;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Resolve a relative path against a base file path (like `path.resolve`, but for
156
+ * workspace-relative paths). Used to turn an internal link's href
157
+ * (`../NodeTypes/Process.md`) into a workspace-relative path before navigating.
158
+ */
159
+ export function resolveRelativePath(basePath: string, relative: string): string {
160
+ // Root-relative hrefs (`/Knowledge/Node.md`) are anchored at the workspace
161
+ // root, not the current file — resolve against an empty base so the leading
162
+ // `/` doesn't get appended onto `baseDir` (`Knowledge/Knowledge/Node.md`).
163
+ const baseDir =
164
+ relative.startsWith('/')
165
+ ? ''
166
+ : basePath.includes('/')
167
+ ? basePath.slice(0, basePath.lastIndexOf('/'))
168
+ : '';
169
+ const parts = baseDir ? baseDir.split('/') : [];
170
+ for (const segment of relative.split('/')) {
171
+ if (segment === '..') parts.pop();
172
+ else if (segment !== '.' && segment !== '') parts.push(segment);
173
+ }
174
+ return parts.join('/');
175
+ }
176
+
177
+ export function useFileNav() {
178
+ const navigate = useNavigate();
179
+ const git = useGit();
180
+ const { kbDirName } = useWorkspace();
181
+ const branch = git.status?.branch ?? null;
182
+
183
+ const openFile = useCallback(
184
+ (pathOrUrl: string) => {
185
+ // Split off a trailing heading anchor (`…/Node.md#goal`) so it survives as
186
+ // a real URL fragment. Without this, `kbFileUrl` would percent-encode the
187
+ // `#` into the path (`Node.md%23goal`) and the deep-link scroll would never
188
+ // fire. The fragment is preserved verbatim and re-appended after the
189
+ // canonical file URL is built.
190
+ const hashIdx = pathOrUrl.indexOf('#');
191
+ const hash = hashIdx >= 0 ? pathOrUrl.slice(hashIdx) : '';
192
+ const path = hashIdx >= 0 ? pathOrUrl.slice(0, hashIdx) : pathOrUrl;
193
+
194
+ // Absolute workspace URLs (`/workspace/<branch>/<path>`) carry their
195
+ // own branch — never override with the current branch. Parse out the
196
+ // branch + path segments and re-route via kbFileUrl so encoding is
197
+ // canonical regardless of how the caller produced the URL (literal
198
+ // spaces, mixed encoding, etc.). FileRoute handles the actual git
199
+ // checkout if the URL's branch differs from the current one.
200
+ if (path.startsWith(`${KB_ROUTE_PREFIX}/`)) {
201
+ const rest = path.slice(KB_ROUTE_PREFIX.length + 1);
202
+ const slashIdx = rest.indexOf('/');
203
+ if (slashIdx < 0) {
204
+ navigate(kbFileUrl(safeDecode(rest)) + hash);
205
+ } else {
206
+ navigate(
207
+ kbFileUrl(
208
+ safeDecode(rest.slice(0, slashIdx)),
209
+ stripJunkBeforeKbDir(safeDecode(rest.slice(slashIdx + 1)), kbDirName),
210
+ ) + hash,
211
+ );
212
+ }
213
+ return;
214
+ }
215
+ if (!branch) return;
216
+ navigate(kbFileUrl(branch, stripJunkBeforeKbDir(path, kbDirName)) + hash);
217
+ },
218
+ [branch, kbDirName, navigate],
219
+ );
220
+
221
+ const closeFile = useCallback(() => {
222
+ if (!branch) return;
223
+ navigate(kbFileUrl(branch));
224
+ }, [branch, navigate]);
225
+
226
+ return { openFile, closeFile };
227
+ }
228
+
229
+ /**
230
+ * Navigate to a node referenced by its frontmatter id (`<id>` or `<id#heading>`).
231
+ * Resolves the id → its file location via the backend (the same `resolve-id`
232
+ * route the in-KB markdown renderer uses; it 404s fail-closed for ids the caller
233
+ * may not read), then opens the file, preserving any heading anchor as a real
234
+ * URL fragment so the deep-link scroll fires. Shared by the file renderer and
235
+ * the chat citation renderer so both resolve id-links identically.
236
+ */
237
+ export function useNodeIdNav() {
238
+ const { openFile } = useFileNav();
239
+ const git = useGit();
240
+ const branch = git.status?.branch ?? null;
241
+
242
+ const openNodeId = useCallback(
243
+ async (idOrLink: string) => {
244
+ if (!branch) return;
245
+ const hashIdx = idOrLink.indexOf('#');
246
+ const id = hashIdx >= 0 ? idOrLink.slice(0, hashIdx) : idOrLink;
247
+ const hash = hashIdx >= 0 ? idOrLink.slice(hashIdx) : '';
248
+ try {
249
+ const r = await authFetch(
250
+ `/api/workspace/${encodeURIComponent(branch)}/resolve-id/${encodeURIComponent(id)}`,
251
+ );
252
+ if (!r.ok) {
253
+ console.warn(`[useNodeIdNav] unresolved id-link '${id}' (HTTP ${r.status})`);
254
+ return;
255
+ }
256
+ const { workspacePath } = (await r.json()) as { workspacePath: string };
257
+ openFile(workspacePath + hash);
258
+ } catch (err) {
259
+ console.error('[useNodeIdNav] id-link resolve failed:', err);
260
+ }
261
+ },
262
+ [branch, openFile],
263
+ );
264
+
265
+ return { openNodeId };
266
+ }
@@ -0,0 +1,72 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ // Mock the shared auth fetch so we can drive arbitrary responses without a
4
+ // real network call. The module under test binds to this import at load.
5
+ vi.mock('../../../../lib/api', () => ({
6
+ authFetch: vi.fn(),
7
+ }));
8
+
9
+ import { uploadFile, createDirectory, WorkspaceApiError } from '../workspace.api';
10
+ import { authFetch } from '../../../../lib/api';
11
+
12
+ const mockedFetch = vi.mocked(authFetch);
13
+
14
+ /** Build a minimal `Response`-shaped stub for the not-OK paths. */
15
+ function notOk(status: number, body: unknown): Response {
16
+ return {
17
+ ok: false,
18
+ status,
19
+ json: async () => body,
20
+ } as unknown as Response;
21
+ }
22
+
23
+ describe('workspace.api write surface error handling', () => {
24
+ beforeEach(() => {
25
+ vi.clearAllMocks();
26
+ });
27
+
28
+ it('uploadFile surfaces the backend error body on 403, not a bare HTTP code', async () => {
29
+ mockedFetch.mockResolvedValueOnce(
30
+ notOk(403, { error: 'You don\'t have permission to write to "GTM/foo.pdf". Eligible: Admin.' }),
31
+ );
32
+ const file = new File(['hi'], 'foo.pdf');
33
+ await expect(uploadFile('target-company-state', 'foo.pdf', file)).rejects.toMatchObject({
34
+ status: 403,
35
+ message: 'You don\'t have permission to write to "GTM/foo.pdf". Eligible: Admin.',
36
+ });
37
+ });
38
+
39
+ it('uploadFile throws a WorkspaceApiError instance carrying the status', async () => {
40
+ mockedFetch.mockResolvedValueOnce(notOk(413, { error: 'File exceeds 52428800 byte limit' }));
41
+ const file = new File(['hi'], 'big.bin');
42
+ const err = await uploadFile('ws-1', 'big.bin', file).catch((e) => e);
43
+ expect(err).toBeInstanceOf(WorkspaceApiError);
44
+ expect(err.status).toBe(413);
45
+ expect(err.message).toBe('File exceeds 52428800 byte limit');
46
+ });
47
+
48
+ it('uploadFile falls back to the HTTP status when the body is not JSON', async () => {
49
+ mockedFetch.mockResolvedValueOnce({
50
+ ok: false,
51
+ status: 500,
52
+ json: async () => {
53
+ throw new Error('not json');
54
+ },
55
+ } as unknown as Response);
56
+ const file = new File(['hi'], 'x.md');
57
+ await expect(uploadFile('ws-1', 'x.md', file)).rejects.toMatchObject({
58
+ status: 500,
59
+ message: 'HTTP 500',
60
+ });
61
+ });
62
+
63
+ it('createDirectory also surfaces the backend error body on 403', async () => {
64
+ mockedFetch.mockResolvedValueOnce(
65
+ notOk(403, { error: 'You don\'t have permission to write to "GTM/sub". Eligible: Admin.' }),
66
+ );
67
+ await expect(createDirectory('target-company-state', 'sub')).rejects.toMatchObject({
68
+ status: 403,
69
+ message: 'You don\'t have permission to write to "GTM/sub". Eligible: Admin.',
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,185 @@
1
+ import type { WorkspaceInfo, FileTreeEntry } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+
4
+ /**
5
+ * Thrown by the workspace HTTP surface so callers can discriminate between
6
+ * 404 (file missing on the current branch — recoverable, render a not-found
7
+ * state), 401/403 (auth lapsed — bounce to login), and 5xx/network failures
8
+ * (transient — surface a "couldn't load" banner the user can retry). The
9
+ * previous `new Error('HTTP 404')` collapsed all of these into the same
10
+ * untyped string and forced FileRoute to assume "any error means missing."
11
+ */
12
+ export class WorkspaceApiError extends Error {
13
+ readonly status: number;
14
+ constructor(status: number, message?: string) {
15
+ super(message ?? `HTTP ${status}`);
16
+ this.name = 'WorkspaceApiError';
17
+ this.status = status;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Get-or-create the workspace for a branch. Workspaces are per-branch
23
+ * (PLAN §3) — every user editing the same branch shares the same
24
+ * backend workspace. Pass no argument to land on the platform default
25
+ * (target-company-state); pass a specific branch name to retarget.
26
+ *
27
+ * The returned `workspace.id` is `encodeURIComponent(branch)` and can be
28
+ * derived client-side without a round-trip — that's what every other
29
+ * `/workspace/:id/...` route expects. Callers who already know the
30
+ * branch can compute the id themselves, but going through this endpoint
31
+ * forces the backend to bootstrap (clone) the workspace if it's the
32
+ * first access, so it's the safer choice on initial load and on branch
33
+ * switches.
34
+ */
35
+ export async function getOrCreateWorkspace(
36
+ branch?: string,
37
+ ): Promise<{ workspace: WorkspaceInfo; fileTree: FileTreeEntry }> {
38
+ const qs = branch ? `?branch=${encodeURIComponent(branch)}` : '';
39
+ const res = await authFetch(`/api/workspace${qs}`);
40
+ if (!res.ok) throw new WorkspaceApiError(res.status);
41
+ return res.json();
42
+ }
43
+
44
+ export async function listFiles(workspaceId: string): Promise<FileTreeEntry> {
45
+ const res = await authFetch(`/api/workspace/${workspaceId}/files`);
46
+ if (!res.ok) throw new WorkspaceApiError(res.status);
47
+ return res.json();
48
+ }
49
+
50
+ export async function readFile(workspaceId: string, relativePath: string): Promise<string> {
51
+ // `_` cache-bust query parameter. The backend already sends
52
+ // `Cache-Control: no-store` on this route, but intermediate CDNs /
53
+ // service workers can ignore that header. A unique URL per request
54
+ // guarantees we hit the origin every time — important for the live
55
+ // refresh path where a teammate's save fires file-changed and we
56
+ // refetch milliseconds later (a stale response defeats the whole
57
+ // point of the SSE update).
58
+ const bust = `_=${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
59
+ const res = await authFetch(`/api/workspace/${workspaceId}/file?path=${encodeURIComponent(relativePath)}&${bust}`);
60
+ if (!res.ok) throw new WorkspaceApiError(res.status);
61
+ const data = await res.json();
62
+ return data.content;
63
+ }
64
+
65
+ export async function writeFile(workspaceId: string, relativePath: string, content: string): Promise<void> {
66
+ const res = await authFetch(`/api/workspace/${workspaceId}/file?path=${encodeURIComponent(relativePath)}`, {
67
+ method: 'PUT',
68
+ headers: { 'Content-Type': 'application/json' },
69
+ body: JSON.stringify({ content }),
70
+ });
71
+ if (!res.ok) throw await toApiError(res);
72
+ }
73
+
74
+ /**
75
+ * Turn a non-OK response into a `WorkspaceApiError` that carries the
76
+ * backend's `{ error }` body as its message. Without this the file-mutation
77
+ * routes threw a bare `Error('HTTP 403')`, so the file-explorer's
78
+ * "Couldn't add X" banner showed an opaque status code instead of the real
79
+ * reason (e.g. "You don't have permission to write to …"). Shared by every
80
+ * mutating route so the whole workspace API surfaces the backend message
81
+ * uniformly.
82
+ */
83
+ async function toApiError(res: Response): Promise<WorkspaceApiError> {
84
+ let msg = `HTTP ${res.status}`;
85
+ try {
86
+ const body = await res.json();
87
+ if (body?.error) msg = body.error;
88
+ } catch {
89
+ // body wasn't JSON — fall through with the HTTP status message
90
+ }
91
+ return new WorkspaceApiError(res.status, msg);
92
+ }
93
+
94
+ export async function createDirectory(
95
+ workspaceId: string,
96
+ relativePath: string,
97
+ options?: { defer?: boolean },
98
+ ): Promise<void> {
99
+ const res = await authFetch(`/api/workspace/${workspaceId}/directory`, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/json' },
102
+ body: JSON.stringify({ path: relativePath, defer: options?.defer }),
103
+ });
104
+ if (!res.ok) throw await toApiError(res);
105
+ }
106
+
107
+ export async function uploadFile(
108
+ workspaceId: string,
109
+ relativePath: string,
110
+ file: File,
111
+ options?: { defer?: boolean },
112
+ ): Promise<void> {
113
+ // `defer=true` opts into the batch path: the server commits but skips
114
+ // the per-file push + fs-tree event. The caller is responsible for
115
+ // following up with `flushBatch` once at the end of the burst.
116
+ const qs = `path=${encodeURIComponent(relativePath)}${options?.defer ? '&defer=true' : ''}`;
117
+ const res = await authFetch(`/api/workspace/${workspaceId}/upload?${qs}`, {
118
+ method: 'POST',
119
+ body: file,
120
+ });
121
+ if (!res.ok) throw await toApiError(res);
122
+ }
123
+
124
+ /**
125
+ * End-of-batch checkpoint for folder-upload bursts. Pushes all locally
126
+ * accumulated commits to origin in one round-trip and triggers a single
127
+ * `fs-tree-changed` event server-side. Pair with N `uploadFile(...,
128
+ * { defer: true })` (and any `createDirectory(..., { defer: true })`)
129
+ * calls. The HTTP response carries the same `PushNeedsAgentResolutionError`
130
+ * payload as a failed single-file save when the push hits a
131
+ * non-fast-forward / conflict path, so callers can surface the
132
+ * agent-handoff prompt the same way.
133
+ */
134
+ export async function flushBatch(
135
+ workspaceId: string,
136
+ targetPath?: string,
137
+ ): Promise<void> {
138
+ const res = await authFetch(`/api/workspace/${workspaceId}/flush`, {
139
+ method: 'POST',
140
+ headers: { 'Content-Type': 'application/json' },
141
+ body: JSON.stringify({ targetPath: targetPath ?? '.' }),
142
+ });
143
+ if (!res.ok) throw await toApiError(res);
144
+ }
145
+
146
+ export async function moveEntry(workspaceId: string, oldPath: string, newPath: string): Promise<void> {
147
+ const res = await authFetch(`/api/workspace/${workspaceId}/file`, {
148
+ method: 'PATCH',
149
+ headers: { 'Content-Type': 'application/json' },
150
+ body: JSON.stringify({ oldPath, newPath }),
151
+ });
152
+ if (!res.ok) throw await toApiError(res);
153
+ }
154
+
155
+ export async function deleteFile(workspaceId: string, relativePath: string): Promise<void> {
156
+ const res = await authFetch(`/api/workspace/${workspaceId}/file?path=${encodeURIComponent(relativePath)}`, {
157
+ method: 'DELETE',
158
+ });
159
+ if (!res.ok) throw await toApiError(res);
160
+ }
161
+
162
+ export interface UnzipResult {
163
+ destination: string;
164
+ extracted: string[];
165
+ skipped: { path: string; reason: string }[];
166
+ }
167
+
168
+ export async function unzipFile(
169
+ workspaceId: string,
170
+ zipPath: string,
171
+ destination?: string,
172
+ ): Promise<UnzipResult> {
173
+ const res = await authFetch(`/api/workspace/${workspaceId}/unzip`, {
174
+ method: 'POST',
175
+ headers: { 'Content-Type': 'application/json' },
176
+ body: JSON.stringify({ path: zipPath, destination }),
177
+ });
178
+ if (!res.ok) throw await toApiError(res);
179
+ return res.json();
180
+ }
181
+
182
+ export async function deleteWorkspace(workspaceId: string): Promise<void> {
183
+ const res = await authFetch(`/api/workspace/${workspaceId}`, { method: 'DELETE' });
184
+ if (!res.ok) throw await toApiError(res);
185
+ }