@bevel-software/platform-core-frontend 0.4.0 → 0.5.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 (326) hide show
  1. package/package.json +5 -3
  2. package/src/core/CoreAppShell.tsx +195 -56
  3. package/src/core/__tests__/AppChrome.test.tsx +125 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +130 -95
  5. package/src/core/__tests__/bootstrap.test.ts +63 -0
  6. package/src/core/bootstrap.ts +73 -0
  7. package/src/core/events.ts +12 -0
  8. package/src/core/registry.ts +58 -9
  9. package/src/index.css +100 -11
  10. package/src/index.ts +24 -23
  11. package/src/lib/utils.ts +114 -138
  12. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +281 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +166 -1
  14. package/src/modules/access/api.ts +49 -0
  15. package/src/modules/access/components/ManageAccessDialog.tsx +786 -481
  16. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  17. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +86 -0
  18. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +172 -156
  19. package/src/modules/admin/__tests__/admin.unread.test.tsx +61 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +44 -38
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +11 -10
  22. package/src/modules/admin/components/UserAccountsPage.tsx +361 -353
  23. package/src/modules/admin/state/admin.context.tsx +15 -6
  24. package/src/modules/auth/components/AccountPage.tsx +11 -11
  25. package/src/modules/auth/components/LoginScreen.tsx +12 -12
  26. package/src/modules/auth/services/sso.ts +47 -1
  27. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +277 -0
  28. package/src/modules/change-requests/__tests__/author.test.ts +48 -0
  29. package/src/modules/change-requests/__tests__/conflict.test.ts +73 -0
  30. package/src/modules/change-requests/__tests__/diff.test.ts +134 -0
  31. package/src/modules/change-requests/__tests__/propose.test.ts +93 -0
  32. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +72 -0
  33. package/src/modules/change-requests/change-requests.css +22 -0
  34. package/src/modules/change-requests/components/ChangeBox.tsx +277 -0
  35. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +713 -0
  36. package/src/modules/change-requests/components/ConflictHelp.tsx +47 -0
  37. package/src/modules/change-requests/components/CrFileTree.tsx +398 -0
  38. package/src/modules/change-requests/components/FileChangeBoxes.tsx +168 -0
  39. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +236 -0
  40. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +79 -0
  41. package/src/modules/change-requests/hooks/useFileOnBranch.ts +80 -0
  42. package/src/modules/change-requests/services/change-requests.api.ts +45 -0
  43. package/src/modules/change-requests/services/propose.api.ts +162 -0
  44. package/src/modules/change-requests/utils/author.ts +47 -0
  45. package/src/modules/change-requests/utils/conflict.ts +38 -0
  46. package/src/modules/change-requests/utils/diff.ts +80 -0
  47. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +27 -18
  48. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +36 -83
  49. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +5 -5
  50. package/src/modules/git/__tests__/PullRequestsForMe.test.tsx +147 -0
  51. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +2 -8
  52. package/src/modules/git/components/BranchSwitcher.tsx +68 -31
  53. package/src/modules/git/components/DiffView.tsx +4 -4
  54. package/src/modules/git/components/FileComparisonPanel.tsx +20 -20
  55. package/src/modules/git/components/FileHistoryPanel.tsx +71 -107
  56. package/src/modules/git/components/PullNeededBanner.tsx +6 -13
  57. package/src/modules/git/components/PullRequestsForMe.tsx +71 -36
  58. package/src/modules/git/components/UnifiedDiffView.tsx +4 -4
  59. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +2 -2
  60. package/src/modules/git/hooks/useGitState.ts +15 -14
  61. package/src/modules/git/services/__tests__/error-messages.test.ts +4 -4
  62. package/src/modules/git/services/error-messages.ts +7 -7
  63. package/src/modules/git/services/git.api.ts +17 -11
  64. package/src/modules/git/services/pr-prompts.ts +2 -2
  65. package/src/modules/git/state/git.context.ts +10 -1
  66. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +224 -0
  67. package/src/modules/layout/__tests__/SidebarToggle.test.tsx +242 -0
  68. package/src/modules/layout/__tests__/breakpoints.test.ts +56 -0
  69. package/src/modules/layout/breakpoints.ts +6 -0
  70. package/src/modules/layout/components/AppLayout.tsx +17 -5
  71. package/src/modules/layout/components/DemoBanner.tsx +10 -1
  72. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -104
  73. package/src/modules/layout/components/MobileChatLayout.tsx +31 -26
  74. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +59 -24
  75. package/src/modules/layout/components/SidebarFrame.tsx +317 -0
  76. package/src/modules/layout/components/SidebarToggle.tsx +86 -0
  77. package/src/modules/layout/components/SlideOverlay.tsx +1 -1
  78. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +40 -2
  79. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +19 -3
  80. package/src/modules/layout/state/sidebar.ts +200 -0
  81. package/src/modules/library/__tests__/AddToGroupDialog.test.tsx +313 -0
  82. package/src/modules/library/__tests__/ChangeRequestDock.test.tsx +84 -0
  83. package/src/modules/library/__tests__/GroupJoinRequests.test.tsx +178 -0
  84. package/src/modules/library/__tests__/GroupPage.test.tsx +479 -0
  85. package/src/modules/library/__tests__/GroupsIndexPage.test.tsx +283 -0
  86. package/src/modules/library/__tests__/GroupsSidebar.contextmenu.test.tsx +175 -0
  87. package/src/modules/library/__tests__/GroupsSidebar.locked.test.tsx +96 -0
  88. package/src/modules/library/__tests__/GroupsSidebar.test.tsx +142 -0
  89. package/src/modules/library/__tests__/GroupsSidebarMenu.test.tsx +142 -0
  90. package/src/modules/library/__tests__/LibraryCard.test.tsx +149 -0
  91. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +378 -0
  92. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +347 -0
  93. package/src/modules/library/__tests__/LockedGroupView.test.tsx +203 -0
  94. package/src/modules/library/__tests__/NewGroupDialog.test.tsx +114 -0
  95. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +177 -0
  96. package/src/modules/library/__tests__/SkillPage.test.tsx +1063 -0
  97. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +259 -0
  98. package/src/modules/library/__tests__/ToolLogo.test.tsx +63 -0
  99. package/src/modules/library/__tests__/ToolPage.test.tsx +315 -0
  100. package/src/modules/library/__tests__/ToolSharePanel.test.tsx +36 -0
  101. package/src/modules/library/__tests__/ToolVarRow.test.tsx +260 -0
  102. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +197 -0
  103. package/src/modules/library/__tests__/auth-harness.tsx +37 -0
  104. package/src/modules/library/__tests__/oauth-fragment.test.ts +48 -0
  105. package/src/modules/library/__tests__/status.test.ts +210 -117
  106. package/src/modules/library/__tests__/useSkillDetail.test.tsx +102 -0
  107. package/src/modules/library/__tests__/useToolPage.test.tsx +146 -0
  108. package/src/modules/library/components/AccessRequestsBanner.tsx +101 -0
  109. package/src/modules/library/components/AddToGroupDialog.tsx +115 -0
  110. package/src/modules/library/components/ChangeRequestDock.tsx +71 -47
  111. package/src/modules/library/components/DeleteGroupDialog.tsx +87 -0
  112. package/src/modules/library/components/GroupIndexRow.tsx +63 -0
  113. package/src/modules/library/components/GroupJoinRequests.tsx +56 -0
  114. package/src/modules/library/components/GroupPage.tsx +373 -0
  115. package/src/modules/library/components/GroupsIndexPage.tsx +222 -0
  116. package/src/modules/library/components/GroupsSidebar.tsx +338 -0
  117. package/src/modules/library/components/GroupsSidebarMenu.tsx +160 -0
  118. package/src/modules/library/components/LibraryCard.tsx +153 -132
  119. package/src/modules/library/components/LibraryLayout.tsx +344 -0
  120. package/src/modules/library/components/LibraryPage.tsx +138 -254
  121. package/src/modules/library/components/LockGlyph.tsx +31 -0
  122. package/src/modules/library/components/LockedGroupView.tsx +159 -0
  123. package/src/modules/library/components/ManagedGroupRequests.tsx +70 -0
  124. package/src/modules/library/components/NewGroupDialog.tsx +112 -0
  125. package/src/modules/library/components/NewSkillPanel.tsx +151 -0
  126. package/src/modules/library/components/PageActions.tsx +156 -0
  127. package/src/modules/library/components/PendingSkillReview.tsx +63 -0
  128. package/src/modules/library/components/PersonalAddDialog.tsx +88 -0
  129. package/src/modules/library/components/PersonalGroupPage.tsx +125 -0
  130. package/src/modules/library/components/StatusDot.tsx +25 -0
  131. package/src/modules/library/components/ToolLogo.tsx +171 -0
  132. package/src/modules/library/components/group-page-parts.tsx +419 -0
  133. package/src/modules/library/components/skill-page/SkillFileEditor.tsx +134 -0
  134. package/src/modules/library/components/skill-page/SkillFilePane.tsx +117 -0
  135. package/src/modules/library/components/skill-page/SkillFileTabs.tsx +112 -0
  136. package/src/modules/library/components/skill-page/SkillPage.tsx +673 -0
  137. package/src/modules/library/components/skill-page/tab-ids.ts +33 -0
  138. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +175 -0
  139. package/src/modules/library/components/tool-page/ToolPage.tsx +228 -0
  140. package/src/modules/library/components/tool-page/ToolSharePanel.tsx +45 -0
  141. package/src/modules/library/components/tool-page/ToolVarRow.tsx +289 -0
  142. package/src/modules/library/hooks/useJoinRequests.ts +114 -0
  143. package/src/modules/library/hooks/useLibraryData.ts +134 -119
  144. package/src/modules/library/hooks/useSkillDetail.ts +119 -74
  145. package/src/modules/library/hooks/useToolPage.ts +145 -0
  146. package/src/modules/library/library.css +108 -320
  147. package/src/modules/library/routes/LibraryRoutes.tsx +134 -0
  148. package/src/modules/library/routes/WorkspaceItemRoute.tsx +74 -0
  149. package/src/modules/library/routes/library-paths.ts +191 -0
  150. package/src/modules/library/services/groups.api.ts +189 -0
  151. package/src/modules/library/services/library.api.ts +291 -164
  152. package/src/modules/library/services/tools.api.ts +60 -0
  153. package/src/modules/library/state/library-context.ts +22 -0
  154. package/src/modules/library/state/library-data.tsx +223 -0
  155. package/src/modules/library/state/toast.context.ts +32 -0
  156. package/src/modules/library/state/toast.tsx +84 -42
  157. package/src/modules/library/utils/clipboard.ts +33 -0
  158. package/src/modules/library/utils/group-summary.ts +68 -0
  159. package/src/modules/library/utils/names.ts +30 -0
  160. package/src/modules/library/utils/navigate-external.ts +15 -0
  161. package/src/modules/library/utils/oauth-fragment.ts +32 -0
  162. package/src/modules/library/utils/personal-group.ts +36 -0
  163. package/src/modules/library/utils/status.ts +199 -116
  164. package/src/modules/library/utils/toast-duration.ts +16 -0
  165. package/src/modules/onboarding/__tests__/onboarding.test.tsx +533 -0
  166. package/src/modules/onboarding/agent-clients.ts +48 -0
  167. package/src/modules/onboarding/components/ConnectAgentPill.tsx +133 -0
  168. package/src/modules/onboarding/components/RootLanding.tsx +54 -0
  169. package/src/modules/onboarding/components/WelcomePage.tsx +364 -0
  170. package/src/modules/onboarding/paths.ts +9 -0
  171. package/src/modules/onboarding/state/onboarding.ts +191 -0
  172. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +10 -10
  173. package/src/modules/pr/services/pr-approvals.api.ts +19 -0
  174. package/src/modules/pr/services/pr-cancel.api.ts +11 -0
  175. package/src/modules/review/components/BinaryChangePlaceholder.tsx +3 -3
  176. package/src/modules/review/components/DiffViewer.tsx +4 -4
  177. package/src/modules/review/components/MarkdownDiffViewer.tsx +84 -26
  178. package/src/modules/review/components/ReviewFileRow.tsx +10 -10
  179. package/src/modules/review/components/ReviewPanel.tsx +49 -17
  180. package/src/modules/review/components/ReviewPanelSurface.tsx +1 -1
  181. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +122 -0
  182. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +1 -1
  183. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +273 -171
  184. package/src/modules/secrets-vault/components/SecretsPage.tsx +313 -276
  185. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +109 -92
  186. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +82 -51
  187. package/src/modules/secrets-vault/services/connect.api.ts +24 -3
  188. package/src/modules/settings/components/DeploymentPage.tsx +90 -0
  189. package/src/modules/settings/components/SettingsLayout.tsx +135 -0
  190. package/src/modules/settings/components/SettingsNav.tsx +114 -0
  191. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +110 -0
  192. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +249 -0
  193. package/src/modules/settings/settings-nav-items.tsx +166 -0
  194. package/src/modules/setup/__tests__/setup.test.tsx +540 -0
  195. package/src/modules/setup/components/SetupGate.tsx +67 -0
  196. package/src/modules/setup/components/SetupScreen.tsx +573 -0
  197. package/src/modules/setup/services/setup.api.ts +106 -0
  198. package/src/modules/setup/utils/git-host.ts +34 -0
  199. package/src/modules/toolbar/components/AppSwitcher.tsx +131 -108
  200. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -548
  201. package/src/modules/toolbar/components/ProfileMenu.tsx +294 -0
  202. package/src/modules/toolbar/components/Toolbar.tsx +56 -54
  203. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +176 -122
  204. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +252 -77
  205. package/src/modules/tools/ToolsExplorerPage.tsx +45 -40
  206. package/src/modules/workspace/__tests__/design-system-parity.test.ts +133 -0
  207. package/src/modules/workspace/__tests__/testFixtures.ts +2 -0
  208. package/src/modules/workspace/components/EditorTabs.tsx +82 -50
  209. package/src/modules/workspace/components/FileExplorer.tsx +1292 -1068
  210. package/src/modules/workspace/components/FilePaneCard.tsx +53 -0
  211. package/src/modules/workspace/components/FileRoute.tsx +89 -84
  212. package/src/modules/workspace/components/FileViewer.tsx +1312 -906
  213. package/src/modules/workspace/components/KbDocumentShell.tsx +138 -0
  214. package/src/modules/workspace/components/KbFileRail.tsx +128 -0
  215. package/src/modules/workspace/components/KbPageHeader.tsx +390 -0
  216. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +87 -3
  217. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +293 -39
  218. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +1 -16
  219. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +462 -44
  220. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +84 -0
  221. package/src/modules/workspace/components/__tests__/KbFileRail.test.tsx +83 -0
  222. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +192 -0
  223. package/src/modules/workspace/components/renderers/CopyAnchorButton.tsx +64 -0
  224. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +8 -8
  225. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +18 -9
  226. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +14 -14
  227. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +2 -2
  228. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +31 -165
  229. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +18 -5
  230. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +27 -10
  231. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +2 -2
  232. package/src/modules/workspace/components/renderers/TextRenderer.tsx +11 -5
  233. package/src/modules/workspace/components/renderers/ToolForm.tsx +24 -24
  234. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +27 -27
  235. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -11
  236. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +66 -0
  237. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +17 -1
  238. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +1 -1
  239. package/src/modules/workspace/components/renderers/__tests__/MermaidDiagram.test.tsx +58 -0
  240. package/src/modules/workspace/components/renderers/__tests__/lazyRenderer.test.tsx +68 -0
  241. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +64 -0
  242. package/src/modules/workspace/components/renderers/__tests__/sanitizeDocxHtml.test.ts +0 -0
  243. package/src/modules/workspace/components/renderers/chunk-boundary.tsx +71 -0
  244. package/src/modules/workspace/components/renderers/index.ts +78 -2
  245. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +241 -0
  246. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +59 -0
  247. package/src/modules/workspace/components/renderers/sanitizeDocxHtml.ts +91 -0
  248. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +59 -0
  249. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +237 -0
  250. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +185 -0
  251. package/src/modules/workspace/hooks/useAutoGrowTextarea.ts +30 -0
  252. package/src/modules/workspace/hooks/useLastCommit.ts +66 -0
  253. package/src/modules/workspace/hooks/useLinksOut.ts +56 -0
  254. package/src/modules/workspace/hooks/useOpenChangeRequests.ts +20 -0
  255. package/src/modules/workspace/hooks/useWorkspaceState.ts +123 -14
  256. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +1 -1
  257. package/src/modules/workspace/services/workspace.api.ts +9 -2
  258. package/src/modules/workspace/state/open-change-requests.context.ts +35 -0
  259. package/src/modules/workspace/state/open-change-requests.tsx +185 -0
  260. package/src/modules/workspace/state/workspace.context.ts +9 -0
  261. package/src/modules/workspace/utils/__tests__/diff.test.ts +87 -0
  262. package/src/modules/workspace/utils/diff.ts +130 -53
  263. package/src/modules/workspace/utils/fileTree.ts +182 -179
  264. package/src/modules/workspace/workspace.css +28 -0
  265. package/src/shared/components/Badge.tsx +62 -0
  266. package/src/shared/components/Banner.tsx +58 -0
  267. package/src/shared/components/Button.tsx +90 -0
  268. package/src/shared/components/Dialog.tsx +6 -6
  269. package/src/shared/components/Field.tsx +45 -0
  270. package/src/shared/components/IconButton.tsx +74 -0
  271. package/src/shared/components/ListRow.tsx +96 -0
  272. package/src/shared/components/Menu.tsx +88 -0
  273. package/src/shared/components/PageShell.tsx +54 -51
  274. package/src/shared/components/Surface.tsx +86 -0
  275. package/src/shared/components/__tests__/primitives.test.tsx +333 -0
  276. package/src/shared/components/index.ts +48 -0
  277. package/src/shared/components/useDismissableMenu.ts +71 -0
  278. package/src/shared/theme/__tests__/accent-contrast.test.ts +84 -0
  279. package/src/shared/theme/index.css +12 -0
  280. package/src/shared/theme/measure.ts +64 -0
  281. package/src/shared/theme/shadows.css +34 -0
  282. package/src/shared/theme/tokens.css +193 -0
  283. package/src/test-setup.ts +9 -0
  284. package/src/modules/access/components/AccessRestrictedBanner.tsx +0 -31
  285. package/src/modules/access/components/NodeOwnersBanner.tsx +0 -30
  286. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +0 -82
  287. package/src/modules/git/components/ProtectedBranchBanner.tsx +0 -42
  288. package/src/modules/library/__tests__/DetailDialog.test.tsx +0 -200
  289. package/src/modules/library/__tests__/diff.test.ts +0 -62
  290. package/src/modules/library/__tests__/loadout.test.tsx +0 -72
  291. package/src/modules/library/components/CompareView.tsx +0 -357
  292. package/src/modules/library/components/DetailDialog.tsx +0 -566
  293. package/src/modules/library/components/GearIcon.tsx +0 -12
  294. package/src/modules/library/components/LoadoutSidebar.tsx +0 -156
  295. package/src/modules/library/components/StatusGem.tsx +0 -21
  296. package/src/modules/library/components/SuggestChange.tsx +0 -171
  297. package/src/modules/library/components/particles.ts +0 -50
  298. package/src/modules/library/state/loadout.tsx +0 -129
  299. package/src/modules/library/utils/diff.ts +0 -102
  300. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +0 -93
  301. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +0 -158
  302. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +0 -44
  303. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +0 -360
  304. package/src/modules/pr/__tests__/bucketize-comments.test.ts +0 -85
  305. package/src/modules/pr/__tests__/parsePatch.test.ts +0 -104
  306. package/src/modules/pr/__tests__/usePrViewerState.test.ts +0 -72
  307. package/src/modules/pr/components/PrApprovalBadge.tsx +0 -80
  308. package/src/modules/pr/components/PrCancelButton.tsx +0 -99
  309. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +0 -119
  310. package/src/modules/pr/components/PrCommentComposer.tsx +0 -92
  311. package/src/modules/pr/components/PrCommentThread.tsx +0 -168
  312. package/src/modules/pr/components/PrCommentsPanel.tsx +0 -143
  313. package/src/modules/pr/components/PrDiffPane.tsx +0 -425
  314. package/src/modules/pr/components/PrFileRow.tsx +0 -164
  315. package/src/modules/pr/components/PrFilesList.tsx +0 -53
  316. package/src/modules/pr/components/PrHeader.tsx +0 -45
  317. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +0 -58
  318. package/src/modules/pr/components/PrMergeButton.tsx +0 -268
  319. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +0 -112
  320. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +0 -110
  321. package/src/modules/pr/components/PrViewer.tsx +0 -364
  322. package/src/modules/pr/hooks/usePrViewerState.ts +0 -150
  323. package/src/modules/pr/state/pr-viewer.context.ts +0 -34
  324. package/src/modules/pr/utils/bucketize-comments.ts +0 -55
  325. package/src/modules/pr/utils/parsePatch.ts +0 -57
  326. package/src/modules/toolbar/components/AdminMenu.tsx +0 -271
@@ -1,1068 +1,1292 @@
1
- import { useState, useCallback, useEffect, useMemo, useRef, createContext, useContext } from 'react';
2
- import {
3
- Folder,
4
- FolderOpen,
5
- ChevronRight,
6
- ChevronDown,
7
- FilePlus,
8
- FolderPlus,
9
- FolderUp,
10
- Trash2,
11
- Pencil,
12
- Upload,
13
- X,
14
- PackageOpen,
15
- Download,
16
- Loader2,
17
- Pin,
18
- PinOff,
19
- Users,
20
- } from 'lucide-react';
21
- import { Icon } from '@iconify/react';
22
- import type { FileTreeEntry } from '@bevel-software/platform-shared';
23
- import {
24
- validateFilename,
25
- KNOWLEDGE_BASE_DIR,
26
- SKILLS_DIR,
27
- TOOLS_DIR,
28
- DATA_DIR,
29
- AGENTS_DIR,
30
- PIPELINES_DIR,
31
- } from '@bevel-software/platform-shared';
32
- import { useWorkspace } from '../state/workspace.context';
33
- import { mergePendingIntoTree, findKbRoot, KB_ROOT_DIRS } from '../utils/fileTree';
34
- import { snapshotEntries } from '../utils/readDroppedEntries';
35
- import { useFileNav } from '../routing/kb-routes';
36
- import { authFetch } from '../../../lib/api';
37
- import { getFileIcon } from '../../../lib/utils';
38
- import { PullRequestsForMe } from '../../git/components/PullRequestsForMe';
39
- import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
40
- import { useAppRegistry } from '../../../core/registry';
41
-
42
- // ── Pinned folders (client-side, localStorage) ──
43
-
44
- const PINNED_STORAGE_KEY = 'bevel-pinned-folders';
45
-
46
- function readPinnedPaths(): string[] {
47
- if (typeof window === 'undefined') return [];
48
- try {
49
- const raw = window.localStorage.getItem(PINNED_STORAGE_KEY);
50
- const parsed = raw ? JSON.parse(raw) : [];
51
- return Array.isArray(parsed) ? parsed.filter((p): p is string => typeof p === 'string') : [];
52
- } catch {
53
- return [];
54
- }
55
- }
56
-
57
- interface PinnedController {
58
- isPinned: (path: string) => boolean;
59
- togglePin: (path: string) => void;
60
- }
61
-
62
- // Default no-op so a ContextMenu rendered outside the provider (e.g. in a unit
63
- // test) never throws — the real controller is supplied by FileExplorer.
64
- const PinnedContext = createContext<PinnedController>({
65
- isPinned: () => false,
66
- togglePin: () => {},
67
- });
68
- const usePinned = () => useContext(PinnedContext);
69
-
70
- // Lets the deep right-click menu open the Manage access sheet without prop
71
- // drilling through the recursive tree. FileExplorer supplies the opener and
72
- // renders the dialog.
73
- const ManageAccessContext = createContext<(entry: FileTreeEntry) => void>(() => {});
74
- const useManageAccess = () => useContext(ManageAccessContext);
75
-
76
- /** Depth-first lookup of a tree entry by its exact relativePath. */
77
- function findEntryByPath(node: FileTreeEntry, path: string): FileTreeEntry | null {
78
- if (node.relativePath === path) return node;
79
- if (!node.children) return null;
80
- for (const child of node.children) {
81
- const found = findEntryByPath(child, path);
82
- if (found) return found;
83
- }
84
- return null;
85
- }
86
-
87
- // ── Context Menu ──
88
-
89
- function ContextMenu({
90
- x,
91
- y,
92
- entry,
93
- isRoot,
94
- onClose,
95
- onCreateFile,
96
- onCreateFolder,
97
- onRename,
98
- onDownload,
99
- }: {
100
- x: number;
101
- y: number;
102
- entry: FileTreeEntry;
103
- isRoot: boolean;
104
- onClose: () => void;
105
- onCreateFile?: () => void;
106
- onCreateFolder?: () => void;
107
- onRename?: () => void;
108
- onDownload?: () => void;
109
- }) {
110
- const { deleteEntry, unzipHere } = useWorkspace();
111
- const { isPinned, togglePin } = usePinned();
112
- const openManageAccess = useManageAccess();
113
- const pinned = isPinned(entry.relativePath);
114
- const ref = useRef<HTMLDivElement>(null);
115
- const [unzipping, setUnzipping] = useState(false);
116
-
117
- // Only files whose name ends with `.zip` (case-insensitive) get the
118
- // extraction affordance — matches the OS shell-extension behavior users
119
- // already know from Windows Explorer / macOS Finder.
120
- const isZip = entry.type === 'file' && /\.zip$/i.test(entry.name);
121
-
122
- useEffect(() => {
123
- const handler = (e: MouseEvent) => {
124
- if (ref.current && !ref.current.contains(e.target as Node)) onClose();
125
- };
126
- document.addEventListener('mousedown', handler);
127
- return () => document.removeEventListener('mousedown', handler);
128
- }, [onClose]);
129
-
130
- const handleDelete = async () => {
131
- onClose();
132
- try {
133
- await deleteEntry(entry.relativePath);
134
- } catch (err) {
135
- console.error('Failed to delete entry:', err);
136
- const msg = err instanceof Error ? err.message : String(err);
137
- alert(`Failed to delete ${entry.relativePath}:\n${msg}`);
138
- }
139
- };
140
-
141
- const handleUnzip = async () => {
142
- if (unzipping) return;
143
- setUnzipping(true);
144
- try {
145
- const result = await unzipHere(entry.relativePath);
146
- onClose();
147
- // Surface a summary banner only when something was skipped — a silent
148
- // success is the right behavior for the happy path (matches Finder /
149
- // Explorer's "Extract here").
150
- if (result.skipped.length > 0) {
151
- const preview = result.skipped
152
- .slice(0, 5)
153
- .map((s) => ` - ${s.path}: ${s.reason}`)
154
- .join('\n');
155
- const more = result.skipped.length > 5 ? `\n …and ${result.skipped.length - 5} more` : '';
156
- alert(
157
- `Extracted ${result.extracted} file(s) from ${entry.name}.\n` +
158
- `Skipped ${result.skipped.length} entry(ies):\n${preview}${more}`,
159
- );
160
- }
161
- } catch (err) {
162
- console.error('Failed to unzip:', err);
163
- const msg = err instanceof Error ? err.message : String(err);
164
- alert(`Failed to unzip ${entry.name}:\n${msg}`);
165
- } finally {
166
- setUnzipping(false);
167
- }
168
- };
169
-
170
- return (
171
- <div
172
- ref={ref}
173
- className="fixed z-50 bg-slate-100 border border-slate-300 rounded-md shadow-xl py-1 min-w-[140px]"
174
- style={{ left: x, top: y }}
175
- onMouseDown={(e) => e.stopPropagation()}
176
- >
177
- {onCreateFile && (
178
- <button
179
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
180
- onClick={() => { onCreateFile(); onClose(); }}
181
- >
182
- <FilePlus size={14} />
183
- New file
184
- </button>
185
- )}
186
- {onCreateFolder && (
187
- <button
188
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
189
- onClick={() => { onCreateFolder(); onClose(); }}
190
- >
191
- <FolderPlus size={14} />
192
- New folder
193
- </button>
194
- )}
195
- {isZip && (
196
- <button
197
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80 disabled:opacity-60 disabled:cursor-not-allowed"
198
- onClick={handleUnzip}
199
- disabled={unzipping}
200
- >
201
- <PackageOpen size={14} />
202
- {unzipping ? 'Unzipping…' : 'Unzip here'}
203
- </button>
204
- )}
205
- {onDownload && (
206
- <button
207
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
208
- onClick={() => { onDownload(); onClose(); }}
209
- >
210
- <Download size={14} />
211
- {entry.type === 'directory' ? 'Download as zip' : 'Download'}
212
- </button>
213
- )}
214
- {!isRoot && (
215
- <>
216
- <div className="my-1 border-t border-slate-200/70" />
217
- <button
218
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-bevel-deep font-medium hover:bg-slate-200/80"
219
- onClick={() => { openManageAccess(entry); onClose(); }}
220
- >
221
- <Users size={14} />
222
- Manage access
223
- </button>
224
- </>
225
- )}
226
- {entry.type === 'directory' && !isRoot && (
227
- <button
228
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
229
- onClick={() => { togglePin(entry.relativePath); onClose(); }}
230
- >
231
- {pinned ? <PinOff size={14} /> : <Pin size={14} />}
232
- {pinned ? 'Unpin' : 'Pin to top'}
233
- </button>
234
- )}
235
- {!isRoot && onRename && (
236
- <button
237
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
238
- onClick={() => { onRename(); onClose(); }}
239
- >
240
- <Pencil size={14} />
241
- Rename
242
- </button>
243
- )}
244
- {!isRoot && (
245
- <button
246
- className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-red-600 hover:bg-slate-200/80"
247
- onClick={handleDelete}
248
- >
249
- <Trash2 size={14} />
250
- Delete
251
- </button>
252
- )}
253
- </div>
254
- );
255
- }
256
-
257
- // ── Inline Input ──
258
-
259
- function InlineInput({
260
- onSubmit,
261
- onCancel,
262
- placeholder,
263
- }: {
264
- onSubmit: (value: string) => void;
265
- onCancel: () => void;
266
- placeholder: string;
267
- }) {
268
- const [value, setValue] = useState('');
269
- const trimmed = value.trim();
270
- const error = trimmed.length === 0 ? null : validateFilename(trimmed);
271
- const valid = trimmed.length > 0 && error === null;
272
-
273
- const submit = () => {
274
- if (valid) onSubmit(trimmed);
275
- };
276
-
277
- return (
278
- <div className="w-full">
279
- <input
280
- autoFocus
281
- className={`w-full bg-slate-100 text-slate-900 text-sm px-2 py-0.5 rounded border outline-none ${
282
- error ? 'border-red-500' : 'border-slate-300 focus:border-slate-400'
283
- }`}
284
- placeholder={placeholder}
285
- value={value}
286
- onChange={(e) => setValue(e.target.value)}
287
- onKeyDown={(e) => {
288
- if (e.key === 'Enter') submit();
289
- if (e.key === 'Escape') onCancel();
290
- }}
291
- onBlur={() => {
292
- if (valid) onSubmit(trimmed);
293
- else onCancel();
294
- }}
295
- title={error ?? undefined}
296
- />
297
- {error && (
298
- <div className="text-[11px] text-red-700 mt-0.5 px-1">{error}</div>
299
- )}
300
- </div>
301
- );
302
- }
303
-
304
- // ── Rename Input ──
305
-
306
- function RenameInput({
307
- currentName,
308
- isFile,
309
- onSubmit,
310
- onCancel,
311
- }: {
312
- currentName: string;
313
- isFile: boolean;
314
- onSubmit: (value: string) => void;
315
- onCancel: () => void;
316
- }) {
317
- const [value, setValue] = useState(currentName);
318
- const trimmed = value.trim();
319
- const error = trimmed.length === 0 ? null : validateFilename(trimmed);
320
- const valid = trimmed.length > 0 && error === null;
321
-
322
- const submit = () => {
323
- if (valid && trimmed !== currentName) onSubmit(trimmed);
324
- else onCancel();
325
- };
326
-
327
- return (
328
- <div className="w-full">
329
- <input
330
- autoFocus
331
- className={`w-full bg-slate-100 text-slate-900 text-sm px-2 py-0.5 rounded border outline-none ${
332
- error ? 'border-red-500' : 'border-slate-300 focus:border-slate-400'
333
- }`}
334
- value={value}
335
- onClick={(e) => e.stopPropagation()}
336
- onMouseDown={(e) => e.stopPropagation()}
337
- onChange={(e) => setValue(e.target.value)}
338
- onKeyDown={(e) => {
339
- if (e.key === 'Enter') submit();
340
- if (e.key === 'Escape') onCancel();
341
- }}
342
- onBlur={submit}
343
- onFocus={(e) => {
344
- if (isFile) {
345
- // Select name without extension for files
346
- const dotIdx = currentName.lastIndexOf('.');
347
- if (dotIdx > 0) e.target.setSelectionRange(0, dotIdx);
348
- else e.target.select();
349
- } else {
350
- e.target.select();
351
- }
352
- }}
353
- title={error ?? undefined}
354
- />
355
- {error && (
356
- <div className="text-[11px] text-red-700 mt-0.5 px-1">{error}</div>
357
- )}
358
- </div>
359
- );
360
- }
361
-
362
- // ── Tree Node ──
363
-
364
- const DRAG_MIME = 'application/x-workspace-path';
365
-
366
- function FileTreeNode({
367
- entry,
368
- depth,
369
- initiallyExpanded,
370
- accent,
371
- collapseChildren,
372
- }: {
373
- entry: FileTreeEntry;
374
- depth: number;
375
- // Overrides the depth-based default for whether this node starts expanded.
376
- // The explorer's Knowledge/Skills roots use this so their own children start
377
- // collapsed regardless of depth (auto-reveal on deep links still wins).
378
- initiallyExpanded?: boolean;
379
- // Green-tints the folder icon + label — used for the Knowledge / Skills roots.
380
- accent?: boolean;
381
- // When set, this node's direct children start collapsed (so opening Knowledge
382
- // reveals the ontologies without cascading them all open).
383
- collapseChildren?: boolean;
384
- }) {
385
- const { openFilePath, createFile, createDirectory, dispatchUpload, isUploading, moveEntry, workspaceId, pendingUploads } = useWorkspace();
386
- const { openFile } = useFileNav();
387
-
388
- const handleDownload = useCallback(async () => {
389
- if (!workspaceId) return;
390
- // Files hit /file/raw; folders hit /folder/zip and arrive as <name>.zip.
391
- // Both endpoints share the same per-path `download:` access gate, the
392
- // same `?download=1` flag shape, and the same Content-Disposition
393
- // handling on the backend — branching here just picks the URL.
394
- // No preflight: a 403 surfaces in the alert below.
395
- const isFolder = entry.type === 'directory';
396
- const url = isFolder
397
- ? `/api/workspace/${workspaceId}/folder/zip?path=${encodeURIComponent(entry.relativePath)}&download=1`
398
- : `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(entry.relativePath)}&download=1`;
399
- const savedAs = isFolder ? `${entry.name}.zip` : entry.name;
400
- try {
401
- const res = await authFetch(url);
402
- if (!res.ok) {
403
- const body = await res.text().catch(() => '');
404
- alert(`Failed to download ${entry.name} (HTTP ${res.status})${body ? `: ${body}` : ''}`);
405
- return;
406
- }
407
- const blob = await res.blob();
408
- const blobUrl = URL.createObjectURL(blob);
409
- const a = document.createElement('a');
410
- a.href = blobUrl;
411
- a.download = savedAs;
412
- document.body.appendChild(a);
413
- a.click();
414
- a.remove();
415
- URL.revokeObjectURL(blobUrl);
416
- } catch (err) {
417
- console.error('Failed to download:', err);
418
- const msg = err instanceof Error ? err.message : String(err);
419
- alert(`Failed to download ${entry.name}:\n${msg}`);
420
- }
421
- }, [workspaceId, entry.relativePath, entry.name, entry.type]);
422
- // `null` = no explicit user intent; fall through to the auto-expand / depth
423
- // default. Once the user clicks the chevron, intent wins over auto-expand
424
- // until the auto-expand trigger transitions (new file opened, new upload),
425
- // at which point intent is reset and auto-expand takes over again.
426
- const [userIntent, setUserIntent] = useState<boolean | null>(null);
427
- const [creating, setCreating] = useState<'file' | 'directory' | null>(null);
428
- const [renaming, setRenaming] = useState(false);
429
- const [dragOver, setDragOver] = useState(false);
430
- // Only the root row uses these refs, but hooks must run unconditionally.
431
- const rootFileInputRef = useRef<HTMLInputElement>(null);
432
- const rootFolderInputRef = useRef<HTMLInputElement>(null);
433
-
434
- const handleRootUploadClick = useCallback((e: React.MouseEvent) => {
435
- e.stopPropagation();
436
- rootFileInputRef.current?.click();
437
- }, []);
438
-
439
- const handleRootFolderClick = useCallback((e: React.MouseEvent) => {
440
- e.stopPropagation();
441
- rootFolderInputRef.current?.click();
442
- }, []);
443
-
444
- // Resetting `value` after dispatch lets users re-select the same file and
445
- // still get an `onChange` event the second time around.
446
- const handleRootFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
447
- const files = Array.from(e.target.files ?? []);
448
- e.target.value = '';
449
- if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
450
- }, [dispatchUpload]);
451
-
452
- // Folder picker: each File carries a `webkitRelativePath` like
453
- // "foldername/sub/file.txt" — we feed those straight into the upload
454
- // pipeline as pre-resolved paths. Note: `<input webkitdirectory>` only
455
- // enumerates files (the browser hides empty subdirs from us), so empty
456
- // folders are only preserved via the drag-and-drop path that uses the
457
- // FileSystem entries API.
458
- const handleRootFolderChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
459
- const files = Array.from(e.target.files ?? []);
460
- e.target.value = '';
461
- if (files.length === 0) return;
462
- const items = files.map((file) => ({
463
- file,
464
- relativePath: file.webkitRelativePath || file.name,
465
- }));
466
- dispatchUpload({ kind: 'paths', items }, '');
467
- }, [dispatchUpload]);
468
- const [dragging, setDragging] = useState(false);
469
- const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
470
-
471
- const paddingLeft = 12 + depth * 16;
472
- const isRoot = entry.relativePath === '.';
473
- const isPending = pendingUploads.has(entry.relativePath);
474
-
475
- // Auto-expand a directory whenever the open file lives inside it (so
476
- // deep-link URLs reveal the file's row in the tree) or while files
477
- // dropped under it are still uploading (so the user can watch them
478
- // fill in).
479
- const isOpenFileAncestor = entry.type === 'directory' && !!openFilePath && (
480
- isRoot || openFilePath.startsWith(entry.relativePath + '/')
481
- );
482
- const autoExpanded = entry.type === 'directory' && (isPending || isOpenFileAncestor);
483
-
484
- // Fingerprint of what currently drives auto-expand. When it transitions
485
- // (different file opened, upload starts), the user's prior collapse intent
486
- // is stale — reset so deep-links / new uploads can re-reveal the folder.
487
- const autoTrigger = `${isPending ? 'P' : ''}|${isOpenFileAncestor ? openFilePath : ''}`;
488
- const prevAutoTriggerRef = useRef(autoTrigger);
489
- useEffect(() => {
490
- if (prevAutoTriggerRef.current !== autoTrigger) {
491
- prevAutoTriggerRef.current = autoTrigger;
492
- setUserIntent(null);
493
- }
494
- }, [autoTrigger]);
495
-
496
- const isExpanded = userIntent ?? (autoExpanded || (initiallyExpanded ?? depth < 2));
497
-
498
- const handleContextMenu = useCallback((e: React.MouseEvent) => {
499
- e.preventDefault();
500
- e.stopPropagation();
501
- setContextMenu({ x: e.clientX, y: e.clientY });
502
- }, []);
503
-
504
- // ── Drag source (internal reorder) ──
505
- const handleDragStart = useCallback((e: React.DragEvent) => {
506
- if (isRoot) { e.preventDefault(); return; }
507
- e.dataTransfer.setData(DRAG_MIME, entry.relativePath);
508
- e.dataTransfer.effectAllowed = 'move';
509
- setDragging(true);
510
- }, [entry.relativePath, isRoot]);
511
-
512
- const handleDragEnd = useCallback(() => {
513
- setDragging(false);
514
- }, []);
515
-
516
- // ── Drop target ──
517
- const handleDrop = useCallback(
518
- (e: React.DragEvent) => {
519
- e.preventDefault();
520
- e.stopPropagation();
521
- setDragOver(false);
522
-
523
- // Internal move (reorder)
524
- const sourcePath = e.dataTransfer.getData(DRAG_MIME);
525
- if (sourcePath) {
526
- const targetDir = entry.type === 'directory'
527
- ? (isRoot ? '' : entry.relativePath)
528
- : '';
529
- const name = sourcePath.split('/').pop()!;
530
- const newPath = targetDir ? `${targetDir}/${name}` : name;
531
- // Skip no-op or nesting a directory inside itself
532
- if (
533
- newPath === sourcePath ||
534
- targetDir === sourcePath ||
535
- targetDir.startsWith(sourcePath + '/')
536
- ) {
537
- return;
538
- }
539
- moveEntry(sourcePath, newPath);
540
- return;
541
- }
542
-
543
- // External file/folder drop. Snapshot the entries synchronously
544
- // before any await — the browser invalidates `DataTransfer` once the
545
- // handler returns, and the walker awaits inside.
546
- const dir = entry.type === 'directory' ? entry.relativePath : '';
547
- const targetDir = dir === '.' ? '' : dir;
548
- const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
549
- if (entries.length > 0) {
550
- dispatchUpload({ kind: 'items', entries }, targetDir);
551
- return;
552
- }
553
- // Fallback for older browsers / non-entry drops: use the flat FileList.
554
- const files = Array.from(e.dataTransfer.files);
555
- if (files.length === 0) return;
556
- dispatchUpload({ kind: 'files', files }, targetDir);
557
- },
558
- [entry, isRoot, dispatchUpload, moveEntry],
559
- );
560
-
561
- const handleDragOver = useCallback((e: React.DragEvent) => {
562
- e.preventDefault();
563
- e.stopPropagation();
564
- if (entry.type === 'directory') {
565
- e.dataTransfer.dropEffect = 'move';
566
- setDragOver(true);
567
- }
568
- }, [entry.type]);
569
-
570
- const handleDragLeave = useCallback((e: React.DragEvent) => {
571
- e.preventDefault();
572
- e.stopPropagation();
573
- setDragOver(false);
574
- }, []);
575
-
576
- if (entry.type === 'directory') {
577
- const dirPath = isRoot ? '' : entry.relativePath;
578
- return (
579
- <div>
580
- <div
581
- className={`flex items-center gap-1 w-full text-left py-1 px-2 text-sm text-slate-700 hover:bg-slate-100/70 rounded group transition-colors duration-150 ${
582
- dragOver ? 'bg-slate-200/60 ring-1 ring-bevel/50' : ''
583
- }`}
584
- style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
585
- draggable={!isRoot && !renaming && !isPending}
586
- onDragStart={handleDragStart}
587
- onDragEnd={handleDragEnd}
588
- onDrop={handleDrop}
589
- onDragOver={handleDragOver}
590
- onDragLeave={handleDragLeave}
591
- onContextMenu={handleContextMenu}
592
- >
593
- <button
594
- className="flex items-center gap-1.5 flex-1 min-w-0"
595
- onClick={() => setUserIntent(!isExpanded)}
596
- >
597
- {isExpanded ? (
598
- <ChevronDown size={14} className="text-slate-600 shrink-0" />
599
- ) : (
600
- <ChevronRight size={14} className="text-slate-600 shrink-0" />
601
- )}
602
- {isExpanded ? (
603
- <FolderOpen size={14} className={`shrink-0 ${accent ? 'text-emerald-600' : 'text-slate-600'}`} />
604
- ) : (
605
- <Folder size={14} className={`shrink-0 ${accent ? 'text-emerald-600' : 'text-slate-600'}`} />
606
- )}
607
- {renaming ? (
608
- <RenameInput
609
- currentName={entry.name}
610
- isFile={false}
611
- onSubmit={async (newName) => {
612
- const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
613
- const newPath = parentDir ? `${parentDir}/${newName}` : newName;
614
- // Close the input BEFORE the fallible move — see the create
615
- // flow: on error the alert() blurs the still-mounted input,
616
- // whose onBlur re-fires this onSubmit, looping the popup.
617
- setRenaming(false);
618
- try {
619
- await moveEntry(entry.relativePath, newPath);
620
- } catch (err) {
621
- // Same surfacing as the create flow above — a silent failure
622
- // reads as the rename being accepted and then reverting.
623
- const msg = err instanceof Error ? err.message : String(err);
624
- alert(`Failed to rename ${entry.name}:\n${msg}`);
625
- }
626
- }}
627
- onCancel={() => setRenaming(false)}
628
- />
629
- ) : (
630
- <span className={`truncate ${accent ? 'text-emerald-700 font-medium' : ''}`}>{entry.name}</span>
631
- )}
632
- </button>
633
- <div className="hidden group-hover:flex group-focus-within:flex items-center gap-0.5 shrink-0">
634
- <button
635
- className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-700"
636
- title="New file"
637
- onClick={(e) => {
638
- e.stopPropagation();
639
- setUserIntent(true);
640
- setCreating('file');
641
- }}
642
- >
643
- <FilePlus size={13} />
644
- </button>
645
- <button
646
- className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-700"
647
- title="New folder"
648
- onClick={(e) => {
649
- e.stopPropagation();
650
- setUserIntent(true);
651
- setCreating('directory');
652
- }}
653
- >
654
- <FolderPlus size={13} />
655
- </button>
656
- </div>
657
- {isRoot && (
658
- <>
659
- <button
660
- type="button"
661
- className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-900 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
662
- title="Add files"
663
- aria-label="Add files"
664
- disabled={isUploading}
665
- onClick={handleRootUploadClick}
666
- >
667
- <Upload size={13} />
668
- </button>
669
- <input
670
- ref={rootFileInputRef}
671
- type="file"
672
- multiple
673
- hidden
674
- aria-hidden="true"
675
- data-testid="file-explorer-file-input"
676
- onChange={handleRootFileChange}
677
- />
678
- <button
679
- type="button"
680
- className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-900 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
681
- title="Add folder"
682
- aria-label="Add folder"
683
- disabled={isUploading}
684
- onClick={handleRootFolderClick}
685
- >
686
- <FolderUp size={13} />
687
- </button>
688
- <input
689
- ref={rootFolderInputRef}
690
- type="file"
691
- multiple
692
- webkitdirectory=""
693
- hidden
694
- aria-hidden="true"
695
- data-testid="file-explorer-folder-input"
696
- onChange={handleRootFolderChange}
697
- />
698
- </>
699
- )}
700
- </div>
701
- {isExpanded && (
702
- <div>
703
- {creating && (
704
- <div style={{ paddingLeft: paddingLeft + 34 }} className="py-0.5 px-2">
705
- <InlineInput
706
- placeholder={creating === 'file' ? 'filename' : 'folder name'}
707
- onSubmit={async (name) => {
708
- const fullPath = dirPath ? `${dirPath}/${name}` : name;
709
- const kind = creating;
710
- // Close the inline input BEFORE anything can fail. On
711
- // error the alert() below steals focus; leaving the input
712
- // mounted means dismissing the alert blurs it, and the
713
- // input's onBlur re-fires this same onSubmit — an infinite
714
- // "Failed to create …" popup loop against an unchanging
715
- // 403. Unmounting first breaks that cycle.
716
- setCreating(null);
717
- try {
718
- if (kind === 'file') await createFile(fullPath);
719
- else await createDirectory(fullPath);
720
- } catch (err) {
721
- // Surface the refusal (e.g. a protected branch's write
722
- // gate: "You don't have permission to write to …") —
723
- // otherwise the input clears and nothing appears, which
724
- // reads as the file silently vanishing.
725
- const msg = err instanceof Error ? err.message : String(err);
726
- alert(`Failed to create ${name}:\n${msg}`);
727
- }
728
- }}
729
- onCancel={() => setCreating(null)}
730
- />
731
- </div>
732
- )}
733
- {entry.children?.map((child) => (
734
- <FileTreeNode
735
- key={child.relativePath}
736
- entry={child}
737
- depth={depth + 1}
738
- initiallyExpanded={collapseChildren ? false : undefined}
739
- />
740
- ))}
741
- </div>
742
- )}
743
- {contextMenu && (
744
- <ContextMenu
745
- x={contextMenu.x}
746
- y={contextMenu.y}
747
- entry={entry}
748
- isRoot={isRoot}
749
- onClose={() => setContextMenu(null)}
750
- onCreateFile={() => { setUserIntent(true); setCreating('file'); }}
751
- onCreateFolder={() => { setUserIntent(true); setCreating('directory'); }}
752
- onRename={() => setRenaming(true)}
753
- onDownload={handleDownload}
754
- />
755
- )}
756
- </div>
757
- );
758
- }
759
-
760
- const isActive = entry.relativePath === openFilePath;
761
- const iconName = getFileIcon(entry.name);
762
-
763
- return (
764
- <>
765
- <button
766
- className={`flex items-center gap-1.5 w-full text-left py-1 px-2 text-sm rounded transition-colors duration-150 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-bevel/60 ${
767
- isActive
768
- ? 'bg-slate-200/80 text-slate-900'
769
- : 'text-slate-600 hover:bg-slate-100/70 hover:text-slate-900'
770
- } ${isPending ? 'cursor-progress' : ''}`}
771
- style={{ paddingLeft: paddingLeft + 18, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
772
- draggable={!renaming && !isPending}
773
- onDragStart={handleDragStart}
774
- onDragEnd={handleDragEnd}
775
- onClick={() => { if (!renaming && !isPending) openFile(entry.relativePath); }}
776
- onContextMenu={handleContextMenu}
777
- title={isPending ? 'Adding…' : undefined}
778
- >
779
- {isPending ? (
780
- <Loader2 size={14} className="shrink-0 animate-spin text-slate-500" />
781
- ) : (
782
- <Icon
783
- icon={`material-icon-theme:${iconName}`}
784
- width={16}
785
- height={16}
786
- className="shrink-0"
787
- />
788
- )}
789
- {renaming ? (
790
- <RenameInput
791
- currentName={entry.name}
792
- isFile={true}
793
- onSubmit={async (newName) => {
794
- const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
795
- const newPath = parentDir ? `${parentDir}/${newName}` : newName;
796
- // Close the input BEFORE the fallible move — see the create
797
- // flow: on error the alert() blurs the still-mounted input,
798
- // whose onBlur re-fires this onSubmit, looping the popup.
799
- setRenaming(false);
800
- try {
801
- await moveEntry(entry.relativePath, newPath);
802
- } catch (err) {
803
- // Same surfacing as the create flow — a silent failure reads
804
- // as the rename being accepted and then reverting.
805
- const msg = err instanceof Error ? err.message : String(err);
806
- alert(`Failed to rename ${entry.name}:\n${msg}`);
807
- }
808
- }}
809
- onCancel={() => setRenaming(false)}
810
- />
811
- ) : (
812
- <span className="truncate">{entry.name}</span>
813
- )}
814
- </button>
815
- {contextMenu && (
816
- <ContextMenu
817
- x={contextMenu.x}
818
- y={contextMenu.y}
819
- entry={entry}
820
- isRoot={false}
821
- onClose={() => setContextMenu(null)}
822
- onRename={() => setRenaming(true)}
823
- onDownload={handleDownload}
824
- />
825
- )}
826
- </>
827
- );
828
- }
829
-
830
- // ── Explorer Root ──
831
-
832
- /**
833
- * Walk down to the node that actually holds the KB content. The file tree roots
834
- * at the per-branch workspace dir and wraps the KB clone a level or two deep
835
- * (`<branch>/<kbDir>/{KnowledgeBase,Data,Agents,Pipelines,Skills,Tools,…}`), so
836
- * the split lives below the visible root. Returns the first node whose children
837
- * include one of those well-known root directories, or null when there's no
838
- * such split (legacy clones).
839
- */
840
- // (`findKbRoot` lives in `../utils/fileTree` — shared with registry-
841
- // contributed explorer items.)
842
-
843
- export function FileExplorer() {
844
- const { fileTree, dispatchUpload, uploadError, clearUploadError, pendingUploads } = useWorkspace();
845
- const [dragOver, setDragOver] = useState(false);
846
- // Download is now a per-path permission (resolved server-side from the
847
- // access tree's `download:` verb), so there's no global preflight gate
848
- // here anymore. The menu items always render; if the user clicks on a
849
- // file they don't have download permission for, the backend returns 403
850
- // and `handleDownload` shows the error.
851
- // Optimistic overlay: every dropped/picked file shows up in the tree
852
- // within a frame, even before its commit echoes back from the server.
853
- const mergedTree = useMemo(
854
- () => (fileTree ? mergePendingIntoTree(fileTree, pendingUploads) : null),
855
- [fileTree, pendingUploads],
856
- );
857
-
858
- // Pinned folders — a personal, client-side shortcut list surfaced at the top
859
- // of the explorer. Stored as relativePaths in localStorage; toggled from the
860
- // right-click menu (Pin to top / Unpin).
861
- const [pinnedPaths, setPinnedPaths] = useState<string[]>(readPinnedPaths);
862
- const togglePin = useCallback((path: string) => {
863
- setPinnedPaths((prev) => {
864
- const next = prev.includes(path) ? prev.filter((p) => p !== path) : [...prev, path];
865
- try {
866
- window.localStorage.setItem(PINNED_STORAGE_KEY, JSON.stringify(next));
867
- } catch {
868
- // localStorage unavailable — pins stay in memory for this session.
869
- }
870
- return next;
871
- });
872
- }, []);
873
- const pinnedController = useMemo<PinnedController>(
874
- () => ({ isPinned: (path) => pinnedPaths.includes(path), togglePin }),
875
- [pinnedPaths, togglePin],
876
- );
877
- // Resolve pinned paths to live tree entries, dropping any that no longer
878
- // exist on this branch (a folder pinned elsewhere may be absent here).
879
- const pinnedEntries = useMemo(
880
- () =>
881
- mergedTree
882
- ? pinnedPaths
883
- .map((p) => findEntryByPath(mergedTree, p))
884
- .filter((e): e is FileTreeEntry => e != null)
885
- : [],
886
- [mergedTree, pinnedPaths],
887
- );
888
-
889
- // Registry-contributed rows for the Pinned section (rendered below the
890
- // pinned folders). The enterprise knowledge system contributes its
891
- // "Graph view" entry — the interactive ontology graph — this way; the core
892
- // ships none of its own.
893
- const { explorerItems } = useAppRegistry();
894
-
895
- // Right-click → Manage access opens this sheet for the chosen entry.
896
- const [accessTarget, setAccessTarget] = useState<FileTreeEntry | null>(null);
897
-
898
- // KB content splits Knowledge (`KnowledgeBase/`), Data (`Data/`), Agents
899
- // (`Agents/`), Pipelines (`Pipelines/`), Skills (`Skills/`) and Tools
900
- // (`Tools/`) into separate top-level folders; surface them as labelled sections
901
- // rather than a single flat root. The Knowledge section hoists `KnowledgeBase/`'s
902
- // children and folds in any other top-level content folder (e.g. a stray
903
- // `Legal/`); loose top-level files (access.md, roles.yaml) sit below a divider.
904
- // Clones that predate the split (none of the well-known root dirs) fall back
905
- // to the flat tree.
906
- const sections = useMemo(() => {
907
- // Descend past the workspace / KB-clone wrapper levels to the node that
908
- // actually holds the well-known root dirs, then split that level.
909
- const kids = findKbRoot(mergedTree)?.children;
910
- if (!kids) return null;
911
- const findDir = (name: string) =>
912
- kids.find((c) => c.type === 'directory' && c.name === name);
913
- const knowledgeBase = findDir(KNOWLEDGE_BASE_DIR);
914
- const data = findDir(DATA_DIR);
915
- const agents = findDir(AGENTS_DIR);
916
- const pipelines = findDir(PIPELINES_DIR);
917
- const skills = findDir(SKILLS_DIR);
918
- const tools = findDir(TOOLS_DIR);
919
- if (!knowledgeBase && !data && !agents && !pipelines && !skills && !tools) return null;
920
- // Any other top-level content folder (e.g. a stray `Legal/`) folds into Knowledge.
921
- const otherDirs = kids.filter(
922
- (c) => c.type === 'directory' && !KB_ROOT_DIRS.has(c.name),
923
- );
924
- // Present Knowledge, Data, Agents, Pipelines, Skills and Tools as named
925
- // roots. Knowledge is synthetic so it can relabel `KnowledgeBase` and
926
- // absorb the stray content folders; it reuses KnowledgeBase's own path so
927
- // file ops on the row still resolve.
928
- const knowledge: FileTreeEntry | null = knowledgeBase
929
- ? {
930
- ...knowledgeBase,
931
- name: 'Knowledge',
932
- children: [...(knowledgeBase.children ?? []), ...otherDirs],
933
- }
934
- : otherDirs.length > 0
935
- ? { name: 'Knowledge', relativePath: otherDirs[0].relativePath, type: 'directory', children: otherDirs }
936
- : null;
937
- const dataRoot: FileTreeEntry | null = data ? { ...data, name: DATA_DIR } : null;
938
- const agentsRoot: FileTreeEntry | null = agents ? { ...agents, name: AGENTS_DIR } : null;
939
- const pipelinesRoot: FileTreeEntry | null = pipelines
940
- ? { ...pipelines, name: PIPELINES_DIR }
941
- : null;
942
- const skillsRoot: FileTreeEntry | null = skills ? { ...skills, name: SKILLS_DIR } : null;
943
- const toolsRoot: FileTreeEntry | null = tools ? { ...tools, name: TOOLS_DIR } : null;
944
- return {
945
- knowledge,
946
- data: dataRoot,
947
- agents: agentsRoot,
948
- pipelines: pipelinesRoot,
949
- skills: skillsRoot,
950
- tools: toolsRoot,
951
- looseFiles: kids.filter((c) => c.type === 'file'),
952
- };
953
- }, [mergedTree]);
954
-
955
- const handleDrop = useCallback(
956
- (e: React.DragEvent) => {
957
- e.preventDefault();
958
- setDragOver(false);
959
- // Only handle external file/folder drops at the root level.
960
- if (e.dataTransfer.getData(DRAG_MIME)) return;
961
- const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
962
- if (entries.length > 0) {
963
- dispatchUpload({ kind: 'items', entries }, '');
964
- return;
965
- }
966
- const files = Array.from(e.dataTransfer.files);
967
- if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
968
- },
969
- [dispatchUpload],
970
- );
971
-
972
- return (
973
- <>
974
- <aside
975
- className={`h-full w-full min-w-0 flex flex-col bg-white overflow-hidden ${
976
- dragOver ? 'ring-2 ring-inset ring-bevel/40' : ''
977
- }`}
978
- onDrop={handleDrop}
979
- onDragOver={(e) => {
980
- e.preventDefault();
981
- setDragOver(true);
982
- }}
983
- onDragLeave={(e) => {
984
- if (e.currentTarget.contains(e.relatedTarget as Node)) return;
985
- setDragOver(false);
986
- }}
987
- >
988
- {uploadError && (
989
- <div
990
- role="alert"
991
- className="flex items-start gap-1 px-2 py-1 text-xs text-red-700 bg-red-50 border-b border-red-200 shrink-0"
992
- >
993
- <span className="flex-1 truncate" title={uploadError.reason}>
994
- Couldn't add {uploadError.filename}: {uploadError.reason}
995
- </span>
996
- <button
997
- type="button"
998
- onClick={clearUploadError}
999
- className="p-0.5 rounded hover:bg-red-100 text-red-600 hover:text-red-800 shrink-0"
1000
- title="Dismiss"
1001
- aria-label="Dismiss upload error"
1002
- >
1003
- <X size={12} />
1004
- </button>
1005
- </div>
1006
- )}
1007
- <PinnedContext.Provider value={pinnedController}>
1008
- <ManageAccessContext.Provider value={setAccessTarget}>
1009
- <div className="flex-1 overflow-y-auto py-1 min-h-0">
1010
- <div className="px-3 pt-2 pb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">
1011
- Pinned
1012
- </div>
1013
- {pinnedEntries.map((e) => (
1014
- <FileTreeNode key={`pin:${e.relativePath}`} entry={e} depth={0} collapseChildren />
1015
- ))}
1016
- {explorerItems.map(({ id, Component }) => (
1017
- <Component key={id} tree={mergedTree} />
1018
- ))}
1019
- <div className="mx-3 my-2 border-t border-slate-100" />
1020
- {!mergedTree ? (
1021
- <div className="px-3 py-4 text-xs text-slate-600">Loading...</div>
1022
- ) : sections ? (
1023
- <>
1024
- {sections.knowledge && (
1025
- <FileTreeNode entry={sections.knowledge} depth={0} accent collapseChildren />
1026
- )}
1027
- {sections.data && (
1028
- <FileTreeNode entry={sections.data} depth={0} accent collapseChildren />
1029
- )}
1030
- {sections.agents && (
1031
- <FileTreeNode entry={sections.agents} depth={0} accent collapseChildren />
1032
- )}
1033
- {sections.pipelines && (
1034
- <FileTreeNode entry={sections.pipelines} depth={0} accent collapseChildren />
1035
- )}
1036
- {sections.skills && (
1037
- <FileTreeNode entry={sections.skills} depth={0} accent collapseChildren />
1038
- )}
1039
- {sections.tools && (
1040
- <FileTreeNode entry={sections.tools} depth={0} accent collapseChildren />
1041
- )}
1042
- {sections.looseFiles.length > 0 && (
1043
- <>
1044
- <div className="mx-3 my-2 border-t border-slate-100" />
1045
- {sections.looseFiles.map((c) => (
1046
- <FileTreeNode key={c.relativePath} entry={c} depth={0} />
1047
- ))}
1048
- </>
1049
- )}
1050
- </>
1051
- ) : (
1052
- <FileTreeNode entry={mergedTree} depth={0} />
1053
- )}
1054
- </div>
1055
- </ManageAccessContext.Provider>
1056
- </PinnedContext.Provider>
1057
- <PullRequestsForMe />
1058
- </aside>
1059
- {accessTarget && (
1060
- <ManageAccessDialog
1061
- key={accessTarget.relativePath}
1062
- entry={accessTarget}
1063
- onClose={() => setAccessTarget(null)}
1064
- />
1065
- )}
1066
- </>
1067
- );
1068
- }
1
+ import { useState, useCallback, useEffect, useMemo, useRef, createContext, useContext } from 'react';
2
+ import {
3
+ ChevronRight,
4
+ FilePlus,
5
+ FolderPlus,
6
+ FolderUp,
7
+ Trash2,
8
+ Pencil,
9
+ Upload,
10
+ X,
11
+ PackageOpen,
12
+ Download,
13
+ Link2,
14
+ Loader2,
15
+ Pin,
16
+ PinOff,
17
+ Users,
18
+ } from 'lucide-react';
19
+ import type { FileTreeEntry, PullRequestSummary } from '@bevel-software/platform-shared';
20
+ import {
21
+ validateFilename,
22
+ KNOWLEDGE_BASE_DIR,
23
+ DATA_DIR,
24
+ GROUPS_DIR,
25
+ AGENTS_DIR,
26
+ PIPELINES_DIR,
27
+ } from '@bevel-software/platform-shared';
28
+ import { useWorkspace, type PendingEntry } from '../state/workspace.context';
29
+ import { mergePendingIntoTree, pathExistsInTree, findKbRoot, KB_ROOT_DIRS } from '../utils/fileTree';
30
+ import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequestDialog';
31
+ import { PR_STALE_EVENT } from '../../../core/events';
32
+ import { snapshotEntries } from '../utils/readDroppedEntries';
33
+ import { useFileNav } from '../routing/kb-routes';
34
+ import { authFetch } from '../../../lib/api';
35
+ import { cn } from '../../../lib/utils';
36
+ import { MenuPanel, MenuItem, TextField, IconButton } from '../../../shared/components';
37
+ import { useDismissableMenu } from '../../../shared/components';
38
+ import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
39
+ import { PullRequestsForMe } from '../../git/components/PullRequestsForMe';
40
+ import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
41
+ import { useAppRegistry } from '../../../core/registry';
42
+
43
+ /**
44
+ * The tree row — the prototype's `.trow` (proto:684-693), and token for token
45
+ * the same string as the Library sidebar's `rowClass`
46
+ * (`GroupsSidebar.tsx:68-72`). Two sidebars in one app should not read as two
47
+ * different products, and the only way to guarantee that is for both to be
48
+ * this one declaration.
49
+ *
50
+ * Names and one caret, nothing else. The folder icon repeated what the caret
51
+ * already said and the file icon repeated what the extension already said;
52
+ * both stood where the name should start (proto:3552-3559).
53
+ */
54
+ const ROW_CLASS =
55
+ 'flex w-full items-center gap-1.5 rounded-sm px-2.5 py-1.5 text-left text-ui transition-colors';
56
+ const ROW_TONE = (current: boolean) =>
57
+ current ? 'bg-hover font-semibold text-ink' : 'text-ink-muted hover:bg-hover hover:text-ink';
58
+
59
+ /** Indent: `10 + depth * 13` (proto:3561). */
60
+ const indentFor = (depth: number) => 10 + depth * 13;
61
+
62
+ /**
63
+ * The caret's slot — 13px wide, and rendered EMPTY for a file and for a
64
+ * childless folder. It is what keeps a file's name in line with its siblings'
65
+ * once the icons are gone: the indent is the tree, so it has to survive them
66
+ * (proto:3571-3572).
67
+ */
68
+ function CaretSlot({ open, show }: { open?: boolean; show: boolean }) {
69
+ return (
70
+ <span className="flex h-3.5 w-3.5 flex-none items-center justify-center text-ink-faint">
71
+ {show && (
72
+ <ChevronRight
73
+ size={13}
74
+ className={cn('transition-transform duration-150', open && 'rotate-90')}
75
+ />
76
+ )}
77
+ </span>
78
+ );
79
+ }
80
+
81
+ // ── Pinned folders (client-side, localStorage) ──
82
+
83
+ const PINNED_STORAGE_KEY = 'bevel-pinned-folders';
84
+
85
+ function readPinnedPaths(): string[] {
86
+ if (typeof window === 'undefined') return [];
87
+ try {
88
+ const raw = window.localStorage.getItem(PINNED_STORAGE_KEY);
89
+ const parsed = raw ? JSON.parse(raw) : [];
90
+ return Array.isArray(parsed) ? parsed.filter((p): p is string => typeof p === 'string') : [];
91
+ } catch {
92
+ return [];
93
+ }
94
+ }
95
+
96
+ interface PinnedController {
97
+ isPinned: (path: string) => boolean;
98
+ togglePin: (path: string) => void;
99
+ }
100
+
101
+ // Default no-op so a ContextMenu rendered outside the provider (e.g. in a unit
102
+ // test) never throws — the real controller is supplied by FileExplorer.
103
+ const PinnedContext = createContext<PinnedController>({
104
+ isPinned: () => false,
105
+ togglePin: () => {},
106
+ });
107
+ const usePinned = () => useContext(PinnedContext);
108
+
109
+ // Lets the deep right-click menu open the Manage access sheet without prop
110
+ // drilling through the recursive tree. FileExplorer supplies the opener and
111
+ // renders the dialog.
112
+ const ManageAccessContext = createContext<(entry: FileTreeEntry) => void>(() => {});
113
+ const useManageAccess = () => useContext(ManageAccessContext);
114
+
115
+ /**
116
+ * The tree shows files from TWO places: this branch, and the caller's own
117
+ * open change requests. A path in this controller is the second kind — it was
118
+ * synthesized into the tree from `minePaths` because it does not exist on the
119
+ * branch — and its row renders differently and opens the change request,
120
+ * because there is no content here to open.
121
+ *
122
+ * Context, not props, for the same reason as the two above: the tree is
123
+ * recursive, and every intermediate directory would otherwise have to carry
124
+ * a concern that only file rows have.
125
+ */
126
+ interface SuggestionsController {
127
+ /** CR number for a synthesized suggestion-only path; null for real files. */
128
+ crFor(path: string): number | null;
129
+ /** Open the shared change-request dialog on the request this path belongs to. */
130
+ open(path: string, crNumber: number): void;
131
+ }
132
+ const SuggestionsContext = createContext<SuggestionsController>({
133
+ crFor: () => null,
134
+ open: () => {},
135
+ });
136
+ const useSuggestions = () => useContext(SuggestionsContext);
137
+
138
+ /** Depth-first lookup of a tree entry by its exact relativePath. */
139
+ function findEntryByPath(node: FileTreeEntry, path: string): FileTreeEntry | null {
140
+ if (node.relativePath === path) return node;
141
+ if (!node.children) return null;
142
+ for (const child of node.children) {
143
+ const found = findEntryByPath(child, path);
144
+ if (found) return found;
145
+ }
146
+ return null;
147
+ }
148
+
149
+ // ── Context Menu ──
150
+
151
+ function ContextMenu({
152
+ x,
153
+ y,
154
+ entry,
155
+ isRoot,
156
+ onClose,
157
+ onCreateFile,
158
+ onCreateFolder,
159
+ onRename,
160
+ onDownload,
161
+ returnFocusTo,
162
+ }: {
163
+ x: number;
164
+ y: number;
165
+ entry: FileTreeEntry;
166
+ isRoot: boolean;
167
+ onClose: () => void;
168
+ onCreateFile?: () => void;
169
+ onCreateFolder?: () => void;
170
+ onRename?: () => void;
171
+ onDownload?: () => void;
172
+ /** The row this menu was opened from — Escape hands focus back to it. */
173
+ returnFocusTo?: React.RefObject<HTMLElement | null>;
174
+ }) {
175
+ const { deleteEntry, unzipHere } = useWorkspace();
176
+ const { isPinned, togglePin } = usePinned();
177
+ const openManageAccess = useManageAccess();
178
+ const pinned = isPinned(entry.relativePath);
179
+ const [unzipping, setUnzipping] = useState(false);
180
+ // Outside-click, Escape, and focus return — none of which `MenuPanel`
181
+ // provides (it is presentation only, by design).
182
+ const ref = useDismissableMenu<HTMLDivElement>({ open: true, onClose, returnFocusTo });
183
+
184
+ // Only files whose name ends with `.zip` (case-insensitive) get the
185
+ // extraction affordance — matches the OS shell-extension behavior users
186
+ // already know from Windows Explorer / macOS Finder.
187
+ const isZip = entry.type === 'file' && /\.zip$/i.test(entry.name);
188
+
189
+ // The one prototype context-menu item the platform has never had
190
+ // (proto:3948). The page-level `⋯ → Copy path` does not cover it: that only
191
+ // ever reaches the file you have open, never a folder row or an unopened
192
+ // one. A clipboard write can be refused outright (a non-secure origin), and
193
+ // a silent no-op is the worst possible answer to "copy this" — so a refusal
194
+ // surfaces the same way every other failure in this tree does.
195
+ const handleCopyPath = async () => {
196
+ try {
197
+ await navigator.clipboard.writeText(entry.relativePath);
198
+ onClose();
199
+ } catch (err) {
200
+ console.error('Failed to copy path:', err);
201
+ onClose();
202
+ alert(`Couldn't copy the path to the clipboard.\n\n${entry.relativePath}`);
203
+ }
204
+ };
205
+
206
+ const handleDelete = async () => {
207
+ onClose();
208
+ try {
209
+ await deleteEntry(entry.relativePath);
210
+ } catch (err) {
211
+ console.error('Failed to delete entry:', err);
212
+ const msg = err instanceof Error ? err.message : String(err);
213
+ alert(`Failed to delete ${entry.relativePath}:\n${msg}`);
214
+ }
215
+ };
216
+
217
+ const handleUnzip = async () => {
218
+ if (unzipping) return;
219
+ setUnzipping(true);
220
+ try {
221
+ const result = await unzipHere(entry.relativePath);
222
+ onClose();
223
+ // Surface a summary banner only when something was skipped — a silent
224
+ // success is the right behavior for the happy path (matches Finder /
225
+ // Explorer's "Extract here").
226
+ if (result.skipped.length > 0) {
227
+ const preview = result.skipped
228
+ .slice(0, 5)
229
+ .map((s) => ` - ${s.path}: ${s.reason}`)
230
+ .join('\n');
231
+ const more = result.skipped.length > 5 ? `\n …and ${result.skipped.length - 5} more` : '';
232
+ alert(
233
+ `Extracted ${result.extracted} file(s) from ${entry.name}.\n` +
234
+ `Skipped ${result.skipped.length} entry(ies):\n${preview}${more}`,
235
+ );
236
+ }
237
+ } catch (err) {
238
+ console.error('Failed to unzip:', err);
239
+ const msg = err instanceof Error ? err.message : String(err);
240
+ alert(`Failed to unzip ${entry.name}:\n${msg}`);
241
+ } finally {
242
+ setUnzipping(false);
243
+ }
244
+ };
245
+
246
+ return (
247
+ // Positioning stays with the caller — `MenuPanel` is presentation only, so
248
+ // the fixed-to-the-pointer wrapper is ours and the panel inside is the
249
+ // shared one.
250
+ <div
251
+ ref={ref}
252
+ className="fixed z-50"
253
+ style={{ left: x, top: y }}
254
+ onMouseDown={(e) => e.stopPropagation()}
255
+ >
256
+ <MenuPanel role="menu" aria-label={`Actions for ${entry.name}`} className="min-w-[180px]">
257
+ {onCreateFile && (
258
+ <MenuItem role="menuitem" onClick={() => { onCreateFile(); onClose(); }}>
259
+ <span className="flex items-center gap-2"><FilePlus size={14} />New file</span>
260
+ </MenuItem>
261
+ )}
262
+ {onCreateFolder && (
263
+ <MenuItem role="menuitem" onClick={() => { onCreateFolder(); onClose(); }}>
264
+ <span className="flex items-center gap-2"><FolderPlus size={14} />New folder</span>
265
+ </MenuItem>
266
+ )}
267
+ {isZip && (
268
+ <MenuItem role="menuitem" onClick={handleUnzip} disabled={unzipping}>
269
+ <span className="flex items-center gap-2">
270
+ <PackageOpen size={14} />
271
+ {unzipping ? 'Unzipping…' : 'Unzip here'}
272
+ </span>
273
+ </MenuItem>
274
+ )}
275
+ {onDownload && (
276
+ <MenuItem role="menuitem" onClick={() => { onDownload(); onClose(); }}>
277
+ <span className="flex items-center gap-2">
278
+ <Download size={14} />
279
+ {entry.type === 'directory' ? 'Download as zip' : 'Download'}
280
+ </span>
281
+ </MenuItem>
282
+ )}
283
+ <MenuItem role="menuitem" onClick={handleCopyPath}>
284
+ <span className="flex items-center gap-2"><Link2 size={14} />Copy path</span>
285
+ </MenuItem>
286
+ {!isRoot && (
287
+ <>
288
+ <div className="my-1 border-t border-line" />
289
+ <MenuItem role="menuitem" onClick={() => { openManageAccess(entry); onClose(); }}>
290
+ <span className="flex items-center gap-2"><Users size={14} />Manage access</span>
291
+ </MenuItem>
292
+ </>
293
+ )}
294
+ {entry.type === 'directory' && !isRoot && (
295
+ <MenuItem role="menuitem" onClick={() => { togglePin(entry.relativePath); onClose(); }}>
296
+ <span className="flex items-center gap-2">
297
+ {pinned ? <PinOff size={14} /> : <Pin size={14} />}
298
+ {pinned ? 'Unpin' : 'Pin to top'}
299
+ </span>
300
+ </MenuItem>
301
+ )}
302
+ {!isRoot && onRename && (
303
+ <MenuItem role="menuitem" onClick={() => { onRename(); onClose(); }}>
304
+ <span className="flex items-center gap-2"><Pencil size={14} />Rename</span>
305
+ </MenuItem>
306
+ )}
307
+ {!isRoot && (
308
+ // Danger tone comes from the primitive, not from a hand-written red.
309
+ <MenuItem role="menuitem" tone="danger" onClick={handleDelete}>
310
+ <span className="flex items-center gap-2"><Trash2 size={14} />Delete</span>
311
+ </MenuItem>
312
+ )}
313
+ </MenuPanel>
314
+ </div>
315
+ );
316
+ }
317
+
318
+ // ── Inline Input ──
319
+
320
+ function InlineInput({
321
+ onSubmit,
322
+ onCancel,
323
+ placeholder,
324
+ }: {
325
+ onSubmit: (value: string) => void;
326
+ onCancel: () => void;
327
+ placeholder: string;
328
+ }) {
329
+ const [value, setValue] = useState('');
330
+ const trimmed = value.trim();
331
+ const error = trimmed.length === 0 ? null : validateFilename(trimmed);
332
+ const valid = trimmed.length > 0 && error === null;
333
+
334
+ const submit = () => {
335
+ if (valid) onSubmit(trimmed);
336
+ };
337
+
338
+ return (
339
+ <div className="w-full">
340
+ <TextField
341
+ autoFocus
342
+ className={cn('bg-sunken px-2 py-0.5 text-detail', error && 'border-danger')}
343
+ placeholder={placeholder}
344
+ value={value}
345
+ onChange={(e) => setValue(e.target.value)}
346
+ onKeyDown={(e) => {
347
+ if (e.key === 'Enter') submit();
348
+ if (e.key === 'Escape') onCancel();
349
+ }}
350
+ onBlur={() => {
351
+ if (valid) onSubmit(trimmed);
352
+ else onCancel();
353
+ }}
354
+ title={error ?? undefined}
355
+ aria-invalid={error ? true : undefined}
356
+ />
357
+ {error && <div className="mt-0.5 px-1 text-meta text-danger">{error}</div>}
358
+ </div>
359
+ );
360
+ }
361
+
362
+ // ── Rename Input ──
363
+
364
+ function RenameInput({
365
+ currentName,
366
+ isFile,
367
+ onSubmit,
368
+ onCancel,
369
+ }: {
370
+ currentName: string;
371
+ isFile: boolean;
372
+ onSubmit: (value: string) => void;
373
+ onCancel: () => void;
374
+ }) {
375
+ const [value, setValue] = useState(currentName);
376
+ const trimmed = value.trim();
377
+ const error = trimmed.length === 0 ? null : validateFilename(trimmed);
378
+ const valid = trimmed.length > 0 && error === null;
379
+
380
+ const submit = () => {
381
+ if (valid && trimmed !== currentName) onSubmit(trimmed);
382
+ else onCancel();
383
+ };
384
+
385
+ return (
386
+ <div className="w-full">
387
+ <TextField
388
+ autoFocus
389
+ className={cn('bg-sunken px-2 py-0.5 text-detail', error && 'border-danger')}
390
+ value={value}
391
+ onClick={(e) => e.stopPropagation()}
392
+ onMouseDown={(e) => e.stopPropagation()}
393
+ onChange={(e) => setValue(e.target.value)}
394
+ onKeyDown={(e) => {
395
+ if (e.key === 'Enter') submit();
396
+ if (e.key === 'Escape') onCancel();
397
+ }}
398
+ onBlur={submit}
399
+ onFocus={(e) => {
400
+ if (isFile) {
401
+ // Select name without extension for files
402
+ const dotIdx = currentName.lastIndexOf('.');
403
+ if (dotIdx > 0) e.target.setSelectionRange(0, dotIdx);
404
+ else e.target.select();
405
+ } else {
406
+ e.target.select();
407
+ }
408
+ }}
409
+ title={error ?? undefined}
410
+ aria-invalid={error ? true : undefined}
411
+ />
412
+ {error && <div className="mt-0.5 px-1 text-meta text-danger">{error}</div>}
413
+ </div>
414
+ );
415
+ }
416
+
417
+ // ── Tree Node ──
418
+
419
+ const DRAG_MIME = 'application/x-workspace-path';
420
+
421
+ function FileTreeNode({
422
+ entry,
423
+ depth,
424
+ initiallyExpanded,
425
+ collapseChildren,
426
+ }: {
427
+ entry: FileTreeEntry;
428
+ depth: number;
429
+ // Overrides the depth-based default for whether this node starts expanded.
430
+ // The explorer's Knowledge/Skills roots use this so their own children start
431
+ // collapsed regardless of depth (auto-reveal on deep links still wins).
432
+ initiallyExpanded?: boolean;
433
+ // When set, this node's direct children start collapsed (so opening Knowledge
434
+ // reveals the ontologies without cascading them all open).
435
+ collapseChildren?: boolean;
436
+ }) {
437
+ const { openFilePath, createFile, createDirectory, dispatchUpload, isUploading, moveEntry, workspaceId, pendingUploads } = useWorkspace();
438
+ const { openFile } = useFileNav();
439
+ // One shared fetch behind this — see `OpenChangeRequestsProvider`.
440
+ const openChangeRequests = useOpenChangeRequests();
441
+ const suggestions = useSuggestions();
442
+
443
+ const handleDownload = useCallback(async () => {
444
+ if (!workspaceId) return;
445
+ // Files hit /file/raw; folders hit /folder/zip and arrive as <name>.zip.
446
+ // Both endpoints share the same per-path `download:` access gate, the
447
+ // same `?download=1` flag shape, and the same Content-Disposition
448
+ // handling on the backend — branching here just picks the URL.
449
+ // No preflight: a 403 surfaces in the alert below.
450
+ const isFolder = entry.type === 'directory';
451
+ const url = isFolder
452
+ ? `/api/workspace/${workspaceId}/folder/zip?path=${encodeURIComponent(entry.relativePath)}&download=1`
453
+ : `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(entry.relativePath)}&download=1`;
454
+ const savedAs = isFolder ? `${entry.name}.zip` : entry.name;
455
+ try {
456
+ const res = await authFetch(url);
457
+ if (!res.ok) {
458
+ const body = await res.text().catch(() => '');
459
+ alert(`Failed to download ${entry.name} (HTTP ${res.status})${body ? `: ${body}` : ''}`);
460
+ return;
461
+ }
462
+ const blob = await res.blob();
463
+ const blobUrl = URL.createObjectURL(blob);
464
+ const a = document.createElement('a');
465
+ a.href = blobUrl;
466
+ a.download = savedAs;
467
+ document.body.appendChild(a);
468
+ a.click();
469
+ a.remove();
470
+ URL.revokeObjectURL(blobUrl);
471
+ } catch (err) {
472
+ console.error('Failed to download:', err);
473
+ const msg = err instanceof Error ? err.message : String(err);
474
+ alert(`Failed to download ${entry.name}:\n${msg}`);
475
+ }
476
+ }, [workspaceId, entry.relativePath, entry.name, entry.type]);
477
+ // `null` = no explicit user intent; fall through to the auto-expand / depth
478
+ // default. Once the user clicks the chevron, intent wins over auto-expand
479
+ // until the auto-expand trigger transitions (new file opened, new upload),
480
+ // at which point intent is reset and auto-expand takes over again.
481
+ const [userIntent, setUserIntent] = useState<boolean | null>(null);
482
+ const [creating, setCreating] = useState<'file' | 'directory' | null>(null);
483
+ const [renaming, setRenaming] = useState(false);
484
+ const [dragOver, setDragOver] = useState(false);
485
+ // Only the root row uses these refs, but hooks must run unconditionally.
486
+ const rootFileInputRef = useRef<HTMLInputElement>(null);
487
+ const rootFolderInputRef = useRef<HTMLInputElement>(null);
488
+
489
+ const handleRootUploadClick = useCallback((e: React.MouseEvent) => {
490
+ e.stopPropagation();
491
+ rootFileInputRef.current?.click();
492
+ }, []);
493
+
494
+ const handleRootFolderClick = useCallback((e: React.MouseEvent) => {
495
+ e.stopPropagation();
496
+ rootFolderInputRef.current?.click();
497
+ }, []);
498
+
499
+ // Resetting `value` after dispatch lets users re-select the same file and
500
+ // still get an `onChange` event the second time around.
501
+ const handleRootFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
502
+ const files = Array.from(e.target.files ?? []);
503
+ e.target.value = '';
504
+ if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
505
+ }, [dispatchUpload]);
506
+
507
+ // Folder picker: each File carries a `webkitRelativePath` like
508
+ // "foldername/sub/file.txt" — we feed those straight into the upload
509
+ // pipeline as pre-resolved paths. Note: `<input webkitdirectory>` only
510
+ // enumerates files (the browser hides empty subdirs from us), so empty
511
+ // folders are only preserved via the drag-and-drop path that uses the
512
+ // FileSystem entries API.
513
+ const handleRootFolderChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
514
+ const files = Array.from(e.target.files ?? []);
515
+ e.target.value = '';
516
+ if (files.length === 0) return;
517
+ const items = files.map((file) => ({
518
+ file,
519
+ relativePath: file.webkitRelativePath || file.name,
520
+ }));
521
+ dispatchUpload({ kind: 'paths', items }, '');
522
+ }, [dispatchUpload]);
523
+ const [dragging, setDragging] = useState(false);
524
+ const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
525
+
526
+ const paddingLeft = indentFor(depth);
527
+ const isRoot = entry.relativePath === '.';
528
+ const isPending = pendingUploads.has(entry.relativePath);
529
+ // A folder with nothing in it doesn't get a caret, because there is nothing
530
+ // to open (proto:3565).
531
+ const hasChildren = (entry.children?.length ?? 0) > 0;
532
+ // Escape inside the context menu hands focus back to the row it came from.
533
+ const rowRef = useRef<HTMLButtonElement>(null);
534
+
535
+ // Auto-expand a directory whenever the open file lives inside it (so
536
+ // deep-link URLs reveal the file's row in the tree) or while files
537
+ // dropped under it are still uploading (so the user can watch them
538
+ // fill in).
539
+ const isOpenFileAncestor = entry.type === 'directory' && !!openFilePath && (
540
+ isRoot || openFilePath.startsWith(entry.relativePath + '/')
541
+ );
542
+ const autoExpanded = entry.type === 'directory' && (isPending || isOpenFileAncestor);
543
+
544
+ // Fingerprint of what currently drives auto-expand. When it transitions
545
+ // (different file opened, upload starts), the user's prior collapse intent
546
+ // is stale — reset so deep-links / new uploads can re-reveal the folder.
547
+ const autoTrigger = `${isPending ? 'P' : ''}|${isOpenFileAncestor ? openFilePath : ''}`;
548
+ const prevAutoTriggerRef = useRef(autoTrigger);
549
+ useEffect(() => {
550
+ if (prevAutoTriggerRef.current !== autoTrigger) {
551
+ prevAutoTriggerRef.current = autoTrigger;
552
+ setUserIntent(null);
553
+ }
554
+ }, [autoTrigger]);
555
+
556
+ const isExpanded = userIntent ?? (autoExpanded || (initiallyExpanded ?? depth < 2));
557
+
558
+ const handleContextMenu = useCallback((e: React.MouseEvent) => {
559
+ e.preventDefault();
560
+ e.stopPropagation();
561
+ setContextMenu({ x: e.clientX, y: e.clientY });
562
+ }, []);
563
+
564
+ // ── Drag source (internal reorder) ──
565
+ const handleDragStart = useCallback((e: React.DragEvent) => {
566
+ if (isRoot) { e.preventDefault(); return; }
567
+ e.dataTransfer.setData(DRAG_MIME, entry.relativePath);
568
+ e.dataTransfer.effectAllowed = 'move';
569
+ setDragging(true);
570
+ }, [entry.relativePath, isRoot]);
571
+
572
+ const handleDragEnd = useCallback(() => {
573
+ setDragging(false);
574
+ }, []);
575
+
576
+ // ── Drop target ──
577
+ const handleDrop = useCallback(
578
+ (e: React.DragEvent) => {
579
+ e.preventDefault();
580
+ e.stopPropagation();
581
+ setDragOver(false);
582
+
583
+ // Internal move (reorder)
584
+ const sourcePath = e.dataTransfer.getData(DRAG_MIME);
585
+ if (sourcePath) {
586
+ const targetDir = entry.type === 'directory'
587
+ ? (isRoot ? '' : entry.relativePath)
588
+ : '';
589
+ const name = sourcePath.split('/').pop()!;
590
+ const newPath = targetDir ? `${targetDir}/${name}` : name;
591
+ // Skip no-op or nesting a directory inside itself
592
+ if (
593
+ newPath === sourcePath ||
594
+ targetDir === sourcePath ||
595
+ targetDir.startsWith(sourcePath + '/')
596
+ ) {
597
+ return;
598
+ }
599
+ moveEntry(sourcePath, newPath);
600
+ return;
601
+ }
602
+
603
+ // External file/folder drop. Snapshot the entries synchronously
604
+ // before any await — the browser invalidates `DataTransfer` once the
605
+ // handler returns, and the walker awaits inside.
606
+ const dir = entry.type === 'directory' ? entry.relativePath : '';
607
+ const targetDir = dir === '.' ? '' : dir;
608
+ const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
609
+ if (entries.length > 0) {
610
+ dispatchUpload({ kind: 'items', entries }, targetDir);
611
+ return;
612
+ }
613
+ // Fallback for older browsers / non-entry drops: use the flat FileList.
614
+ const files = Array.from(e.dataTransfer.files);
615
+ if (files.length === 0) return;
616
+ dispatchUpload({ kind: 'files', files }, targetDir);
617
+ },
618
+ [entry, isRoot, dispatchUpload, moveEntry],
619
+ );
620
+
621
+ const handleDragOver = useCallback((e: React.DragEvent) => {
622
+ e.preventDefault();
623
+ e.stopPropagation();
624
+ if (entry.type === 'directory') {
625
+ e.dataTransfer.dropEffect = 'move';
626
+ setDragOver(true);
627
+ }
628
+ }, [entry.type]);
629
+
630
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
631
+ e.preventDefault();
632
+ e.stopPropagation();
633
+ setDragOver(false);
634
+ }, []);
635
+
636
+ if (entry.type === 'directory') {
637
+ const dirPath = isRoot ? '' : entry.relativePath;
638
+ return (
639
+ <div>
640
+ <div
641
+ className={cn(
642
+ ROW_CLASS,
643
+ ROW_TONE(false),
644
+ 'group',
645
+ dragOver && 'bg-hover text-ink ring-1 ring-accent/40',
646
+ )}
647
+ style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
648
+ draggable={!isRoot && !renaming && !isPending}
649
+ onDragStart={handleDragStart}
650
+ onDragEnd={handleDragEnd}
651
+ onDrop={handleDrop}
652
+ onDragOver={handleDragOver}
653
+ onDragLeave={handleDragLeave}
654
+ onContextMenu={handleContextMenu}
655
+ >
656
+ <button
657
+ ref={rowRef}
658
+ type="button"
659
+ aria-expanded={isExpanded}
660
+ className="flex min-w-0 flex-1 items-center gap-1.5 text-left"
661
+ onClick={() => { if (hasChildren) setUserIntent(!isExpanded); }}
662
+ >
663
+ <CaretSlot open={isExpanded} show={hasChildren} />
664
+ {renaming ? (
665
+ <RenameInput
666
+ currentName={entry.name}
667
+ isFile={false}
668
+ onSubmit={async (newName) => {
669
+ const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
670
+ const newPath = parentDir ? `${parentDir}/${newName}` : newName;
671
+ // Close the input BEFORE the fallible move — see the create
672
+ // flow: on error the alert() blurs the still-mounted input,
673
+ // whose onBlur re-fires this onSubmit, looping the popup.
674
+ setRenaming(false);
675
+ try {
676
+ await moveEntry(entry.relativePath, newPath);
677
+ } catch (err) {
678
+ // Same surfacing as the create flow above — a silent failure
679
+ // reads as the rename being accepted and then reverting.
680
+ const msg = err instanceof Error ? err.message : String(err);
681
+ alert(`Failed to rename ${entry.name}:\n${msg}`);
682
+ }
683
+ }}
684
+ onCancel={() => setRenaming(false)}
685
+ />
686
+ ) : (
687
+ <span className="truncate">{entry.name}</span>
688
+ )}
689
+ </button>
690
+ <div className="hidden shrink-0 items-center gap-0.5 group-hover:flex group-focus-within:flex">
691
+ <IconButton
692
+ size={18}
693
+ title="New file"
694
+ aria-label={`New file in ${entry.name}`}
695
+ onClick={(e) => {
696
+ e.stopPropagation();
697
+ setUserIntent(true);
698
+ setCreating('file');
699
+ }}
700
+ >
701
+ <FilePlus size={13} />
702
+ </IconButton>
703
+ <IconButton
704
+ size={18}
705
+ title="New folder"
706
+ aria-label={`New folder in ${entry.name}`}
707
+ onClick={(e) => {
708
+ e.stopPropagation();
709
+ setUserIntent(true);
710
+ setCreating('directory');
711
+ }}
712
+ >
713
+ <FolderPlus size={13} />
714
+ </IconButton>
715
+ </div>
716
+ {isRoot && (
717
+ <>
718
+ <IconButton
719
+ size={18}
720
+ title="Add files"
721
+ aria-label="Add files"
722
+ disabled={isUploading}
723
+ onClick={handleRootUploadClick}
724
+ >
725
+ <Upload size={13} />
726
+ </IconButton>
727
+ <input
728
+ ref={rootFileInputRef}
729
+ type="file"
730
+ multiple
731
+ hidden
732
+ aria-hidden="true"
733
+ data-testid="file-explorer-file-input"
734
+ onChange={handleRootFileChange}
735
+ />
736
+ <IconButton
737
+ size={18}
738
+ title="Add folder"
739
+ aria-label="Add folder"
740
+ disabled={isUploading}
741
+ onClick={handleRootFolderClick}
742
+ >
743
+ <FolderUp size={13} />
744
+ </IconButton>
745
+ <input
746
+ ref={rootFolderInputRef}
747
+ type="file"
748
+ multiple
749
+ webkitdirectory=""
750
+ hidden
751
+ aria-hidden="true"
752
+ data-testid="file-explorer-folder-input"
753
+ onChange={handleRootFolderChange}
754
+ />
755
+ </>
756
+ )}
757
+ </div>
758
+ {isExpanded && (
759
+ <div>
760
+ {creating && (
761
+ // Line the input up with the child rows it is about to join:
762
+ // one more indent step (13px), plus the caret slot (13px) and
763
+ // the row gap (6px) the child's name starts after.
764
+ <div style={{ paddingLeft: paddingLeft + 32 }} className="px-2 py-0.5">
765
+ <InlineInput
766
+ placeholder={creating === 'file' ? 'filename' : 'folder name'}
767
+ onSubmit={async (name) => {
768
+ const fullPath = dirPath ? `${dirPath}/${name}` : name;
769
+ const kind = creating;
770
+ // Close the inline input BEFORE anything can fail. On
771
+ // error the alert() below steals focus; leaving the input
772
+ // mounted means dismissing the alert blurs it, and the
773
+ // input's onBlur re-fires this same onSubmit — an infinite
774
+ // "Failed to create …" popup loop against an unchanging
775
+ // 403. Unmounting first breaks that cycle.
776
+ setCreating(null);
777
+ try {
778
+ if (kind === 'file') await createFile(fullPath);
779
+ else await createDirectory(fullPath);
780
+ } catch (err) {
781
+ // Surface the refusal (e.g. a protected branch's write
782
+ // gate: "You don't have permission to write to …") —
783
+ // otherwise the input clears and nothing appears, which
784
+ // reads as the file silently vanishing.
785
+ const msg = err instanceof Error ? err.message : String(err);
786
+ alert(`Failed to create ${name}:\n${msg}`);
787
+ }
788
+ }}
789
+ onCancel={() => setCreating(null)}
790
+ />
791
+ </div>
792
+ )}
793
+ {entry.children?.map((child) => (
794
+ <FileTreeNode
795
+ key={child.relativePath}
796
+ entry={child}
797
+ depth={depth + 1}
798
+ initiallyExpanded={collapseChildren ? false : undefined}
799
+ />
800
+ ))}
801
+ </div>
802
+ )}
803
+ {contextMenu && (
804
+ <ContextMenu
805
+ x={contextMenu.x}
806
+ y={contextMenu.y}
807
+ entry={entry}
808
+ isRoot={isRoot}
809
+ onClose={() => setContextMenu(null)}
810
+ onCreateFile={() => { setUserIntent(true); setCreating('file'); }}
811
+ onCreateFolder={() => { setUserIntent(true); setCreating('directory'); }}
812
+ onRename={() => setRenaming(true)}
813
+ onDownload={handleDownload}
814
+ returnFocusTo={rowRef}
815
+ />
816
+ )}
817
+ </div>
818
+ );
819
+ }
820
+
821
+ // A file from the caller's own open change request that does not exist on
822
+ // this branch. Its row is a LINK to the request, not a file: there is no
823
+ // content here to show, so clicking opens the change-request view, and none
824
+ // of the file affordances (rename, drag, download, context menu) apply —
825
+ // they would all 404 against a path this branch has never heard of. The
826
+ // accent colour is the tell that this is proposed, not present.
827
+ const suggestedCr = suggestions.crFor(entry.relativePath);
828
+ if (suggestedCr !== null) {
829
+ return (
830
+ <button
831
+ type="button"
832
+ className={cn(
833
+ ROW_CLASS,
834
+ 'text-accent hover:bg-hover hover:text-accent-hover',
835
+ 'focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-ink-muted',
836
+ )}
837
+ style={{ paddingLeft }}
838
+ onClick={() => suggestions.open(entry.relativePath, suggestedCr)}
839
+ title="Proposed by you: opens the change request"
840
+ >
841
+ <CaretSlot show={false} />
842
+ <span className="truncate">{entry.name}</span>
843
+ <span
844
+ aria-hidden
845
+ className="ml-auto h-1.5 w-1.5 flex-none rounded-full bg-accent"
846
+ />
847
+ </button>
848
+ );
849
+ }
850
+
851
+ const isActive = entry.relativePath === openFilePath;
852
+
853
+ return (
854
+ <>
855
+ <button
856
+ ref={rowRef}
857
+ type="button"
858
+ aria-current={isActive}
859
+ className={cn(
860
+ ROW_CLASS,
861
+ ROW_TONE(isActive),
862
+ 'focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-ink-muted',
863
+ isPending && 'cursor-progress',
864
+ )}
865
+ style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
866
+ draggable={!renaming && !isPending}
867
+ onDragStart={handleDragStart}
868
+ onDragEnd={handleDragEnd}
869
+ onClick={() => { if (!renaming && !isPending) openFile(entry.relativePath); }}
870
+ onContextMenu={handleContextMenu}
871
+ title={isPending ? 'Adding…' : undefined}
872
+ >
873
+ {/* The pending spinner is the one glyph that survives the icon cull,
874
+ because it says something no other part of the row says. It takes
875
+ the caret's slot so the name never shifts when it appears. */}
876
+ {isPending ? (
877
+ <span className="flex h-3.5 w-3.5 flex-none items-center justify-center">
878
+ <Loader2 size={13} className="animate-spin text-ink-faint" />
879
+ </span>
880
+ ) : (
881
+ <CaretSlot show={false} />
882
+ )}
883
+ {renaming ? (
884
+ <RenameInput
885
+ currentName={entry.name}
886
+ isFile={true}
887
+ onSubmit={async (newName) => {
888
+ const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
889
+ const newPath = parentDir ? `${parentDir}/${newName}` : newName;
890
+ // Close the input BEFORE the fallible move — see the create
891
+ // flow: on error the alert() blurs the still-mounted input,
892
+ // whose onBlur re-fires this onSubmit, looping the popup.
893
+ setRenaming(false);
894
+ try {
895
+ await moveEntry(entry.relativePath, newPath);
896
+ } catch (err) {
897
+ // Same surfacing as the create flow — a silent failure reads
898
+ // as the rename being accepted and then reverting.
899
+ const msg = err instanceof Error ? err.message : String(err);
900
+ alert(`Failed to rename ${entry.name}:\n${msg}`);
901
+ }
902
+ }}
903
+ onCancel={() => setRenaming(false)}
904
+ />
905
+ ) : (
906
+ <span className="truncate">{entry.name}</span>
907
+ )}
908
+ {/* News about a file you are not looking at (proto:692). Amber, not
909
+ the tab dot's accent: on a tab the dot marks the file you have
910
+ open; here it marks one you do not. */}
911
+ {openChangeRequests.paths.has(entry.relativePath) && (
912
+ <span
913
+ title="Open change request"
914
+ className="ml-auto h-1.5 w-1.5 flex-none rounded-full bg-wait-dot"
915
+ />
916
+ )}
917
+ </button>
918
+ {contextMenu && (
919
+ <ContextMenu
920
+ x={contextMenu.x}
921
+ y={contextMenu.y}
922
+ entry={entry}
923
+ isRoot={false}
924
+ onClose={() => setContextMenu(null)}
925
+ onRename={() => setRenaming(true)}
926
+ onDownload={handleDownload}
927
+ returnFocusTo={rowRef}
928
+ />
929
+ )}
930
+ </>
931
+ );
932
+ }
933
+
934
+ // ── Explorer Root ──
935
+
936
+ /**
937
+ * Walk down to the node that actually holds the KB content. The file tree roots
938
+ * at the per-branch workspace dir and wraps the KB clone a level or two deep
939
+ * (`<branch>/<kbDir>/{KnowledgeBase,Data,Agents,Pipelines,Skills,Tools,…}`), so
940
+ * the split lives below the visible root. Returns the first node whose children
941
+ * include one of those well-known root directories, or null when there's no
942
+ * such split (legacy clones).
943
+ */
944
+ // (`findKbRoot` lives in `../utils/fileTree` — shared with registry-
945
+ // contributed explorer items.)
946
+
947
+ export function FileExplorer() {
948
+ const {
949
+ fileTree,
950
+ kbDirName,
951
+ dispatchUpload,
952
+ uploadError,
953
+ clearUploadError,
954
+ uploadNotice,
955
+ clearUploadNotice,
956
+ pendingUploads,
957
+ } = useWorkspace();
958
+ const [dragOver, setDragOver] = useState(false);
959
+ // Download is now a per-path permission (resolved server-side from the
960
+ // access tree's `download:` verb), so there's no global preflight gate
961
+ // here anymore. The menu items always render; if the user clicks on a
962
+ // file they don't have download permission for, the backend returns 403
963
+ // and `handleDownload` shows the error.
964
+ // Optimistic overlay: every dropped/picked file shows up in the tree
965
+ // within a frame, even before its commit echoes back from the server.
966
+ const serverTree = useMemo(
967
+ () => (fileTree ? mergePendingIntoTree(fileTree, pendingUploads) : null),
968
+ [fileTree, pendingUploads],
969
+ );
970
+
971
+ // The caller's own proposed files that do NOT exist on this branch — they
972
+ // live only on the personal suggestions branch behind an open change
973
+ // request. The tree shows them beside the branch's real files (synthesized
974
+ // below), coloured differently, and clicking one opens the request.
975
+ const openChangeRequests = useOpenChangeRequests();
976
+ const suggestionOnlyPaths = useMemo(() => {
977
+ const map = new Map<string, number>();
978
+ if (!serverTree) return map;
979
+ /**
980
+ * "Not in the tree" has TWO causes, and only one earns a row: the file is
981
+ * new on the suggestions branch — or the server FILTERED it (.bevelignore,
982
+ * read gates). The client cannot evaluate those rules itself, but it can
983
+ * read their verdict off the tree: if the path's top-level folder under
984
+ * the repo root is absent, the whole subtree is hidden (a skill proposal
985
+ * under a bevelignored `Groups/` was the observed leak), so the overlay
986
+ * must not resurrect it. The known cost: a proposal that CREATES a new
987
+ * top-level root folder shows no row until it merges.
988
+ */
989
+ const hiddenRoot = (path: string): boolean => {
990
+ const prefix = kbDirName && path.startsWith(`${kbDirName}/`) ? `${kbDirName}/` : '';
991
+ const segments = path.slice(prefix.length).split('/');
992
+ if (segments.length < 2) return false; // directly under the repo root
993
+ return !pathExistsInTree(serverTree, `${prefix}${segments[0]}`);
994
+ };
995
+ for (const [path, crNumber] of openChangeRequests.minePaths) {
996
+ if (!pathExistsInTree(serverTree, path) && !hiddenRoot(path)) {
997
+ map.set(path, crNumber);
998
+ }
999
+ }
1000
+ return map;
1001
+ }, [serverTree, openChangeRequests, kbDirName]);
1002
+
1003
+ const mergedTree = useMemo(() => {
1004
+ if (!serverTree || suggestionOnlyPaths.size === 0) return serverTree;
1005
+ // Reuses the pending-upload synthesizer: same parent-directory creation,
1006
+ // same sort order, and a real entry always wins over a synthesized one.
1007
+ const asEntries = new Map<string, PendingEntry>();
1008
+ for (const path of suggestionOnlyPaths.keys()) {
1009
+ asEntries.set(path, { fullPath: path, type: 'file' });
1010
+ }
1011
+ return mergePendingIntoTree(serverTree, asEntries);
1012
+ }, [serverTree, suggestionOnlyPaths]);
1013
+
1014
+ // A clicked suggestion row opens the SHARED change-request dialog on the
1015
+ // request the path belongs to — the row is a link to the request, and the
1016
+ // dialog is the one change-request view the app has.
1017
+ const [openSuggestionCr, setOpenSuggestionCr] = useState<PullRequestSummary | null>(null);
1018
+ const suggestionsController = useMemo<SuggestionsController>(
1019
+ () => ({
1020
+ crFor: (path) => suggestionOnlyPaths.get(path) ?? null,
1021
+ open: (path, crNumber) => {
1022
+ const cr = openChangeRequests.forPath(path).find((c) => c.number === crNumber) ?? null;
1023
+ setOpenSuggestionCr(cr);
1024
+ },
1025
+ }),
1026
+ [suggestionOnlyPaths, openChangeRequests],
1027
+ );
1028
+
1029
+ // Pinned folders — a personal, client-side shortcut list surfaced at the top
1030
+ // of the explorer. Stored as relativePaths in localStorage; toggled from the
1031
+ // right-click menu (Pin to top / Unpin).
1032
+ const [pinnedPaths, setPinnedPaths] = useState<string[]>(readPinnedPaths);
1033
+ const togglePin = useCallback((path: string) => {
1034
+ setPinnedPaths((prev) => {
1035
+ const next = prev.includes(path) ? prev.filter((p) => p !== path) : [...prev, path];
1036
+ try {
1037
+ window.localStorage.setItem(PINNED_STORAGE_KEY, JSON.stringify(next));
1038
+ } catch {
1039
+ // localStorage unavailable — pins stay in memory for this session.
1040
+ }
1041
+ return next;
1042
+ });
1043
+ }, []);
1044
+ const pinnedController = useMemo<PinnedController>(
1045
+ () => ({ isPinned: (path) => pinnedPaths.includes(path), togglePin }),
1046
+ [pinnedPaths, togglePin],
1047
+ );
1048
+ // Resolve pinned paths to live tree entries, dropping any that no longer
1049
+ // exist on this branch (a folder pinned elsewhere may be absent here).
1050
+ const pinnedEntries = useMemo(
1051
+ () =>
1052
+ mergedTree
1053
+ ? pinnedPaths
1054
+ .map((p) => findEntryByPath(mergedTree, p))
1055
+ .filter((e): e is FileTreeEntry => e != null)
1056
+ : [],
1057
+ [mergedTree, pinnedPaths],
1058
+ );
1059
+
1060
+ // Registry-contributed rows for the Pinned section (rendered below the
1061
+ // pinned folders). The enterprise knowledge system contributes its
1062
+ // "Graph view" entry — the interactive ontology graph — this way; the core
1063
+ // ships none of its own.
1064
+ const { explorerItems } = useAppRegistry();
1065
+
1066
+ // Right-click → Manage access opens this sheet for the chosen entry.
1067
+ const [accessTarget, setAccessTarget] = useState<FileTreeEntry | null>(null);
1068
+
1069
+ // KB content splits into separate top-level folders; surface them as labelled
1070
+ // sections rather than a single flat root. The Knowledge section hoists
1071
+ // `KnowledgeBase/`'s children and folds in any other top-level content folder
1072
+ // (e.g. a stray `Legal/`); loose top-level files (access.md, roles.yaml) sit
1073
+ // below a divider. Clones that predate the split (none of the well-known root
1074
+ // dirs) fall back to the flat tree.
1075
+ //
1076
+ // `Groups/` is NOT among them. It is the Skills & Tools app's storage — one
1077
+ // folder per group holding its skills and its tools — and that app presents
1078
+ // it as groups, skills and tools rather than as files. Listing it here too
1079
+ // offered a second, worse way in: raw markdown editing of a SKILL.md with
1080
+ // none of the surrounding affordances, on a folder whose access is managed
1081
+ // from the group page. Deep links into a group file still resolve; the
1082
+ // folder just is not a browsing destination in Knowledge.
1083
+ //
1084
+ // `Data/`, `Agents/` and `Pipelines/` are rendered when PRESENT but never
1085
+ // created by core (see `CORE_REQUIRED_DIRS`) — a deployment that owns the
1086
+ // agentic execution layer seeds them, and this reads whatever is there.
1087
+ const sections = useMemo(() => {
1088
+ // Descend past the workspace / KB-clone wrapper levels to the node that
1089
+ // actually holds the well-known root dirs, then split that level.
1090
+ const kids = findKbRoot(mergedTree)?.children;
1091
+ if (!kids) return null;
1092
+ const findDir = (name: string) =>
1093
+ kids.find((c) => c.type === 'directory' && c.name === name);
1094
+ const knowledgeBase = findDir(KNOWLEDGE_BASE_DIR);
1095
+ const data = findDir(DATA_DIR);
1096
+ const agents = findDir(AGENTS_DIR);
1097
+ const pipelines = findDir(PIPELINES_DIR);
1098
+ // Groups counts toward "is this a split layout?" even though it is never
1099
+ // rendered: its presence proves the split just as well as the others, and
1100
+ // without it a KB whose only root is Groups would fail this check, fall
1101
+ // back to the flat tree, and show the folder that way instead.
1102
+ const groups = findDir(GROUPS_DIR);
1103
+ if (!knowledgeBase && !data && !agents && !pipelines && !groups) return null;
1104
+ // Any other top-level content folder (e.g. a stray `Legal/`) folds into Knowledge.
1105
+ const otherDirs = kids.filter(
1106
+ (c) => c.type === 'directory' && !KB_ROOT_DIRS.has(c.name),
1107
+ );
1108
+ // Present Knowledge, Data and Groups as named roots. Knowledge is
1109
+ // synthetic so it can relabel `KnowledgeBase` and absorb the stray
1110
+ // content folders; it reuses KnowledgeBase's own path so file ops on the
1111
+ // row still resolve.
1112
+ const knowledge: FileTreeEntry | null = knowledgeBase
1113
+ ? {
1114
+ ...knowledgeBase,
1115
+ name: 'Knowledge',
1116
+ children: [...(knowledgeBase.children ?? []), ...otherDirs],
1117
+ }
1118
+ : otherDirs.length > 0
1119
+ ? { name: 'Knowledge', relativePath: otherDirs[0].relativePath, type: 'directory', children: otherDirs }
1120
+ : null;
1121
+ const dataRoot: FileTreeEntry | null = data ? { ...data, name: DATA_DIR } : null;
1122
+ const agentsRoot: FileTreeEntry | null = agents ? { ...agents, name: AGENTS_DIR } : null;
1123
+ const pipelinesRoot: FileTreeEntry | null = pipelines
1124
+ ? { ...pipelines, name: PIPELINES_DIR }
1125
+ : null;
1126
+ return {
1127
+ knowledge,
1128
+ data: dataRoot,
1129
+ agents: agentsRoot,
1130
+ pipelines: pipelinesRoot,
1131
+ looseFiles: kids.filter((c) => c.type === 'file'),
1132
+ };
1133
+ }, [mergedTree]);
1134
+
1135
+ const handleDrop = useCallback(
1136
+ (e: React.DragEvent) => {
1137
+ e.preventDefault();
1138
+ setDragOver(false);
1139
+ // Only handle external file/folder drops at the root level.
1140
+ if (e.dataTransfer.getData(DRAG_MIME)) return;
1141
+ const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
1142
+ if (entries.length > 0) {
1143
+ dispatchUpload({ kind: 'items', entries }, '');
1144
+ return;
1145
+ }
1146
+ const files = Array.from(e.dataTransfer.files);
1147
+ if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
1148
+ },
1149
+ [dispatchUpload],
1150
+ );
1151
+
1152
+ return (
1153
+ <>
1154
+ {/* No background, no border, no width: this is the CONTENTS of the app's
1155
+ one sidebar, and `SidebarFrame` is the sidebar. It used to be
1156
+ `bg-white` against the Library's `bg-sidebar`, which is how two navs in
1157
+ one app ended up looking like two apps. */}
1158
+ <div
1159
+ // The drop target. It was findable as `role="complementary"` while this
1160
+ // was the `<aside>`; the aside is `SidebarFrame`'s now, and a second
1161
+ // complementary nested inside the first would be a lie about the page's
1162
+ // landmarks.
1163
+ data-testid="file-explorer-root"
1164
+ className={`h-full w-full min-w-0 flex flex-col overflow-hidden ${
1165
+ dragOver ? 'ring-2 ring-inset ring-accent/40' : ''
1166
+ }`}
1167
+ onDrop={handleDrop}
1168
+ onDragOver={(e) => {
1169
+ e.preventDefault();
1170
+ setDragOver(true);
1171
+ }}
1172
+ onDragLeave={(e) => {
1173
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
1174
+ setDragOver(false);
1175
+ }}
1176
+ >
1177
+ {uploadError && (
1178
+ <div
1179
+ role="alert"
1180
+ className="flex items-start gap-1 px-2 py-1 text-xs text-danger bg-danger-soft border-b border-danger/30 shrink-0"
1181
+ >
1182
+ <span className="flex-1 truncate" title={uploadError.reason}>
1183
+ Couldn't add {uploadError.filename}: {uploadError.reason}
1184
+ </span>
1185
+ <IconButton
1186
+ size={18}
1187
+ tone="danger"
1188
+ title="Dismiss"
1189
+ aria-label="Dismiss upload error"
1190
+ onClick={clearUploadError}
1191
+ >
1192
+ <X size={12} />
1193
+ </IconButton>
1194
+ </div>
1195
+ )}
1196
+ {/* Not an error: the upload LANDED, on the suggestions branch. Saying
1197
+ so is load-bearing — nothing appears in the tree where the user
1198
+ dropped the files, and silence there reads as a failed upload. */}
1199
+ {uploadNotice && (
1200
+ <div
1201
+ role="status"
1202
+ className="flex items-start gap-1 px-2 py-1 text-xs text-ink bg-wait-soft border-b border-line shrink-0"
1203
+ >
1204
+ <span className="flex-1" title={uploadNotice}>
1205
+ {uploadNotice}
1206
+ </span>
1207
+ <IconButton
1208
+ size={18}
1209
+ title="Dismiss"
1210
+ aria-label="Dismiss upload notice"
1211
+ onClick={clearUploadNotice}
1212
+ >
1213
+ <X size={12} />
1214
+ </IconButton>
1215
+ </div>
1216
+ )}
1217
+ <PinnedContext.Provider value={pinnedController}>
1218
+ <ManageAccessContext.Provider value={setAccessTarget}>
1219
+ <SuggestionsContext.Provider value={suggestionsController}>
1220
+ <div className="flex-1 overflow-y-auto min-h-0">
1221
+ {/* "Company Context", not "Pinned". The mechanism is pinning; the
1222
+ SECTION is the handful of places this company actually works out
1223
+ of. A label naming the mechanism tells you how the rows got there,
1224
+ which nobody is wondering — the useful heading says what they are.
1225
+
1226
+ Same padding as the Library's `SectionLabel`, because it is the
1227
+ same thing: a heading over a list of places. */}
1228
+ <div className="px-2.5 pb-1.5 text-label uppercase text-ink-faint">Company Context</div>
1229
+ {pinnedEntries.map((e) => (
1230
+ <FileTreeNode key={`pin:${e.relativePath}`} entry={e} depth={0} collapseChildren />
1231
+ ))}
1232
+ {explorerItems.map(({ id, Component }) => (
1233
+ <Component key={id} tree={mergedTree} />
1234
+ ))}
1235
+ <div className="mx-3 my-2 border-t border-line" />
1236
+ {!mergedTree ? (
1237
+ <div className="px-3 py-4 text-xs text-ink-muted">Loading...</div>
1238
+ ) : sections ? (
1239
+ <>
1240
+ {sections.knowledge && (
1241
+ <FileTreeNode entry={sections.knowledge} depth={0} collapseChildren />
1242
+ )}
1243
+ {sections.data && (
1244
+ <FileTreeNode entry={sections.data} depth={0} collapseChildren />
1245
+ )}
1246
+ {sections.agents && (
1247
+ <FileTreeNode entry={sections.agents} depth={0} collapseChildren />
1248
+ )}
1249
+ {sections.pipelines && (
1250
+ <FileTreeNode entry={sections.pipelines} depth={0} collapseChildren />
1251
+ )}
1252
+ {sections.looseFiles.length > 0 && (
1253
+ <>
1254
+ <div className="mx-3 my-2 border-t border-line" />
1255
+ {sections.looseFiles.map((c) => (
1256
+ <FileTreeNode key={c.relativePath} entry={c} depth={0} />
1257
+ ))}
1258
+ </>
1259
+ )}
1260
+ </>
1261
+ ) : (
1262
+ <FileTreeNode entry={mergedTree} depth={0} />
1263
+ )}
1264
+ </div>
1265
+ </SuggestionsContext.Provider>
1266
+ </ManageAccessContext.Provider>
1267
+ </PinnedContext.Provider>
1268
+ <PullRequestsForMe />
1269
+ </div>
1270
+ {openSuggestionCr && (
1271
+ <ChangeRequestDialog
1272
+ cr={openSuggestionCr}
1273
+ onClose={() => setOpenSuggestionCr(null)}
1274
+ onResolved={() => {
1275
+ setOpenSuggestionCr(null);
1276
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
1277
+ }}
1278
+ />
1279
+ )}
1280
+ {accessTarget && (
1281
+ <ManageAccessDialog
1282
+ key={accessTarget.relativePath}
1283
+ entry={accessTarget}
1284
+ // The dialog is keyed on the path, so pointing it at a parent remounts
1285
+ // it against that folder — the whole retarget is this one setter.
1286
+ onManageAncestor={setAccessTarget}
1287
+ onClose={() => setAccessTarget(null)}
1288
+ />
1289
+ )}
1290
+ </>
1291
+ );
1292
+ }