@bevel-software/platform-core-frontend 0.15.1 → 0.19.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 (346) hide show
  1. package/THIRD-PARTY-NOTICES.md +2 -2
  2. package/package.json +3 -3
  3. package/src/core/CoreAppShell.tsx +16 -9
  4. package/src/core/__tests__/AppChrome.test.tsx +0 -3
  5. package/src/core/__tests__/events.test.ts +43 -0
  6. package/src/core/bootstrap.ts +11 -3
  7. package/src/core/events.ts +85 -3
  8. package/src/core/registry.ts +1 -1
  9. package/src/lib/__tests__/email.test.ts +44 -0
  10. package/src/lib/email.ts +37 -1
  11. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +141 -0
  12. package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +204 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.download-read.test.tsx +234 -0
  14. package/src/modules/access/__tests__/ManageAccessDialog.edited-row-visible.test.tsx +160 -0
  15. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +2 -2
  16. package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +166 -0
  17. package/src/modules/access/__tests__/ManageAccessDialog.restrict.test.tsx +510 -0
  18. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-axes.test.tsx +299 -0
  19. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-width.test.tsx +226 -0
  20. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +721 -126
  21. package/src/modules/access/__tests__/ManageAccessDialog.unknown-email.test.tsx +314 -0
  22. package/src/modules/access/__tests__/manage-access-affordance.test.ts +14 -0
  23. package/src/modules/access/__tests__/tailwindDeclarations.ts +210 -0
  24. package/src/modules/access/api.ts +140 -6
  25. package/src/modules/access/components/ManageAccessDialog.tsx +1299 -561
  26. package/src/modules/access/manage-access-affordance.ts +17 -0
  27. package/src/modules/admin/__tests__/AddMemberInput.test.tsx +297 -0
  28. package/src/modules/admin/__tests__/AdminRolesPage.capabilities.test.tsx +2 -2
  29. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +189 -0
  30. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +1 -1
  31. package/src/modules/admin/__tests__/ConnectionKeysPage.test.tsx +266 -0
  32. package/src/modules/admin/__tests__/DirectoryGroupsPage.suggest.test.tsx +182 -0
  33. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +165 -14
  34. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +401 -4
  35. package/src/modules/admin/__tests__/group-members-path.test.ts +27 -0
  36. package/src/modules/admin/components/AddMemberInput.tsx +268 -0
  37. package/src/modules/admin/components/AdminRolesPage.tsx +97 -132
  38. package/src/modules/admin/components/ConnectionKeysPage.tsx +269 -0
  39. package/src/modules/admin/components/DirectoryGroupsPage.tsx +91 -39
  40. package/src/modules/admin/components/UserAccountsPage.tsx +271 -37
  41. package/src/modules/admin/components/connection-keys-grouping.ts +43 -0
  42. package/src/modules/admin/components/group-members-path.ts +32 -0
  43. package/src/modules/admin/services/connection-keys.api.ts +47 -0
  44. package/src/modules/admin/services/roles.api.ts +12 -1
  45. package/src/modules/auth/__tests__/AccountPage.test.tsx +50 -2
  46. package/src/modules/auth/components/AccountPage.tsx +73 -54
  47. package/src/modules/auth/components/LoginScreen.tsx +1 -0
  48. package/src/modules/auth/services/account.api.ts +78 -4
  49. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +144 -0
  50. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +422 -0
  51. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +431 -0
  52. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +193 -0
  53. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +142 -0
  54. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +202 -0
  55. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +205 -13
  56. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +271 -0
  57. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +208 -0
  58. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +286 -0
  59. package/src/modules/change-requests/__tests__/propose.concurrent.test.ts +273 -0
  60. package/src/modules/change-requests/__tests__/readFailure.test.ts +122 -0
  61. package/src/modules/change-requests/__tests__/useCrFileDiffs.test.tsx +238 -0
  62. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +56 -1
  63. package/src/modules/change-requests/__tests__/useForkPointFile.test.tsx +79 -0
  64. package/src/modules/change-requests/components/BranchFilePreview.tsx +357 -0
  65. package/src/modules/change-requests/components/ChangeBox.tsx +31 -2
  66. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +862 -72
  67. package/src/modules/change-requests/components/CrFileTree.tsx +74 -58
  68. package/src/modules/change-requests/components/FileChangeBoxes.tsx +19 -15
  69. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +41 -7
  70. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +181 -23
  71. package/src/modules/change-requests/hooks/useFileOnBranch.ts +70 -7
  72. package/src/modules/change-requests/hooks/useForkPointFile.ts +77 -0
  73. package/src/modules/change-requests/services/change-requests.api.ts +57 -1
  74. package/src/modules/change-requests/services/denied-file.api.ts +53 -0
  75. package/src/modules/change-requests/services/propose.api.ts +97 -8
  76. package/src/modules/change-requests/utils/approval.ts +15 -0
  77. package/src/modules/change-requests/utils/author.ts +32 -0
  78. package/src/modules/change-requests/utils/readFailure.ts +110 -0
  79. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +20 -0
  80. package/src/modules/git/components/FileHistoryPanel.tsx +5 -0
  81. package/src/modules/git/components/PullRequestsForMe.tsx +51 -24
  82. package/src/modules/git/services/__tests__/error-messages.test.ts +29 -0
  83. package/src/modules/git/services/error-messages.ts +12 -0
  84. package/src/modules/git/services/pr-prompts.ts +5 -5
  85. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +401 -0
  86. package/src/modules/layout/__tests__/SidebarFooterGrid.test.tsx +286 -0
  87. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +61 -0
  88. package/src/modules/layout/components/AppLayout.tsx +2 -0
  89. package/src/modules/layout/components/MobileChatLayout.tsx +4 -1
  90. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +4 -1
  91. package/src/modules/layout/components/SidebarFrame.tsx +108 -3
  92. package/src/modules/library/__tests__/AddToPluginDialog.test.tsx +171 -5
  93. package/src/modules/library/__tests__/DeleteToolDialog.test.tsx +356 -0
  94. package/src/modules/library/__tests__/IntegrationsSetupReminder.test.tsx +60 -0
  95. package/src/modules/library/__tests__/LibraryCard.test.tsx +91 -10
  96. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +242 -107
  97. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +103 -98
  98. package/src/modules/library/__tests__/LinkSkillPanel.test.tsx +20 -5
  99. package/src/modules/library/__tests__/LockedPluginView.test.tsx +97 -7
  100. package/src/modules/library/__tests__/NewPluginDialog.test.tsx +13 -4
  101. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +79 -3
  102. package/src/modules/library/__tests__/PersonalPluginPage.test.tsx +201 -0
  103. package/src/modules/library/__tests__/PluginExtras.test.tsx +100 -9
  104. package/src/modules/library/__tests__/PluginJoinRequests.test.tsx +60 -1
  105. package/src/modules/library/__tests__/PluginPage.test.tsx +258 -6
  106. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +16 -56
  107. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +155 -152
  108. package/src/modules/library/__tests__/PluginsSidebarMenu.test.tsx +16 -0
  109. package/src/modules/library/__tests__/SharedViaPlugins.test.tsx +106 -0
  110. package/src/modules/library/__tests__/SkillPage.test.tsx +386 -80
  111. package/src/modules/library/__tests__/SkillsTree.test.tsx +293 -4
  112. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +582 -71
  113. package/src/modules/library/__tests__/ToolPage.test.tsx +87 -4
  114. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +173 -26
  115. package/src/modules/library/__tests__/auth-harness.tsx +9 -9
  116. package/src/modules/library/__tests__/card-row-menu.test.tsx +320 -0
  117. package/src/modules/library/__tests__/library-data.mapping.test.tsx +98 -0
  118. package/src/modules/library/__tests__/library-data.stale.test.tsx +121 -28
  119. package/src/modules/library/__tests__/library-data.test.ts +7 -0
  120. package/src/modules/library/__tests__/library-paths.test.ts +47 -4
  121. package/src/modules/library/__tests__/link-membership.test.ts +13 -4
  122. package/src/modules/library/__tests__/name-with-badges.test.tsx +273 -0
  123. package/src/modules/library/__tests__/newSkillMarkdown.test.ts +30 -0
  124. package/src/modules/library/__tests__/owner-pill.test.tsx +357 -0
  125. package/src/modules/library/__tests__/pending-tools.test.tsx +400 -0
  126. package/src/modules/library/__tests__/plugin-entries.test.ts +122 -0
  127. package/src/modules/library/__tests__/plugin-summary.test.ts +36 -1
  128. package/src/modules/library/__tests__/status.test.ts +82 -2
  129. package/src/modules/library/__tests__/tools.api.test.ts +44 -1
  130. package/src/modules/library/components/AccessRequestsBanner.tsx +85 -47
  131. package/src/modules/library/components/AddDialogTabs.tsx +103 -0
  132. package/src/modules/library/components/AddToPluginDialog.tsx +74 -18
  133. package/src/modules/library/components/IntegrationsSetupReminder.tsx +59 -0
  134. package/src/modules/library/components/ItemActionsMenu.tsx +288 -0
  135. package/src/modules/library/components/LibraryCard.tsx +146 -45
  136. package/src/modules/library/components/LibraryLayout.tsx +119 -256
  137. package/src/modules/library/components/LibraryPage.tsx +172 -39
  138. package/src/modules/library/components/LinkSkillPanel.tsx +1 -3
  139. package/src/modules/library/components/LockedPluginView.tsx +62 -34
  140. package/src/modules/library/components/NameWithBadges.tsx +164 -0
  141. package/src/modules/library/components/NewPluginDialog.tsx +16 -2
  142. package/src/modules/library/components/PageActions.tsx +11 -9
  143. package/src/modules/library/components/{PendingSkillReview.tsx → PendingItemReview.tsx} +14 -7
  144. package/src/modules/library/components/PersonalAddDialog.tsx +68 -18
  145. package/src/modules/library/components/PersonalPluginPage.tsx +121 -22
  146. package/src/modules/library/components/PluginExtras.tsx +140 -17
  147. package/src/modules/library/components/PluginIndexRow.tsx +47 -12
  148. package/src/modules/library/components/PluginPage.tsx +157 -41
  149. package/src/modules/library/components/PluginRows.tsx +286 -0
  150. package/src/modules/library/components/PluginsSidebar.tsx +239 -263
  151. package/src/modules/library/components/PluginsSidebarMenu.tsx +26 -1
  152. package/src/modules/library/components/ShareButton.tsx +17 -0
  153. package/src/modules/library/components/SkillsTree.tsx +141 -28
  154. package/src/modules/library/components/TeamRoute.tsx +15 -0
  155. package/src/modules/library/components/__tests__/upload-notices-once-per-page.test.tsx +144 -0
  156. package/src/modules/library/components/plugin-page-parts.tsx +103 -17
  157. package/src/modules/library/components/skill-page/SharedViaPlugins.tsx +6 -12
  158. package/src/modules/library/components/skill-page/SkillFilePane.tsx +5 -0
  159. package/src/modules/library/components/skill-page/SkillPage.tsx +274 -122
  160. package/src/modules/library/components/tool-page/DeleteToolDialog.tsx +218 -0
  161. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +79 -178
  162. package/src/modules/library/components/tool-page/ToolPage.tsx +106 -16
  163. package/src/modules/library/components/tool-page/ToolVarRow.tsx +42 -41
  164. package/src/modules/library/hooks/__tests__/useLibraryData.test.ts +98 -0
  165. package/src/modules/library/hooks/useLibraryData.ts +92 -19
  166. package/src/modules/library/routes/LibraryRoutes.tsx +14 -11
  167. package/src/modules/library/routes/WorkspaceItemRoute.tsx +77 -27
  168. package/src/modules/library/routes/library-paths.ts +26 -28
  169. package/src/modules/library/services/library.api.ts +38 -20
  170. package/src/modules/library/services/plugins.api.ts +69 -8
  171. package/src/modules/library/services/teams.api.ts +15 -0
  172. package/src/modules/library/services/tools.api.ts +78 -0
  173. package/src/modules/library/state/library-data.tsx +170 -32
  174. package/src/modules/library/utils/personal-plugin.ts +13 -15
  175. package/src/modules/library/utils/plugin-entries.ts +134 -0
  176. package/src/modules/library/utils/plugin-summary.ts +75 -9
  177. package/src/modules/library/utils/status.ts +135 -33
  178. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +8 -1
  179. package/src/modules/onboarding/__tests__/onboarding.test.tsx +853 -760
  180. package/src/modules/onboarding/agent-clients.ts +55 -23
  181. package/src/modules/onboarding/components/ConnectAgentPill.tsx +5 -1
  182. package/src/modules/onboarding/components/WelcomePage.tsx +98 -62
  183. package/src/modules/pr/services/pr-merge.api.ts +2 -1
  184. package/src/modules/review/components/MarkdownDiffViewer.tsx +53 -8
  185. package/src/modules/review/components/ReviewPanel.tsx +15 -17
  186. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +64 -0
  187. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +25 -1
  188. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +454 -117
  189. package/src/modules/secrets-vault/components/SecretsPage.tsx +48 -7
  190. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +84 -5
  191. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +425 -0
  192. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +417 -82
  193. package/src/modules/secrets-vault/components/__tests__/ToolSecretsPanel.test.tsx +105 -0
  194. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +407 -0
  195. package/src/modules/secrets-vault/probe/SavedKeyProbeResult.tsx +98 -0
  196. package/src/modules/secrets-vault/probe/__tests__/probe-verdict.test.ts +160 -0
  197. package/src/modules/secrets-vault/probe/probe-verdict.ts +108 -0
  198. package/src/modules/secrets-vault/probe/useSavedKeyProbe.ts +228 -0
  199. package/src/modules/secrets-vault/services/connect.api.ts +36 -5
  200. package/src/modules/secrets-vault/utils/connect-status.ts +98 -0
  201. package/src/modules/settings/components/ClaudeConnectionCard.tsx +9 -24
  202. package/src/modules/settings/components/ClaudeConnectionFields.tsx +23 -0
  203. package/src/modules/settings/components/DeploymentPage.tsx +10 -30
  204. package/src/modules/settings/components/MarketplaceSection.tsx +152 -0
  205. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +67 -4
  206. package/src/modules/settings/components/__tests__/MarketplaceSection.test.tsx +325 -0
  207. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +5 -5
  208. package/src/modules/settings/services/github-facade.api.ts +23 -0
  209. package/src/modules/settings/settings-nav-items.tsx +10 -2
  210. package/src/modules/setup/__tests__/setup.oidc.test.tsx +172 -0
  211. package/src/modules/setup/__tests__/setup.probe-refusal.test.tsx +123 -0
  212. package/src/modules/setup/__tests__/setup.test.tsx +497 -4
  213. package/src/modules/setup/__tests__/useSetupStatus.test.tsx +130 -0
  214. package/src/modules/setup/components/SetupGate.tsx +16 -16
  215. package/src/modules/setup/components/SetupScreen.tsx +521 -43
  216. package/src/modules/setup/hooks/useSetupStatus.ts +93 -0
  217. package/src/modules/setup/services/setup.api.ts +140 -3
  218. package/src/modules/setup/utils/__tests__/root-folders.test.ts +72 -0
  219. package/src/modules/setup/utils/root-folders.ts +46 -0
  220. package/src/modules/toolbar/assets/claude-setup/01-add-manually.webp +0 -0
  221. package/src/modules/toolbar/assets/claude-setup/02-add-configuration.webp +0 -0
  222. package/src/modules/toolbar/assets/claude-setup/03-connect-account.webp +0 -0
  223. package/src/modules/toolbar/assets/claude-setup/04-pick-instance.webp +0 -0
  224. package/src/modules/toolbar/assets/claude-setup/05-plugins-add.webp +0 -0
  225. package/src/modules/toolbar/assets/claude-setup/06-add-marketplace.webp +0 -0
  226. package/src/modules/toolbar/assets/claude-setup/07-paste-url-sync.webp +0 -0
  227. package/src/modules/toolbar/assets/claude-setup/08-install-plugins.webp +0 -0
  228. package/src/modules/toolbar/assets/claude-setup/09-select-repository.webp +0 -0
  229. package/src/modules/toolbar/assets/claude-setup/10-connector-not-added.webp +0 -0
  230. package/src/modules/toolbar/assets/claude-setup/11-add-custom-connector.webp +0 -0
  231. package/src/modules/toolbar/assets/claude-setup/README.md +68 -0
  232. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +296 -0
  233. package/src/modules/toolbar/components/ClaudeMarketplaceCarousel.tsx +107 -0
  234. package/src/modules/toolbar/components/ClaudeRegistrationSteps.tsx +127 -0
  235. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +100 -0
  236. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +177 -118
  237. package/src/modules/toolbar/components/ScreenshotStep.tsx +77 -0
  238. package/src/modules/toolbar/components/SetupCarousel.tsx +177 -0
  239. package/src/modules/toolbar/components/__tests__/AgentInstructionsCard.test.tsx +370 -0
  240. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +542 -42
  241. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +2 -2
  242. package/src/modules/toolbar/components/__tests__/claude-setup-shots.test.ts +104 -0
  243. package/src/modules/toolbar/components/claude-connector-slide.tsx +38 -0
  244. package/src/modules/toolbar/components/claude-setup-shots.ts +167 -0
  245. package/src/modules/toolbar/components/deployment-address.ts +29 -0
  246. package/src/modules/toolbar/components/setup-step-parts.tsx +35 -0
  247. package/src/modules/toolbar/services/__tests__/agent-instructions.api.test.ts +89 -0
  248. package/src/modules/toolbar/services/agent-instructions.api.ts +167 -0
  249. package/src/modules/toolbar/services/external-api-keys.api.ts +6 -0
  250. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +43 -0
  251. package/src/modules/workflow/state/EventBusProvider.tsx +122 -11
  252. package/src/modules/workflow/state/__tests__/EventBusProvider.storage.test.tsx +87 -0
  253. package/src/modules/workflow/state/__tests__/EventBusProvider.watch.test.tsx +223 -0
  254. package/src/modules/workflow/state/event-bus.context.ts +10 -0
  255. package/src/modules/workspace/__tests__/testFixtures.ts +5 -3
  256. package/src/modules/workspace/components/FileExplorer.tsx +1295 -191
  257. package/src/modules/workspace/components/FileRoute.tsx +353 -36
  258. package/src/modules/workspace/components/FileViewer.tsx +166 -45
  259. package/src/modules/workspace/components/KbDocumentShell.tsx +50 -6
  260. package/src/modules/workspace/components/KbPageHeader.tsx +120 -55
  261. package/src/modules/workspace/components/TreeActionConfirm.tsx +350 -0
  262. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +2473 -129
  263. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +731 -18
  264. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +331 -12
  265. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +39 -0
  266. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +33 -20
  267. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +4 -5
  268. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +13 -4
  269. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +4 -3
  270. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +8 -14
  271. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +75 -16
  272. package/src/modules/workspace/components/renderers/KbImage.tsx +180 -0
  273. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +22 -6
  274. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +48 -22
  275. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +4 -5
  276. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +4 -3
  277. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +4 -3
  278. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +12 -0
  279. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +57 -9
  280. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +13 -1
  281. package/src/modules/workspace/components/renderers/__tests__/ImageRenderer.test.tsx +163 -0
  282. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +237 -0
  283. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +108 -14
  284. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +14 -1
  285. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +16 -1
  286. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +66 -1
  287. package/src/modules/workspace/components/renderers/index.ts +53 -2
  288. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +25 -4
  289. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +40 -0
  290. package/src/modules/workspace/hooks/__tests__/useImageRevision.test.tsx +174 -0
  291. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +179 -1
  292. package/src/modules/workspace/hooks/__tests__/useWorkspaceImageResolver.test.tsx +122 -0
  293. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +892 -7
  294. package/src/modules/workspace/hooks/useImageRevision.ts +101 -0
  295. package/src/modules/workspace/hooks/useMergedWorkspaceTree.ts +22 -3
  296. package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +55 -0
  297. package/src/modules/workspace/hooks/useWorkspaceState.ts +424 -66
  298. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +279 -3
  299. package/src/modules/workspace/routing/kb-routes.ts +206 -29
  300. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +57 -1
  301. package/src/modules/workspace/services/workspace.api.ts +57 -4
  302. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +343 -0
  303. package/src/modules/workspace/state/__tests__/upload-lands-where-it-was-dropped.test.tsx +158 -0
  304. package/src/modules/workspace/state/open-change-requests.tsx +100 -12
  305. package/src/modules/workspace/state/workspace.context.ts +125 -19
  306. package/src/modules/workspace/utils/__tests__/file-trace.test.ts +73 -0
  307. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +220 -6
  308. package/src/modules/workspace/utils/__tests__/pasteLink.test.ts +76 -0
  309. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +364 -0
  310. package/src/modules/workspace/utils/__tests__/uploadError.test.ts +35 -0
  311. package/src/modules/workspace/utils/file-trace.ts +50 -0
  312. package/src/modules/workspace/utils/fileTree.ts +112 -36
  313. package/src/modules/workspace/utils/frontmatter.ts +8 -4
  314. package/src/modules/workspace/utils/pasteLink.ts +90 -0
  315. package/src/modules/workspace/utils/treeConfirm.ts +338 -0
  316. package/src/modules/workspace/utils/uploadError.ts +29 -0
  317. package/src/shared/__tests__/marketplace-url.test.ts +6 -1
  318. package/src/shared/components/Button.tsx +16 -2
  319. package/src/shared/components/Dialog.tsx +27 -11
  320. package/src/shared/components/Menu.tsx +13 -1
  321. package/src/shared/components/PageShell.tsx +13 -8
  322. package/src/shared/components/__tests__/primitives.test.tsx +116 -2
  323. package/src/shared/components/__tests__/useFocusHandoff.test.tsx +192 -0
  324. package/src/shared/components/index.ts +2 -0
  325. package/src/shared/components/useDismissableMenu.ts +32 -10
  326. package/src/shared/components/useFocusHandoff.ts +51 -0
  327. package/src/shared/components/useLatestRef.ts +28 -0
  328. package/src/shared/markdown/Markdown.tsx +12 -3
  329. package/src/shared/markdown/__tests__/escapeSpacesInLinkDestinations.test.ts +39 -0
  330. package/src/shared/markdown/hrefs.ts +50 -0
  331. package/src/shared/marketplace-url.ts +33 -5
  332. package/src/shared/mcp/ChatGptInstallLink.tsx +3 -3
  333. package/src/shared/mcp/ConnectionInstructions.tsx +38 -27
  334. package/src/shared/mcp/__tests__/connect-snippets.test.ts +3 -3
  335. package/src/shared/mcp/connect-snippets.ts +14 -9
  336. package/src/shared/mcp/index.ts +1 -1
  337. package/src/shared/theme/__tests__/header-band.test.ts +197 -0
  338. package/src/shared/theme/header.ts +75 -0
  339. package/src/shared/theme/measure.ts +7 -4
  340. package/src/shared/theme/tokens.css +25 -0
  341. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +0 -363
  342. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +0 -97
  343. package/src/modules/library/components/PluginsIndexPage.tsx +0 -270
  344. package/src/modules/update-check/__tests__/UpdateBanner.test.tsx +0 -126
  345. package/src/modules/update-check/components/UpdateBanner.tsx +0 -92
  346. package/src/modules/update-check/services/update-check.api.ts +0 -24
@@ -24,9 +24,11 @@ import {
24
24
  Pin,
25
25
  PinOff,
26
26
  Users,
27
+ Undo2,
27
28
  } from 'lucide-react';
28
- import type { FileTreeEntry, PullRequestSummary } from '@bevel-software/platform-shared';
29
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
29
30
  import {
31
+ isProtectedBranch,
30
32
  validateFilename,
31
33
  KNOWLEDGE_BASE_DIR,
32
34
  DATA_DIR,
@@ -35,21 +37,58 @@ import {
35
37
  AGENTS_DIR,
36
38
  PIPELINES_DIR,
37
39
  } from '@bevel-software/platform-shared';
38
- import { useWorkspace } from '../state/workspace.context';
39
- import { findKbRoot, KB_ROOT_DIRS } from '../utils/fileTree';
40
+ import {
41
+ KNOWLEDGE_UPLOAD_TARGET,
42
+ useWorkspace,
43
+ type UploadInput,
44
+ type UploadTarget,
45
+ } from '../state/workspace.context';
46
+ import { rootAnchoredPath } from '../utils/pasteLink';
47
+ import {
48
+ checkoutRoot,
49
+ KB_ROOT_DIRS,
50
+ pathExistsInTree,
51
+ subtreeHasVisibleEntries,
52
+ subtreeWithheld,
53
+ treeHasVisibleEntries,
54
+ } from '../utils/fileTree';
55
+ import { uploadErrorNextStep } from '../utils/uploadError';
40
56
  import { useMergedWorkspaceTree } from '../hooks/useMergedWorkspaceTree';
41
57
  import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequestDialog';
42
- import { PR_STALE_EVENT } from '../../../core/events';
58
+ import { PR_STALE_EVENT, SUGGESTIONS_RETRACTED_EVENT } from '../../../core/events';
59
+ import {
60
+ listChangeRequestsUnderFolder,
61
+ removeFolderFromChangeRequests,
62
+ } from '../../change-requests/services/change-requests.api';
63
+ import { cancelPullRequest } from '../../pr/services/pr-cancel.api';
43
64
  import { snapshotEntries } from '../utils/readDroppedEntries';
44
- import { useFileNav } from '../routing/kb-routes';
65
+ import { useSearchParams } from 'react-router-dom';
66
+ import { CR_FILE_PARAM, CR_PARAM, useFileNav } from '../routing/kb-routes';
67
+ import { rawFileUrl } from '../services/workspace.api';
45
68
  import { downloadViaBlob } from './renderers/downloadFile';
46
69
  import { cn } from '../../../lib/utils';
47
- import { MenuPanel, MenuItem, TextField, IconButton } from '../../../shared/components';
70
+ import { Banner, MenuPanel, MenuItem, TextField, IconButton } from '../../../shared/components';
48
71
  import { useDismissableMenu, usePointerMenuPosition } from '../../../shared/components';
49
72
  import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
50
- import { PullRequestsForMe } from '../../git/components/PullRequestsForMe';
73
+ import { AdminContext } from '../../admin/state/admin.context';
51
74
  import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
75
+ import { offersManageAccess } from '../../access/manage-access-affordance';
52
76
  import { useAppRegistry } from '../../../core/registry';
77
+ import { fetchFileAccess, fetchProspectiveAccess } from '../../access/api';
78
+ import {
79
+ TreeActionConfirmDialog,
80
+ type DeleteMode,
81
+ type FolderProposals,
82
+ type MoveAccessChange,
83
+ type TreeConfirmRequest,
84
+ } from './TreeActionConfirm';
85
+ import {
86
+ ACCESS_LOOKUP_TIMEOUT_MS,
87
+ accessChangeOf,
88
+ moveWarnings,
89
+ platformFileDragRefusal,
90
+ platformFileMoveRefusal,
91
+ } from '../utils/treeConfirm';
53
92
 
54
93
  /**
55
94
  * The tree row — the prototype's `.trow` (proto:684-693), and token for token
@@ -71,9 +110,10 @@ const ROW_TONE = (current: boolean) =>
71
110
  const indentFor = (depth: number) => 10 + depth * 13;
72
111
 
73
112
  /**
74
- * The caret's slot — 13px wide, and rendered EMPTY for a file and for a
75
- * childless folder. It is what keeps a file's name in line with its siblings'
76
- * once the icons are gone: the indent is the tree, so it has to survive them
113
+ * The caret's slot — 13px wide, and rendered EMPTY for a file. Every folder
114
+ * shows the caret, an empty one included: without it a folder reads as a file.
115
+ * The slot is what keeps a file's name in line with its siblings' once the
116
+ * icons are gone: the indent is the tree, so it has to survive them
77
117
  * (proto:3571-3572).
78
118
  */
79
119
  function CaretSlot({ open, show }: { open?: boolean; show: boolean }) {
@@ -89,6 +129,37 @@ function CaretSlot({ open, show }: { open?: boolean; show: boolean }) {
89
129
  );
90
130
  }
91
131
 
132
+ /** How many trailing characters of a file name always stay on screen. */
133
+ const FILE_NAME_TAIL = 8;
134
+
135
+ /**
136
+ * A file's name, truncated in the MIDDLE when it does not fit: the lead is
137
+ * shortened with an ellipsis and the last `FILE_NAME_TAIL` characters stay —
138
+ * for an ordinary name that is the extension, the part that says what the
139
+ * file is. A name that fits reads exactly as before, because the two halves
140
+ * sit flush against each other.
141
+ *
142
+ * The split halves are a picture, so they are hidden from assistive tech; the
143
+ * whole name is carried once, unsplit, in a visually hidden span. A folder has
144
+ * no extension to protect and keeps the plain end truncation.
145
+ */
146
+ function FileName({ name }: { name: string }) {
147
+ // By code point, so the split never lands inside a surrogate pair.
148
+ const chars = Array.from(name);
149
+ if (chars.length <= FILE_NAME_TAIL) return <span className="truncate">{name}</span>;
150
+ return (
151
+ <span className="flex min-w-0" data-file-name>
152
+ <span className="sr-only">{name}</span>
153
+ <span aria-hidden className="truncate" data-name-lead>
154
+ {chars.slice(0, -FILE_NAME_TAIL).join('')}
155
+ </span>
156
+ <span aria-hidden className="flex-none whitespace-pre" data-name-tail>
157
+ {chars.slice(-FILE_NAME_TAIL).join('')}
158
+ </span>
159
+ </span>
160
+ );
161
+ }
162
+
92
163
  // ── Pinned folders (client-side, localStorage) ──
93
164
 
94
165
  const PINNED_STORAGE_KEY = 'bevel-pinned-folders';
@@ -147,10 +218,35 @@ interface SuggestionsController {
147
218
  crFor(path: string): number | null;
148
219
  /** Open the shared change-request dialog on the request this path belongs to. */
149
220
  open(path: string, crNumber: number): void;
221
+ /**
222
+ * The caller AUTHORED this request, so they may take it back.
223
+ *
224
+ * Every suggestion row is the caller's own today — the map they are
225
+ * synthesized from is `/mine`. The menu asks anyway, because the answer is
226
+ * what the offer means: an owner looking at someone else's proposal must
227
+ * never be shown a Withdraw (their "no" is Decline, in the dialog), and
228
+ * this predicate is already right for the day those rows appear here.
229
+ */
230
+ mine(crNumber: number): boolean;
231
+ /**
232
+ * Every file the request carries — a multi-file drop is ONE request, and
233
+ * withdrawing it withdraws all of them, which the confirmation says out loud.
234
+ * Empty when the request has not arrived in the shared list yet.
235
+ */
236
+ filesOf(path: string, crNumber: number): string[];
237
+ /**
238
+ * Cancel the request down the author-cancel path — the same call the file
239
+ * page's change box makes — and tell the app its request list changed, so
240
+ * the rows go without a reload.
241
+ */
242
+ withdraw(crNumber: number): Promise<void>;
150
243
  }
151
244
  const SuggestionsContext = createContext<SuggestionsController>({
152
245
  crFor: () => null,
153
246
  open: () => {},
247
+ mine: () => false,
248
+ filesOf: () => [],
249
+ withdraw: async () => {},
154
250
  });
155
251
  const useSuggestions = () => useContext(SuggestionsContext);
156
252
 
@@ -167,8 +263,60 @@ export interface TreeNav {
167
263
  /** The workspace-relative path the surface is showing — lights its row, reveals its folders. */
168
264
  activePath: string | null;
169
265
  open(path: string): void;
266
+ /**
267
+ * Extra items for a row's context menu, decided by the SURFACE for the
268
+ * entry at hand — injected, so the one tree serves every nav without
269
+ * growing a verb per caller. Rendered after the tree's own create items,
270
+ * in the order given; absent or empty, the menu is the tree's alone.
271
+ * (The Library's Plugins tree adds "New plugin" on folders this way.)
272
+ */
273
+ menuItems?(entry: FileTreeEntry): TreeMenuItem[];
274
+ }
275
+
276
+ /** One injected context-menu item — see `TreeNav.menuItems`. */
277
+ export interface TreeMenuItem {
278
+ /** Stable within one menu; keys the rendered item. */
279
+ id: string;
280
+ label: string;
281
+ icon?: ReactNode;
282
+ onSelect(): void;
170
283
  }
171
284
  const TreeNavContext = createContext<TreeNav>({ activePath: null, open: () => {} });
285
+
286
+ /**
287
+ * Which tree this is, for the upload banners — see `UploadTarget`. Every drop
288
+ * inside a `TreeChrome` carries it into `dispatchUpload`, and the
289
+ * `UploadNotices` inside the same chrome renders only the banners that come
290
+ * back with it. One page can hold two of these trees (the Library sidebar
291
+ * holds `Skills/` and `Plugins/`); before they were told apart, one drop
292
+ * painted its notice in both.
293
+ */
294
+ const UploadTargetContext = createContext<UploadTarget>(KNOWLEDGE_UPLOAD_TARGET);
295
+
296
+ /** The tree the surrounding `TreeChrome` is, for a drop or a banner. */
297
+ const useUploadTarget = () => useContext(UploadTargetContext);
298
+
299
+ /**
300
+ * Ask before a delete or a move — see `TreeActionConfirm`. `TreeChrome` holds
301
+ * the one open request and renders its dialog; a row outside any chrome has
302
+ * no one to ask, so the default runs the operation as it always did.
303
+ */
304
+ const TreeConfirmContext = createContext<(request: TreeConfirmRequest) => void>((request) => {
305
+ void request.run();
306
+ });
307
+ const useTreeConfirm = () => useContext(TreeConfirmContext);
308
+
309
+ /**
310
+ * The row button for a path, found in the DOM. A move is dropped on ANOTHER
311
+ * row, so the dragged row's ref is not in hand where the drop lands; the path
312
+ * is. (A pinned folder renders twice — the first match is the one to return to.)
313
+ */
314
+ function rowForPath(path: string): HTMLElement | null {
315
+ for (const el of document.querySelectorAll<HTMLElement>('[data-tree-path]')) {
316
+ if (el.dataset.treePath === path) return el;
317
+ }
318
+ return null;
319
+ }
172
320
  const useTreeNav = () => useContext(TreeNavContext);
173
321
 
174
322
  /** Depth-first lookup of a tree entry by its exact relativePath. */
@@ -182,6 +330,63 @@ function findEntryByPath(node: FileTreeEntry, path: string): FileTreeEntry | nul
182
330
  return null;
183
331
  }
184
332
 
333
+ // ── Download permission ──
334
+
335
+ /**
336
+ * The tooltip on a Download the caller may not use, and the reason a late
337
+ * refusal gives. One string, because the menu and the 403 notice are two
338
+ * views of the SAME verdict and must not drift.
339
+ */
340
+ export const DOWNLOAD_DENIED_MESSAGE = "You don't have download permission for this item";
341
+
342
+ /**
343
+ * The entry's `download:` verdict, asked ONCE — the menu mounts when it
344
+ * opens and unmounts when it closes, so the request is per menu open, never
345
+ * per tree render (one request per row was the alternative, and it is why
346
+ * this lives here and not on the row).
347
+ *
348
+ * `null` means "not known": the lookup is in flight, there is nothing to ask
349
+ * about, or it failed. The item stays ENABLED on null — a flash of disabled
350
+ * on every menu open would be worse than the 403 this preflight exists to
351
+ * avoid, and the backend's own gate is authoritative either way.
352
+ *
353
+ * The path goes to the server workspace-relative, exactly as the download
354
+ * URLs send it: the access route strips `<kbDirName>/` itself, with the same
355
+ * strip the download gate applies, so the preflight asks the question the
356
+ * gate will answer. A path the route refuses outright (the tree root's `.`)
357
+ * throws and leaves the verdict unknown, which is the enabled-as-today case.
358
+ */
359
+ function useDownloadVerdict(entry: FileTreeEntry | null): boolean | null {
360
+ const { workspaceId } = useWorkspace();
361
+ const path = entry?.relativePath ?? null;
362
+ const kind = entry?.type === 'directory' ? 'folder' : 'file';
363
+ // The verdict is stored WITH the question it answers, and read back only
364
+ // while that question still stands. Keying it — rather than clearing it
365
+ // when a new lookup starts — is what makes an answer about a PREVIOUS
366
+ // entry unreadable as this one's: a stale `false` would disable a Download
367
+ // the caller does have, and would stay disabled for good if the new lookup
368
+ // failed, because the failure path deliberately leaves the verdict alone.
369
+ // Keying also costs no extra render, so there is no flash of a wrong state.
370
+ const key = workspaceId && path !== null ? `${workspaceId}\u0000${path}\u0000${kind}` : null;
371
+ const [answered, setAnswered] = useState<{ key: string; verdict: boolean } | null>(null);
372
+ useEffect(() => {
373
+ if (!workspaceId || path === null || key === null) return;
374
+ let cancelled = false;
375
+ fetchFileAccess(workspaceId, path, kind)
376
+ .then((res) => {
377
+ if (!cancelled) setAnswered({ key, verdict: res.canDownload });
378
+ })
379
+ .catch(() => {
380
+ // Default-allow, as `useFileAccess` does: a transient lookup failure
381
+ // must not take an action away from someone who has it.
382
+ });
383
+ return () => {
384
+ cancelled = true;
385
+ };
386
+ }, [key, workspaceId, path, kind]);
387
+ return answered !== null && answered.key === key ? answered.verdict : null;
388
+ }
389
+
185
390
  // ── Context Menu ──
186
391
 
187
392
  function ContextMenu({
@@ -193,29 +398,60 @@ function ContextMenu({
193
398
  onCreateFile,
194
399
  onCreateFolder,
195
400
  onRename,
401
+ renameRefusal = null,
196
402
  onDownload,
403
+ onWithdraw,
197
404
  returnFocusTo,
198
405
  deletable = true,
406
+ extraItems = [],
407
+ proposed = false,
199
408
  }: {
200
409
  x: number;
201
410
  y: number;
202
411
  entry: FileTreeEntry;
203
412
  isRoot: boolean;
413
+ /**
414
+ * The entry exists only on a change request's branch. Nothing that acts on
415
+ * THIS branch's copy applies (there is none), so only the path and Manage
416
+ * access — which follows the file to the proposal — are offered.
417
+ */
418
+ proposed?: boolean;
204
419
  /** False for a folder the platform owns (a reserved root): no Delete. */
205
420
  deletable?: boolean;
206
421
  onClose: () => void;
207
422
  onCreateFile?: () => void;
208
423
  onCreateFolder?: () => void;
209
424
  onRename?: () => void;
425
+ /**
426
+ * Why Rename is not on offer for this row — a platform file stays in its
427
+ * folder, and a rename is a move. The item is still drawn and still
428
+ * reachable: an affordance that vanishes teaches nobody why.
429
+ */
430
+ renameRefusal?: string | null;
210
431
  onDownload?: () => void;
432
+ /**
433
+ * Take this suggestion back. Supplied ONLY by a proposed row whose change
434
+ * request the caller authored — its absence is what keeps Withdraw off an
435
+ * owner's view of someone else's proposal, the same way `onRename`'s
436
+ * absence keeps Rename off a row that cannot be renamed.
437
+ */
438
+ onWithdraw?: () => void;
439
+ /** The surface's own items for this entry — see `TreeNav.menuItems`. */
440
+ extraItems?: TreeMenuItem[];
211
441
  /** The row this menu was opened from — Escape hands focus back to it. */
212
442
  returnFocusTo?: React.RefObject<HTMLElement | null>;
213
443
  }) {
214
- const { deleteEntry, unzipHere } = useWorkspace();
444
+ const { deleteEntry, unzipHere, kbDirName, fileTree } = useWorkspace();
445
+ const suggestions = useSuggestions();
215
446
  const { isPinned, togglePin, available: pinning } = usePinned();
216
447
  const openManageAccess = useManageAccess();
448
+ const confirm = useTreeConfirm();
217
449
  const pinned = isPinned(entry.relativePath);
218
450
  const [unzipping, setUnzipping] = useState(false);
451
+ // Asked only where a Download is on offer — a proposed row or an absent
452
+ // folder has none, and must not spend a request finding that out.
453
+ const canDownload = useDownloadVerdict(onDownload ? entry : null);
454
+ const downloadDenied = canDownload === false;
219
455
  // Outside-click, Escape, and focus return — none of which `MenuPanel`
220
456
  // provides (it is presentation only, by design).
221
457
  const ref = useDismissableMenu<HTMLDivElement>({ open: true, onClose, returnFocusTo });
@@ -229,34 +465,97 @@ function ContextMenu({
229
465
  // Only files whose name ends with `.zip` (case-insensitive) get the
230
466
  // extraction affordance — matches the OS shell-extension behavior users
231
467
  // already know from Windows Explorer / macOS Finder.
232
- const isZip = entry.type === 'file' && /\.zip$/i.test(entry.name);
468
+ const isZip = !proposed && entry.type === 'file' && /\.zip$/i.test(entry.name);
233
469
 
234
470
  // The one prototype context-menu item the platform has never had
235
- // (proto:3948). The page-level `⋯ → Copy path` does not cover it: that only
471
+ // (proto:3948). The page-level Share `⌄ → Copy path` does not cover it: that only
236
472
  // ever reaches the file you have open, never a folder row or an unopened
237
473
  // one. A clipboard write can be refused outright (a non-secure origin), and
238
474
  // a silent no-op is the worst possible answer to "copy this" — so a refusal
239
475
  // surfaces the same way every other failure in this tree does.
476
+ // The ROOT-ANCHORED form: pasted into a Markdown link it resolves from any
477
+ // folder, where the bare `knowledge-base/…` resolved against the linking
478
+ // file's own folder and landed on File not found.
240
479
  const handleCopyPath = async () => {
480
+ const copied = rootAnchoredPath(entry.relativePath);
241
481
  try {
242
- await navigator.clipboard.writeText(entry.relativePath);
482
+ await navigator.clipboard.writeText(copied);
243
483
  onClose();
244
484
  } catch (err) {
245
485
  console.error('Failed to copy path:', err);
246
486
  onClose();
247
- alert(`Couldn't copy the path to the clipboard.\n\n${entry.relativePath}`);
487
+ alert(`Couldn't copy the path to the clipboard.\n\n${copied}`);
248
488
  }
249
489
  };
250
490
 
251
- const handleDelete = async () => {
491
+ // Delete asks first; Confirm runs the delete exactly as the menu used to.
492
+ // A KB folder can also hold proposed files — the dialog then offers to take
493
+ // them out of their change requests as well (`runWithProposals`).
494
+ const repoFolder =
495
+ entry.type === 'directory' && kbDirName && entry.relativePath.startsWith(`${kbDirName}/`)
496
+ ? entry.relativePath.slice(kbDirName.length + 1)
497
+ : null;
498
+ const handleDelete = () => {
252
499
  onClose();
253
- try {
254
- await deleteEntry(entry.relativePath);
255
- } catch (err) {
256
- console.error('Failed to delete entry:', err);
257
- const msg = err instanceof Error ? err.message : String(err);
258
- alert(`Failed to delete ${entry.relativePath}:\n${msg}`);
259
- }
500
+ const deleteOnBranch = async (): Promise<boolean> => {
501
+ // A folder only proposed files put in the tree is not on this branch:
502
+ // nothing to delete here, and asking the server would only queue a
503
+ // commit for a path that does not exist.
504
+ if (fileTree && !pathExistsInTree(fileTree, entry.relativePath)) return true;
505
+ try {
506
+ return (await deleteEntry(entry.relativePath)) !== false;
507
+ } catch (err) {
508
+ console.error('Failed to delete entry:', err);
509
+ const msg = err instanceof Error ? err.message : String(err);
510
+ alert(`Failed to delete ${entry.relativePath}:\n${msg}`);
511
+ return false;
512
+ }
513
+ };
514
+ confirm({
515
+ kind: 'delete',
516
+ entry,
517
+ returnFocusTo: () => returnFocusTo?.current ?? null,
518
+ // The folder it was in — the row itself is gone once the delete lands.
519
+ focusAfterRun: () => rowForPath(entry.relativePath.split('/').slice(0, -1).join('/')),
520
+ isProposed: (path) => suggestions.crFor(path) !== null,
521
+ // Entries under THIS folder the caller's read rules kept out: the
522
+ // delete then takes files the tree cannot count, and the question says
523
+ // so instead of naming a number that is too small.
524
+ partial: (entry.withheld ?? 0) > 0,
525
+ run: async () => {
526
+ await deleteOnBranch();
527
+ },
528
+ ...(repoFolder !== null && {
529
+ runWithProposals: async () => {
530
+ // The branch first: a delete that failed (or was called off over
531
+ // unsaved tabs) must not have already emptied the proposals.
532
+ if (!(await deleteOnBranch())) return;
533
+ let leftovers: string[];
534
+ try {
535
+ // What the removal could not take out, said rather than left to
536
+ // reappear unexplained in the tree once the refetch lands.
537
+ leftovers = (await removeFolderFromChangeRequests(repoFolder)).flatMap((r) => [
538
+ ...(r.stillProposed.length > 0
539
+ ? [`#${r.number} still proposes ${r.stillProposed.join(', ')} — added while the folder was being deleted.`]
540
+ : []),
541
+ ...(r.keptForSaves ? [`#${r.number} stays open: a save to it was still landing.`] : []),
542
+ ]);
543
+ } catch (err) {
544
+ console.error('Failed to remove proposed changes:', err);
545
+ const msg = err instanceof Error ? err.message : String(err);
546
+ alert(`Deleted ${entry.name}, but couldn't remove its proposed changes:\n${msg}`);
547
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
548
+ return;
549
+ }
550
+ // The rows and dots go now; the refetch confirms it.
551
+ window.dispatchEvent(new CustomEvent(SUGGESTIONS_RETRACTED_EVENT, { detail: { folder: repoFolder } }));
552
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
553
+ if (leftovers.length > 0) {
554
+ alert(`Deleted ${entry.name} and its proposed changes, except:\n${leftovers.join('\n')}`);
555
+ }
556
+ },
557
+ }),
558
+ });
260
559
  };
261
560
 
262
561
  const handleUnzip = async () => {
@@ -309,6 +608,13 @@ function ContextMenu({
309
608
  <span className="flex items-center gap-2"><FolderPlus size={14} />New folder</span>
310
609
  </MenuItem>
311
610
  )}
611
+ {/* The surface's own verbs for this entry, after the tree's create
612
+ items — a "make a thing here" reads with the other two. */}
613
+ {extraItems.map((item) => (
614
+ <MenuItem key={item.id} role="menuitem" onClick={() => { item.onSelect(); onClose(); }}>
615
+ <span className="flex items-center gap-2">{item.icon}{item.label}</span>
616
+ </MenuItem>
617
+ ))}
312
618
  {isZip && (
313
619
  <MenuItem role="menuitem" onClick={handleUnzip} disabled={unzipping}>
314
620
  <span className="flex items-center gap-2">
@@ -318,17 +624,33 @@ function ContextMenu({
318
624
  </MenuItem>
319
625
  )}
320
626
  {onDownload && (
321
- <MenuItem role="menuitem" onClick={() => { onDownload(); onClose(); }}>
627
+ <MenuItem
628
+ role="menuitem"
629
+ // `aria-disabled`, not `disabled`: the item keeps its tooltip and
630
+ // its place in the tab order, so the reason is reachable by mouse
631
+ // AND by keyboard. Activation is refused here instead — which is
632
+ // what stops Enter and Space on the focused item, not just a click.
633
+ aria-disabled={downloadDenied || undefined}
634
+ title={downloadDenied ? DOWNLOAD_DENIED_MESSAGE : undefined}
635
+ onClick={() => {
636
+ if (downloadDenied) return;
637
+ onDownload();
638
+ onClose();
639
+ }}
640
+ >
322
641
  <span className="flex items-center gap-2">
323
642
  <Download size={14} />
324
643
  {entry.type === 'directory' ? 'Download as zip' : 'Download'}
325
644
  </span>
326
645
  </MenuItem>
327
646
  )}
328
- <MenuItem role="menuitem" onClick={handleCopyPath}>
329
- <span className="flex items-center gap-2"><Link2 size={14} />Copy path</span>
330
- </MenuItem>
647
+ {/* The workspace root has no path worth linking: it would copy `/.`. */}
331
648
  {!isRoot && (
649
+ <MenuItem role="menuitem" onClick={handleCopyPath}>
650
+ <span className="flex items-center gap-2"><Link2 size={14} />Copy path</span>
651
+ </MenuItem>
652
+ )}
653
+ {offersManageAccess(entry) && (
332
654
  <>
333
655
  <div className="my-1 border-t border-line" />
334
656
  <MenuItem role="menuitem" onClick={() => { openManageAccess(entry); onClose(); }}>
@@ -345,7 +667,19 @@ function ContextMenu({
345
667
  </MenuItem>
346
668
  )}
347
669
  {!isRoot && onRename && (
348
- <MenuItem role="menuitem" onClick={() => { onRename(); onClose(); }}>
670
+ <MenuItem
671
+ role="menuitem"
672
+ // Same shape as a denied Download: `aria-disabled`, so the reason
673
+ // stays reachable by mouse AND keyboard, with activation refused
674
+ // here rather than by taking the item out of the tab order.
675
+ aria-disabled={renameRefusal ? true : undefined}
676
+ title={renameRefusal ?? undefined}
677
+ onClick={() => {
678
+ if (renameRefusal) return;
679
+ onRename();
680
+ onClose();
681
+ }}
682
+ >
349
683
  <span className="flex items-center gap-2"><Pencil size={14} />Rename</span>
350
684
  </MenuItem>
351
685
  )}
@@ -355,6 +689,14 @@ function ContextMenu({
355
689
  <span className="flex items-center gap-2"><Trash2 size={14} />Delete</span>
356
690
  </MenuItem>
357
691
  )}
692
+ {onWithdraw && (
693
+ // Last, in danger tone, exactly where Delete sits on a row that has
694
+ // one: it is the same shape of act — what the row points at stops
695
+ // existing — and a proposed row never has a Delete to collide with.
696
+ <MenuItem role="menuitem" tone="danger" onClick={() => { onWithdraw(); onClose(); }}>
697
+ <span className="flex items-center gap-2"><Undo2 size={14} />Withdraw suggestion</span>
698
+ </MenuItem>
699
+ )}
358
700
  </MenuPanel>
359
701
  </div>
360
702
  );
@@ -406,6 +748,16 @@ function InlineInput({
406
748
 
407
749
  // ── Rename Input ──
408
750
 
751
+ /**
752
+ * `onSubmit` answers with the refusal to show, or null once the rename
753
+ * landed. A refused rename KEEPS THE BOX OPEN with the sentence under it —
754
+ * the name the user typed is still there to fix, which is the whole point of
755
+ * being told "A file named Notes.md already exists in Sales." The box used to
756
+ * close first and report through `alert()`, which was the only way to avoid
757
+ * the create flow's popup loop (the alert blurs the still-mounted input,
758
+ * whose onBlur re-submits); an inline sentence steals no focus, so the loop
759
+ * cannot start.
760
+ */
409
761
  function RenameInput({
410
762
  currentName,
411
763
  isFile,
@@ -414,17 +766,34 @@ function RenameInput({
414
766
  }: {
415
767
  currentName: string;
416
768
  isFile: boolean;
417
- onSubmit: (value: string) => void;
769
+ onSubmit: (value: string) => Promise<string | null>;
418
770
  onCancel: () => void;
419
771
  }) {
420
772
  const [value, setValue] = useState(currentName);
773
+ // The server's answer to the last name submitted. Cleared on every edit, so
774
+ // a name that has been changed since is submitted again rather than read as
775
+ // still-refused.
776
+ const [refusal, setRefusal] = useState<string | null>(null);
777
+ const [submitting, setSubmitting] = useState(false);
421
778
  const trimmed = value.trim();
422
- const error = trimmed.length === 0 ? null : validateFilename(trimmed);
423
- const valid = trimmed.length > 0 && error === null;
779
+ const nameError = trimmed.length === 0 ? null : validateFilename(trimmed);
780
+ const error = nameError ?? refusal;
781
+ const valid = trimmed.length > 0 && nameError === null;
424
782
 
425
783
  const submit = () => {
426
- if (valid && trimmed !== currentName) onSubmit(trimmed);
427
- else onCancel();
784
+ if (submitting) return;
785
+ if (!valid || trimmed === currentName) { onCancel(); return; }
786
+ setSubmitting(true);
787
+ void onSubmit(trimmed)
788
+ // `onSubmit` answers rather than throws; a rejection anyway must still
789
+ // free the box, or it would be stuck refusing to submit again.
790
+ .catch((err: unknown) => (err instanceof Error ? err.message : String(err)))
791
+ .then((answer) => {
792
+ setSubmitting(false);
793
+ // On success the row unmounts this input; only a refusal has anywhere
794
+ // to land.
795
+ setRefusal(answer);
796
+ });
428
797
  };
429
798
 
430
799
  return (
@@ -435,12 +804,24 @@ function RenameInput({
435
804
  value={value}
436
805
  onClick={(e) => e.stopPropagation()}
437
806
  onMouseDown={(e) => e.stopPropagation()}
438
- onChange={(e) => setValue(e.target.value)}
807
+ // Frozen while the rename is in flight: an edit made in that window
808
+ // would be discarded by the row unmounting on success, and a refusal
809
+ // coming back would land under a name it was never about. `readOnly`
810
+ // rather than `disabled` so the box keeps focus and the caret.
811
+ readOnly={submitting}
812
+ onChange={(e) => {
813
+ if (submitting) return;
814
+ setValue(e.target.value);
815
+ setRefusal(null);
816
+ }}
439
817
  onKeyDown={(e) => {
440
818
  if (e.key === 'Enter') submit();
441
819
  if (e.key === 'Escape') onCancel();
442
820
  }}
443
- onBlur={submit}
821
+ // A name the server has already refused is not sent again on the way
822
+ // out: clicking away from a refusal closes the box, it does not retry
823
+ // a rename that cannot land.
824
+ onBlur={() => { if (refusal !== null) onCancel(); else submit(); }}
444
825
  onFocus={(e) => {
445
826
  if (isFile) {
446
827
  // Select name without extension for files
@@ -454,14 +835,64 @@ function RenameInput({
454
835
  title={error ?? undefined}
455
836
  aria-invalid={error ? true : undefined}
456
837
  />
457
- {error && <div className="mt-0.5 px-1 text-meta text-danger">{error}</div>}
838
+ {error && (
839
+ <div role="alert" data-testid="rename-error" className="mt-0.5 px-1 text-meta text-danger">
840
+ {error}
841
+ </div>
842
+ )}
458
843
  </div>
459
844
  );
460
845
  }
461
846
 
847
+ // ── Row Notice ──
848
+
849
+ /**
850
+ * One row's own bad news — a refused download, a refused drop — drawn under
851
+ * the row at the row's indent, with a Dismiss. Never an `alert()`: a modal
852
+ * popup stops the whole app to say something the tree can say in place, and
853
+ * (the create flow learned this the hard way) it steals focus from whatever
854
+ * input is still mounted.
855
+ */
856
+ function RowNotice({
857
+ message,
858
+ testId,
859
+ dismissLabel,
860
+ paddingLeft,
861
+ onDismiss,
862
+ }: {
863
+ message: string;
864
+ testId: string;
865
+ dismissLabel: string;
866
+ paddingLeft: number;
867
+ onDismiss: () => void;
868
+ }) {
869
+ return (
870
+ <Banner
871
+ role="alert"
872
+ tone="danger"
873
+ data-testid={testId}
874
+ className="items-center gap-1 rounded-none px-2 py-1 text-xs"
875
+ style={{ paddingLeft }}
876
+ >
877
+ <span className="flex items-start gap-1">
878
+ <span className="flex-1">{message}</span>
879
+ <IconButton size={18} tone="danger" title="Dismiss" aria-label={dismissLabel} onClick={onDismiss}>
880
+ <X size={12} />
881
+ </IconButton>
882
+ </span>
883
+ </Banner>
884
+ );
885
+ }
886
+
462
887
  // ── Tree Node ──
463
888
 
464
889
  const DRAG_MIME = 'application/x-workspace-path';
890
+ /**
891
+ * What kind of row is being dragged — `directory` or `file`. The path alone
892
+ * does not say (a folder may be named like a file), and the move dialog asks
893
+ * a file-only access question, so the kind travels with the path.
894
+ */
895
+ const DRAG_KIND_MIME = 'application/x-workspace-kind';
465
896
 
466
897
  export function FileTreeNode({
467
898
  entry,
@@ -469,6 +900,8 @@ export function FileTreeNode({
469
900
  initiallyExpanded,
470
901
  collapseChildren,
471
902
  reserved = false,
903
+ absent = false,
904
+ root,
472
905
  }: {
473
906
  entry: FileTreeEntry;
474
907
  depth: number;
@@ -487,37 +920,107 @@ export function FileTreeNode({
487
920
  * not do: be renamed, deleted, dragged, or pinned.
488
921
  */
489
922
  reserved?: boolean;
923
+ /**
924
+ * The folder is not on disk yet — a reserved root drawn before the
925
+ * knowledge base has it, so the way to create it is on screen. Everything
926
+ * that WRITES works (each write creates its parents); what READS the folder
927
+ * is withheld: no Download, which would ask the server for a zip of nothing.
928
+ */
929
+ absent?: boolean;
930
+ /**
931
+ * This row IS the tree — the folder everything below it hangs off. It gets
932
+ * the root's affordances (the Add files / Add folder pickers) and none of
933
+ * the ones that would move the tree out from under itself (drag, rename,
934
+ * delete, Copy path). Defaults to the `.` workspace-root node, which is
935
+ * what a tree rooted at the literal root hands down; the Knowledge
936
+ * explorer sets it on the CHECKOUT folder, which is its root even though
937
+ * the workspace directory above it is not.
938
+ */
939
+ root?: boolean;
490
940
  }) {
491
- const { createFile, createDirectory, dispatchUpload, isUploading, moveEntry, workspaceId, pendingUploads } = useWorkspace();
941
+ const { createFile, createDirectory, dispatchUpload, isUploading, moveEntry, workspaceId, kbDirName, pendingUploads } = useWorkspace();
492
942
  const nav = useTreeNav();
943
+ /**
944
+ * Why this row cannot be renamed, or null when it can. A platform file is
945
+ * refused here with the sentence the server refuses with — the tree says it
946
+ * without a round trip, and says the same thing.
947
+ */
948
+ const platformRefusal = platformFileMoveRefusal(entry.relativePath, kbDirName);
949
+ /**
950
+ * Why it cannot be DRAGGED — the same, minus an admin's one repair (see
951
+ * `platformFileDragRefusal`). Read through the context rather than
952
+ * `useAdmin()` so a tree rendered without an `AdminProvider` — a host app's,
953
+ * a test's — still draws: no provider is simply nobody's admin, which is the
954
+ * refusal this row had before the exception existed.
955
+ */
956
+ const isAdmin = useContext(AdminContext)?.isAdmin ?? false;
957
+ const dragRefusal = platformFileDragRefusal(entry.relativePath, kbDirName, isAdmin);
958
+ const confirm = useTreeConfirm();
959
+ // Which tree this row belongs to, so an upload's banners land here and not
960
+ // in the other tree on the same page.
961
+ const uploadTarget = useUploadTarget();
493
962
  // One shared fetch behind this — see `OpenChangeRequestsProvider`.
494
963
  const openChangeRequests = useOpenChangeRequests();
495
964
  const suggestions = useSuggestions();
496
965
 
966
+ /**
967
+ * A refused download, said in place under the row. Never an `alert()`: the
968
+ * menu's preflight already turns the KNOWN refusal into a disabled item, so
969
+ * what reaches here is the rare late one — permission changed while the
970
+ * menu was open — and a modal popup for it stops the whole app to report
971
+ * something the row itself can say.
972
+ */
973
+ const [downloadError, setDownloadError] = useState<string | null>(null);
974
+ /**
975
+ * A refused drop, said in place under the row it was dropped on — the same
976
+ * treatment a refused download gets, and for the same reason. It used to be
977
+ * an `alert()`, which stops the app to report something the tree can say;
978
+ * the sentence the server sends ("A file named Notes.md already exists in
979
+ * Sales.") is the whole message, so it is shown verbatim.
980
+ */
981
+ const [moveError, setMoveError] = useState<string | null>(null);
982
+ /**
983
+ * Which download the notice is allowed to speak for. The menu closes on
984
+ * click but the ROW does not, so a second Download can be started (reopen,
985
+ * click again) while the first is still in flight — and the two can land
986
+ * out of order. Only the latest may write `downloadError`: without this, a
987
+ * slow refusal arriving after a fast success reports a failed download the
988
+ * user just watched succeed.
989
+ */
990
+ const downloadSeq = useRef(0);
991
+
497
992
  const handleDownload = useCallback(async () => {
498
993
  if (!workspaceId) return;
499
994
  // Files hit /file/raw; folders hit /folder/zip and arrive as <name>.zip.
500
995
  // Both endpoints share the same per-path `download:` access gate, the
501
996
  // same `?download=1` flag shape, and the same Content-Disposition
502
997
  // handling on the backend — branching here just picks the URL.
503
- // No preflight: a 403 surfaces in the alert below.
998
+ // The menu preflights the gate's verdict (`useDownloadVerdict`); a 403
999
+ // still reaching here is a permission that changed since it opened.
504
1000
  const isFolder = entry.type === 'directory';
505
1001
  const url = isFolder
506
1002
  ? `/api/workspace/${workspaceId}/folder/zip?path=${encodeURIComponent(entry.relativePath)}&download=1`
507
- : `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(entry.relativePath)}&download=1`;
1003
+ : rawFileUrl(workspaceId, entry.relativePath, { download: true });
508
1004
  const savedAs = isFolder ? `${entry.name}.zip` : entry.name;
1005
+ const seq = ++downloadSeq.current;
1006
+ setDownloadError(null);
509
1007
  try {
510
1008
  const outcome = await downloadViaBlob(url, savedAs);
1009
+ // Superseded: a later download for this row has already spoken.
1010
+ if (seq !== downloadSeq.current) return;
511
1011
  if (!outcome.ok) {
512
- alert(
513
- `Failed to download ${entry.name} (HTTP ${outcome.status})${outcome.body ? `: ${outcome.body}` : ''}`,
1012
+ setDownloadError(
1013
+ outcome.status === 403
1014
+ ? `Couldn't download ${entry.name}. ${DOWNLOAD_DENIED_MESSAGE}.`
1015
+ : `Couldn't download ${entry.name} (HTTP ${outcome.status})${outcome.body ? `: ${outcome.body}` : ''}`,
514
1016
  );
515
1017
  return;
516
1018
  }
517
1019
  } catch (err) {
518
1020
  console.error('Failed to download:', err);
1021
+ if (seq !== downloadSeq.current) return;
519
1022
  const msg = err instanceof Error ? err.message : String(err);
520
- alert(`Failed to download ${entry.name}:\n${msg}`);
1023
+ setDownloadError(`Couldn't download ${entry.name}: ${msg}`);
521
1024
  }
522
1025
  }, [workspaceId, entry.relativePath, entry.name, entry.type]);
523
1026
  // `null` = no explicit user intent; fall through to the auto-expand / depth
@@ -542,14 +1045,30 @@ export function FileTreeNode({
542
1045
  rootFolderInputRef.current?.click();
543
1046
  }, []);
544
1047
 
1048
+ /**
1049
+ * Every upload into this row goes through here. Nothing is asked first: an
1050
+ * upload into a folder the caller cannot read is refused by the server's
1051
+ * read-before-write gate, and the refusal shows in this tree's banner.
1052
+ */
1053
+ const uploadAfterGate = useCallback(
1054
+ (input: UploadInput, targetDir: string) => {
1055
+ void dispatchUpload(input, targetDir, uploadTarget);
1056
+ },
1057
+ [dispatchUpload, uploadTarget],
1058
+ );
1059
+
1060
+ // Where this row's own writes go. Keyed to the PATH, not to `isRoot`: the
1061
+ // checkout folder is a root row with a real path of its own, and a write
1062
+ // into it is addressed like any other folder's. Only the literal `.`
1063
+ // workspace root has no path to give, and `''` is how the server hears it.
1064
+ const pickTarget = entry.relativePath === '.' ? '' : entry.relativePath;
545
1065
  // Resetting `value` after dispatch lets users re-select the same file and
546
1066
  // still get an `onChange` event the second time around.
547
- const pickTarget = entry.relativePath === '.' ? '' : entry.relativePath;
548
1067
  const handleRootFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
549
1068
  const files = Array.from(e.target.files ?? []);
550
1069
  e.target.value = '';
551
- if (files.length > 0) dispatchUpload({ kind: 'files', files }, pickTarget);
552
- }, [dispatchUpload, pickTarget]);
1070
+ if (files.length > 0) uploadAfterGate({ kind: 'files', files }, pickTarget);
1071
+ }, [uploadAfterGate, pickTarget]);
553
1072
 
554
1073
  // Folder picker: each File carries a `webkitRelativePath` like
555
1074
  // "foldername/sub/file.txt" — we feed those straight into the upload
@@ -565,17 +1084,17 @@ export function FileTreeNode({
565
1084
  file,
566
1085
  relativePath: file.webkitRelativePath || file.name,
567
1086
  }));
568
- dispatchUpload({ kind: 'paths', items }, pickTarget);
569
- }, [dispatchUpload, pickTarget]);
1087
+ uploadAfterGate({ kind: 'paths', items }, pickTarget);
1088
+ }, [uploadAfterGate, pickTarget]);
570
1089
  const [dragging, setDragging] = useState(false);
571
1090
  const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
572
1091
 
573
1092
  const paddingLeft = indentFor(depth);
574
- const isRoot = entry.relativePath === '.';
1093
+ const isRoot = root ?? entry.relativePath === '.';
575
1094
  const isPending = pendingUploads.has(entry.relativePath);
576
- // A folder with nothing in it doesn't get a caret, because there is nothing
577
- // to open (proto:3565).
578
- const hasChildren = (entry.children?.length ?? 0) > 0;
1095
+ // A folder with nothing in it still gets its caret — without one it reads
1096
+ // as a file — and opening it says so with a muted "Empty" row.
1097
+ const isEmpty = (entry.children?.length ?? 0) === 0;
579
1098
  // Escape inside the context menu hands focus back to the row it came from.
580
1099
  const rowRef = useRef<HTMLButtonElement>(null);
581
1100
 
@@ -608,13 +1127,57 @@ export function FileTreeNode({
608
1127
  setContextMenu({ x: e.clientX, y: e.clientY });
609
1128
  }, []);
610
1129
 
1130
+ // Rendered directly under the row it belongs to, at the row's own indent,
1131
+ // so the failure is attached to the file it is about — the sidebar shows
1132
+ // many rows and a banner at the top would name one of them in prose.
1133
+ const downloadNotice = downloadError && (
1134
+ <RowNotice
1135
+ message={downloadError}
1136
+ testId="tree-download-error"
1137
+ dismissLabel="Dismiss download error"
1138
+ paddingLeft={paddingLeft}
1139
+ onDismiss={() => setDownloadError(null)}
1140
+ />
1141
+ );
1142
+ const moveNotice = moveError && (
1143
+ <RowNotice
1144
+ message={moveError}
1145
+ testId="tree-move-error"
1146
+ dismissLabel="Dismiss move error"
1147
+ paddingLeft={paddingLeft}
1148
+ onDismiss={() => setMoveError(null)}
1149
+ />
1150
+ );
1151
+
1152
+ /**
1153
+ * The rename box's submit: move this entry to `newName` beside itself.
1154
+ * Answers with the sentence to show IN the box — "A file named Notes.md
1155
+ * already exists in Sales." — or null once the rename landed, which is the
1156
+ * only case that closes the box. A refused rename leaves the name the user
1157
+ * typed on screen to fix; it is never reported through `alert()`, which
1158
+ * would say it somewhere the user has to dismiss and, by stealing focus
1159
+ * from the still-mounted input, re-submit the same doomed rename.
1160
+ */
1161
+ const renameTo = useCallback(async (newName: string): Promise<string | null> => {
1162
+ const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
1163
+ const newPath = parentDir ? `${parentDir}/${newName}` : newName;
1164
+ try {
1165
+ await moveEntry(entry.relativePath, newPath);
1166
+ } catch (err) {
1167
+ return err instanceof Error ? err.message : String(err);
1168
+ }
1169
+ setRenaming(false);
1170
+ return null;
1171
+ }, [entry.relativePath, moveEntry]);
1172
+
611
1173
  // ── Drag source (internal reorder) ──
612
1174
  const handleDragStart = useCallback((e: React.DragEvent) => {
613
- if (isRoot || reserved) { e.preventDefault(); return; }
1175
+ if (isRoot || reserved || dragRefusal) { e.preventDefault(); return; }
614
1176
  e.dataTransfer.setData(DRAG_MIME, entry.relativePath);
1177
+ e.dataTransfer.setData(DRAG_KIND_MIME, entry.type);
615
1178
  e.dataTransfer.effectAllowed = 'move';
616
1179
  setDragging(true);
617
- }, [entry.relativePath, isRoot, reserved]);
1180
+ }, [entry.relativePath, entry.type, isRoot, reserved, dragRefusal]);
618
1181
 
619
1182
  const handleDragEnd = useCallback(() => {
620
1183
  setDragging(false);
@@ -630,9 +1193,23 @@ export function FileTreeNode({
630
1193
  // Internal move (reorder)
631
1194
  const sourcePath = e.dataTransfer.getData(DRAG_MIME);
632
1195
  if (sourcePath) {
633
- const targetDir = entry.type === 'directory'
1196
+ const droppedOn = entry.type === 'directory'
634
1197
  ? (isRoot ? '' : entry.relativePath)
635
1198
  : '';
1199
+ // "The top level" is the top of the tree the dragged row lives in —
1200
+ // the KB clone's own root — not the workspace folder the clone sits
1201
+ // in. In the split layout the explorer draws the clone's roots
1202
+ // (Knowledge, Data, …) and its loose files but no row for the clone
1203
+ // itself, so a drop that resolves to no folder is how the clone's
1204
+ // root is reached at all: it is where an admin drops a misplaced
1205
+ // `roles.yaml` to put it back. Left bare, that move would send the
1206
+ // file to `roles.yaml` BESIDE the clone — out of the repository,
1207
+ // where nothing reads it and git never sees it again.
1208
+ const kbPrefix = kbDirName ? `${kbDirName}/` : null;
1209
+ const targetDir =
1210
+ droppedOn === '' && kbPrefix !== null && sourcePath.startsWith(kbPrefix)
1211
+ ? kbDirName!
1212
+ : droppedOn;
636
1213
  const name = sourcePath.split('/').pop()!;
637
1214
  const newPath = targetDir ? `${targetDir}/${name}` : name;
638
1215
  // Skip no-op or nesting a directory inside itself
@@ -643,7 +1220,42 @@ export function FileTreeNode({
643
1220
  ) {
644
1221
  return;
645
1222
  }
646
- moveEntry(sourcePath, newPath);
1223
+ // The dragged row is a platform file: refused here, with the server's
1224
+ // sentence, and nothing is sent. The row itself is not draggable, so
1225
+ // this catches a drag begun before the tree knew the path's shape
1226
+ // (a drop is the last moment the answer is still cheap).
1227
+ const refusal = platformFileDragRefusal(sourcePath, kbDirName, isAdmin);
1228
+ if (refusal) {
1229
+ alert(refusal);
1230
+ return;
1231
+ }
1232
+ // Every cross-folder move is an access change, so it asks first;
1233
+ // nothing is sent until Confirm.
1234
+ confirm({
1235
+ kind: 'move',
1236
+ sourcePath,
1237
+ sourceIsDirectory: e.dataTransfer.getData(DRAG_KIND_MIME) === 'directory',
1238
+ targetDir,
1239
+ // Named after the row that was dropped on, so a drop that resolved
1240
+ // to the clone's root still reads as "the top level".
1241
+ destinationLabel: droppedOn ? entry.name : 'the top level',
1242
+ returnFocusTo: () => rowForPath(sourcePath),
1243
+ // The row it was dropped on stays put; the source row moves away.
1244
+ focusAfterRun: () => rowForPath(entry.relativePath),
1245
+ run: async () => {
1246
+ try {
1247
+ setMoveError(null);
1248
+ await moveEntry(sourcePath, newPath);
1249
+ } catch (err) {
1250
+ // Same surfacing as rename — a refused move (a name already
1251
+ // taken here, a folder the caller may not write) must not read
1252
+ // as one that silently reverted. Both entries stay where they
1253
+ // are: the server moved nothing.
1254
+ const msg = err instanceof Error ? err.message : String(err);
1255
+ setMoveError(msg);
1256
+ }
1257
+ },
1258
+ });
647
1259
  return;
648
1260
  }
649
1261
 
@@ -654,15 +1266,15 @@ export function FileTreeNode({
654
1266
  const targetDir = dir === '.' ? '' : dir;
655
1267
  const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
656
1268
  if (entries.length > 0) {
657
- dispatchUpload({ kind: 'items', entries }, targetDir);
1269
+ uploadAfterGate({ kind: 'items', entries }, targetDir);
658
1270
  return;
659
1271
  }
660
1272
  // Fallback for older browsers / non-entry drops: use the flat FileList.
661
1273
  const files = Array.from(e.dataTransfer.files);
662
1274
  if (files.length === 0) return;
663
- dispatchUpload({ kind: 'files', files }, targetDir);
1275
+ uploadAfterGate({ kind: 'files', files }, targetDir);
664
1276
  },
665
- [entry, isRoot, dispatchUpload, moveEntry],
1277
+ [entry, isRoot, uploadAfterGate, moveEntry, confirm, kbDirName, isAdmin],
666
1278
  );
667
1279
 
668
1280
  const handleDragOver = useCallback((e: React.DragEvent) => {
@@ -681,7 +1293,7 @@ export function FileTreeNode({
681
1293
  }, []);
682
1294
 
683
1295
  if (entry.type === 'directory') {
684
- const dirPath = isRoot ? '' : entry.relativePath;
1296
+ const dirPath = pickTarget;
685
1297
  const createButtons = (
686
1298
  <>
687
1299
  <IconButton
@@ -761,7 +1373,7 @@ export function FileTreeNode({
761
1373
  dragOver && 'bg-hover text-ink ring-1 ring-accent/40',
762
1374
  )}
763
1375
  style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
764
- draggable={!isRoot && !reserved && !renaming && !isPending}
1376
+ draggable={!isRoot && !reserved && !renaming && !isPending && !dragRefusal}
765
1377
  onDragStart={handleDragStart}
766
1378
  onDragEnd={handleDragEnd}
767
1379
  onDrop={handleDrop}
@@ -772,31 +1384,17 @@ export function FileTreeNode({
772
1384
  <button
773
1385
  ref={rowRef}
774
1386
  type="button"
1387
+ data-tree-path={entry.relativePath}
775
1388
  aria-expanded={isExpanded}
776
1389
  className="flex min-w-0 flex-1 items-center gap-1.5 text-left"
777
- onClick={() => { if (hasChildren) setUserIntent(!isExpanded); }}
1390
+ onClick={() => setUserIntent(!isExpanded)}
778
1391
  >
779
- <CaretSlot open={isExpanded} show={hasChildren} />
1392
+ <CaretSlot open={isExpanded} show />
780
1393
  {renaming ? (
781
1394
  <RenameInput
782
1395
  currentName={entry.name}
783
1396
  isFile={false}
784
- onSubmit={async (newName) => {
785
- const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
786
- const newPath = parentDir ? `${parentDir}/${newName}` : newName;
787
- // Close the input BEFORE the fallible move — see the create
788
- // flow: on error the alert() blurs the still-mounted input,
789
- // whose onBlur re-fires this onSubmit, looping the popup.
790
- setRenaming(false);
791
- try {
792
- await moveEntry(entry.relativePath, newPath);
793
- } catch (err) {
794
- // Same surfacing as the create flow above — a silent failure
795
- // reads as the rename being accepted and then reverting.
796
- const msg = err instanceof Error ? err.message : String(err);
797
- alert(`Failed to rename ${entry.name}:\n${msg}`);
798
- }
799
- }}
1397
+ onSubmit={renameTo}
800
1398
  onCancel={() => setRenaming(false)}
801
1399
  />
802
1400
  ) : (
@@ -808,6 +1406,8 @@ export function FileTreeNode({
808
1406
  </div>
809
1407
  {isRoot && pickerButtons}
810
1408
  </div>
1409
+ {downloadNotice}
1410
+ {moveNotice}
811
1411
  {isExpanded && (
812
1412
  <div>
813
1413
  {creating && (
@@ -831,10 +1431,11 @@ export function FileTreeNode({
831
1431
  if (kind === 'file') await createFile(fullPath);
832
1432
  else await createDirectory(fullPath);
833
1433
  } catch (err) {
834
- // Surface the refusal (e.g. a protected branch's write
835
- // gate: "You don't have permission to write to …") —
836
- // otherwise the input clears and nothing appears, which
837
- // reads as the file silently vanishing.
1434
+ // Surface the refusal (a protected branch's write gate,
1435
+ // or the read-before-write gate: "You don't have
1436
+ // permission to write to …") — otherwise the input
1437
+ // clears and nothing appears, which reads as the file
1438
+ // silently vanishing.
838
1439
  const msg = err instanceof Error ? err.message : String(err);
839
1440
  alert(`Failed to create ${name}:\n${msg}`);
840
1441
  }
@@ -843,6 +1444,19 @@ export function FileTreeNode({
843
1444
  />
844
1445
  </div>
845
1446
  )}
1447
+ {isEmpty && !creating && (
1448
+ // Not a row anyone acts on — no path, no focus, no menu — so
1449
+ // keyboard navigation and the context menu never meet it. It
1450
+ // sits where a first child would, name column included.
1451
+ <div
1452
+ data-tree-empty
1453
+ className={cn(ROW_CLASS, 'text-ink-faint')}
1454
+ style={{ paddingLeft: indentFor(depth + 1) }}
1455
+ >
1456
+ <CaretSlot show={false} />
1457
+ <span className="truncate">Empty</span>
1458
+ </div>
1459
+ )}
846
1460
  {entry.children?.map((child) => (
847
1461
  <FileTreeNode
848
1462
  key={child.relativePath}
@@ -866,8 +1480,14 @@ export function FileTreeNode({
866
1480
  // either, but that needs no gate: only the Knowledge explorer
867
1481
  // offers pinning, and its roots are not reserved.)
868
1482
  onRename={reserved ? undefined : () => setRenaming(true)}
1483
+ // A folder NAMED like a platform file (`access.md/`) meets the same
1484
+ // rule: the server reads the path, not the kind, and refuses to
1485
+ // move it. Without this the row refused the drag and offered the
1486
+ // rename, which opened an editor only to fail on the round trip.
1487
+ renameRefusal={platformRefusal}
869
1488
  deletable={!reserved}
870
- onDownload={handleDownload}
1489
+ onDownload={absent ? undefined : handleDownload}
1490
+ extraItems={nav.menuItems?.(entry)}
871
1491
  returnFocusTo={rowRef}
872
1492
  />
873
1493
  )}
@@ -878,30 +1498,88 @@ export function FileTreeNode({
878
1498
  // A file from the caller's own open change request that does not exist on
879
1499
  // this branch. Its row is a LINK to the request, not a file: there is no
880
1500
  // content here to show, so clicking opens the change-request view, and none
881
- // of the file affordances (rename, drag, download, context menu) apply —
882
- // they would all 404 against a path this branch has never heard of. The
883
- // accent colour is the tell that this is proposed, not present.
1501
+ // of the file affordances (rename, drag, download) apply — they would all
1502
+ // 404 against a path this branch has never heard of. The context menu keeps
1503
+ // only what makes sense for a proposal: the path, and Manage access, which
1504
+ // the chrome points at the change request's branch. The accent colour is
1505
+ // the tell that this is proposed, not present.
884
1506
  const suggestedCr = suggestions.crFor(entry.relativePath);
885
1507
  if (suggestedCr !== null) {
1508
+ // The one thing the author can DO to a proposal from here: take it back.
1509
+ // The reporter of this had uploaded a file into a folder they cannot
1510
+ // write, watched it turn into an accent-coloured row, and concluded there
1511
+ // was no way to undo it — the Withdraw that already existed was on the
1512
+ // file page and in the dialog, neither of which the row leads to.
1513
+ //
1514
+ // `undefined` for anyone else's request, which is what keeps the item off
1515
+ // the menu entirely; an owner's "no" is Decline, and it stays in the dialog.
1516
+ const withdraw = suggestions.mine(suggestedCr)
1517
+ ? () => {
1518
+ // The request may not be in the shared list yet (the broad fetch
1519
+ // trails a just-made suggestion). Naming the row's own file is then
1520
+ // both true and the least surprising thing to say.
1521
+ const carried = suggestions.filesOf(entry.relativePath, suggestedCr);
1522
+ confirm({
1523
+ kind: 'withdraw',
1524
+ crNumber: suggestedCr,
1525
+ files: carried.length > 0 ? carried : [entry.relativePath],
1526
+ returnFocusTo: () => rowRef.current,
1527
+ // The row leaves the tree with the request it stood for, so focus
1528
+ // goes to the folder that held it — as a delete's does.
1529
+ focusAfterRun: () => rowForPath(entry.relativePath.split('/').slice(0, -1).join('/')),
1530
+ run: async () => {
1531
+ try {
1532
+ await suggestions.withdraw(suggestedCr);
1533
+ } catch (err) {
1534
+ // Already applied, or declined meanwhile: the same surfacing
1535
+ // every other refused tree operation gets. The rows refresh
1536
+ // either way (see the controller), so what the user sees next
1537
+ // is the truth from the server rather than a stale row.
1538
+ console.error('Failed to withdraw suggestion:', err);
1539
+ const msg = err instanceof Error ? err.message : String(err);
1540
+ alert(`Couldn't withdraw ${entry.name}:\n${msg}`);
1541
+ }
1542
+ },
1543
+ });
1544
+ }
1545
+ : undefined;
886
1546
  return (
887
- <button
888
- type="button"
889
- className={cn(
890
- ROW_CLASS,
891
- 'text-accent hover:bg-hover hover:text-accent-hover',
892
- 'focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-ink-muted',
1547
+ <>
1548
+ <button
1549
+ ref={rowRef}
1550
+ type="button"
1551
+ data-tree-path={entry.relativePath}
1552
+ className={cn(
1553
+ ROW_CLASS,
1554
+ 'text-accent hover:bg-hover hover:text-accent-hover',
1555
+ 'focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-ink-muted',
1556
+ )}
1557
+ style={{ paddingLeft }}
1558
+ onClick={() => suggestions.open(entry.relativePath, suggestedCr)}
1559
+ onContextMenu={handleContextMenu}
1560
+ title="Proposed by you: opens the change request"
1561
+ >
1562
+ <CaretSlot show={false} />
1563
+ <FileName name={entry.name} />
1564
+ <span
1565
+ aria-hidden
1566
+ className="ml-auto h-1.5 w-1.5 flex-none rounded-full bg-accent"
1567
+ />
1568
+ </button>
1569
+ {contextMenu && (
1570
+ <ContextMenu
1571
+ x={contextMenu.x}
1572
+ y={contextMenu.y}
1573
+ entry={entry}
1574
+ isRoot={false}
1575
+ proposed
1576
+ deletable={false}
1577
+ onWithdraw={withdraw}
1578
+ onClose={() => setContextMenu(null)}
1579
+ returnFocusTo={rowRef}
1580
+ />
893
1581
  )}
894
- style={{ paddingLeft }}
895
- onClick={() => suggestions.open(entry.relativePath, suggestedCr)}
896
- title="Proposed by you: opens the change request"
897
- >
898
- <CaretSlot show={false} />
899
- <span className="truncate">{entry.name}</span>
900
- <span
901
- aria-hidden
902
- className="ml-auto h-1.5 w-1.5 flex-none rounded-full bg-accent"
903
- />
904
- </button>
1582
+ </>
905
1583
  );
906
1584
  }
907
1585
 
@@ -912,6 +1590,7 @@ export function FileTreeNode({
912
1590
  <button
913
1591
  ref={rowRef}
914
1592
  type="button"
1593
+ data-tree-path={entry.relativePath}
915
1594
  aria-current={isActive}
916
1595
  className={cn(
917
1596
  ROW_CLASS,
@@ -920,7 +1599,7 @@ export function FileTreeNode({
920
1599
  isPending && 'cursor-progress',
921
1600
  )}
922
1601
  style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
923
- draggable={!renaming && !isPending}
1602
+ draggable={!renaming && !isPending && !dragRefusal}
924
1603
  onDragStart={handleDragStart}
925
1604
  onDragEnd={handleDragEnd}
926
1605
  onClick={() => { if (!renaming && !isPending) nav.open(entry.relativePath); }}
@@ -941,26 +1620,11 @@ export function FileTreeNode({
941
1620
  <RenameInput
942
1621
  currentName={entry.name}
943
1622
  isFile={true}
944
- onSubmit={async (newName) => {
945
- const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
946
- const newPath = parentDir ? `${parentDir}/${newName}` : newName;
947
- // Close the input BEFORE the fallible move — see the create
948
- // flow: on error the alert() blurs the still-mounted input,
949
- // whose onBlur re-fires this onSubmit, looping the popup.
950
- setRenaming(false);
951
- try {
952
- await moveEntry(entry.relativePath, newPath);
953
- } catch (err) {
954
- // Same surfacing as the create flow — a silent failure reads
955
- // as the rename being accepted and then reverting.
956
- const msg = err instanceof Error ? err.message : String(err);
957
- alert(`Failed to rename ${entry.name}:\n${msg}`);
958
- }
959
- }}
1623
+ onSubmit={renameTo}
960
1624
  onCancel={() => setRenaming(false)}
961
1625
  />
962
1626
  ) : (
963
- <span className="truncate">{entry.name}</span>
1627
+ <FileName name={entry.name} />
964
1628
  )}
965
1629
  {/* News about a file you are not looking at (proto:692). Amber, not
966
1630
  the tab dot's accent: on a tab the dot marks the file you have
@@ -972,6 +1636,8 @@ export function FileTreeNode({
972
1636
  />
973
1637
  )}
974
1638
  </button>
1639
+ {downloadNotice}
1640
+ {moveNotice}
975
1641
  {contextMenu && (
976
1642
  <ContextMenu
977
1643
  x={contextMenu.x}
@@ -980,7 +1646,9 @@ export function FileTreeNode({
980
1646
  isRoot={false}
981
1647
  onClose={() => setContextMenu(null)}
982
1648
  onRename={() => setRenaming(true)}
1649
+ renameRefusal={platformRefusal}
983
1650
  onDownload={handleDownload}
1651
+ extraItems={nav.menuItems?.(entry)}
984
1652
  returnFocusTo={rowRef}
985
1653
  />
986
1654
  )}
@@ -1003,141 +1671,546 @@ export function TreeChrome({
1003
1671
  nav,
1004
1672
  suggestionOnlyPaths,
1005
1673
  pinned,
1674
+ uploadTarget = KNOWLEDGE_UPLOAD_TARGET,
1006
1675
  children,
1007
1676
  }: {
1008
1677
  nav: TreeNav;
1009
1678
  suggestionOnlyPaths: ReadonlyMap<string, number>;
1010
1679
  pinned?: PinnedController;
1680
+ /**
1681
+ * Which tree this is, for the upload banners — see `UploadTarget`. Two
1682
+ * trees on one page (the Library sidebar's `Skills/` and `Plugins/`) must
1683
+ * name themselves differently, or one drop's notice appears in both.
1684
+ */
1685
+ uploadTarget?: UploadTarget;
1011
1686
  children: ReactNode;
1012
1687
  }) {
1013
1688
  const openChangeRequests = useOpenChangeRequests();
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);
1689
+ const { workspaceId, kbDirName } = useWorkspace();
1690
+ // The move dialog's denied-destination warning reads this: the one move a
1691
+ // denied destination still takes is an admin's platform-file restore, and
1692
+ // for anyone else the refusal it predicts is the right prediction. Read
1693
+ // through the context so a tree drawn without an `AdminProvider` still
1694
+ // draws — see `FileTreeNode`.
1695
+ const isAdmin = useContext(AdminContext)?.isAdmin ?? false;
1696
+ /**
1697
+ * A clicked suggestion row opens the SHARED change-request dialog on the
1698
+ * request the path belongs to, AT that file — the row is a link to the
1699
+ * request's view of one file, and arriving at some other file (the
1700
+ * request's first) is arriving somewhere the user did not click.
1701
+ *
1702
+ * The open dialog lives in the URL (`?cr=12&file=Sales/brief.pdf`), not in
1703
+ * component state, so a reload — or a link pasted to a colleague — lands
1704
+ * back on the same file of the same request instead of on the bare tree.
1705
+ * Everything below DERIVES from the query: there is one source of truth for
1706
+ * what is open, and no effect to keep it in step with.
1707
+ */
1708
+ const [searchParams, setSearchParams] = useSearchParams();
1709
+ const openSuggestion = useMemo(() => {
1710
+ const number = Number(searchParams.get(CR_PARAM));
1711
+ const path = searchParams.get(CR_FILE_PARAM);
1712
+ if (!Number.isInteger(number) || number <= 0 || !path) return null;
1713
+ const cr = openChangeRequests.forPath(path).find((c) => c.number === number) ?? null;
1714
+ // Not (yet) a request this viewer has: the list may still be loading, so
1715
+ // nothing opens and the query stands — the dialog appears when it lands.
1716
+ if (!cr) return null;
1717
+ // The query is in the TREE's path space; the change request's files are
1718
+ // repo-relative. One conversion, here, at the hand-over.
1719
+ const prefix = kbDirName ? `${kbDirName}/` : null;
1720
+ return { cr, path, file: prefix && path.startsWith(prefix) ? path.slice(prefix.length) : path };
1721
+ }, [searchParams, kbDirName, openChangeRequests]);
1722
+ const setOpenSuggestion = useCallback(
1723
+ (open: { number: number; path: string } | null) => {
1724
+ setSearchParams(
1725
+ (prev) => {
1726
+ const next = new URLSearchParams(prev);
1727
+ if (open) {
1728
+ next.set(CR_PARAM, String(open.number));
1729
+ next.set(CR_FILE_PARAM, open.path);
1730
+ } else {
1731
+ next.delete(CR_PARAM);
1732
+ next.delete(CR_FILE_PARAM);
1733
+ }
1734
+ return next;
1735
+ },
1736
+ // Opening a request is a place you can come back from; closing it
1737
+ // again should not leave two entries to press Back through.
1738
+ { replace: !open },
1739
+ );
1740
+ },
1741
+ [setSearchParams],
1742
+ );
1018
1743
  const suggestionsController = useMemo<SuggestionsController>(
1019
1744
  () => ({
1020
1745
  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);
1746
+ open: (path, crNumber) => setOpenSuggestion({ number: crNumber, path }),
1747
+ mine: (crNumber) => openChangeRequests.mineNumbers.has(crNumber),
1748
+ filesOf: (path, crNumber) =>
1749
+ openChangeRequests.forPath(path).find((c) => c.number === crNumber)?.touchedNodePaths ?? [],
1750
+ withdraw: async (crNumber) => {
1751
+ try {
1752
+ await cancelPullRequest(crNumber);
1753
+ } finally {
1754
+ // On BOTH paths. A cancel that succeeded has removed the request,
1755
+ // and one that was refused (applied or declined meanwhile) means
1756
+ // the row was already describing something that is no longer open —
1757
+ // either way the next thing on screen should come from the server.
1758
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
1759
+ }
1024
1760
  },
1025
1761
  }),
1026
- [suggestionOnlyPaths, openChangeRequests],
1762
+ [suggestionOnlyPaths, setOpenSuggestion, openChangeRequests],
1027
1763
  );
1028
1764
  // Right-click → Manage access opens this sheet for the chosen entry.
1029
1765
  const [accessTarget, setAccessTarget] = useState<FileTreeEntry | null>(null);
1766
+ // `Manage <folder> →` from a proposed file's sheet keeps that file's change
1767
+ // request: the inherited grant it retargets from was read on the request's
1768
+ // branch, so the folder's rules are edited there too — not on the viewed
1769
+ // branch, which the folder path alone would resolve to.
1770
+ const [inheritedProposal, setInheritedProposal] = useState<
1771
+ { number: number; branch: string | null } | undefined
1772
+ >(undefined);
1773
+ const openAccess = useCallback((entry: FileTreeEntry) => {
1774
+ setInheritedProposal(undefined);
1775
+ setAccessTarget(entry);
1776
+ }, []);
1777
+ // A proposed-only file does not exist on the branch being viewed, so its
1778
+ // access can only be edited where it lives: the change request's branch.
1779
+ // Everything else — including a file a request merely modifies, which is a
1780
+ // real row here — keeps the ambient workspace. The branch is null when the
1781
+ // request cannot be resolved; the dialog refuses rather than falling back
1782
+ // to a workspace the file is not on.
1783
+ const accessProposal = useMemo(() => {
1784
+ if (!accessTarget) return undefined;
1785
+ if (inheritedProposal) return inheritedProposal;
1786
+ const crNumber = suggestionOnlyPaths.get(accessTarget.relativePath);
1787
+ if (crNumber === undefined) return undefined;
1788
+ const cr = openChangeRequests
1789
+ .forPath(accessTarget.relativePath)
1790
+ .find((c) => c.number === crNumber);
1791
+ return { number: crNumber, branch: cr?.branch ?? null };
1792
+ }, [accessTarget, inheritedProposal, suggestionOnlyPaths, openChangeRequests]);
1793
+
1794
+ // The one open delete/move confirmation for this tree, stamped with the
1795
+ // workspace it was asked in: its `run` closes over that workspace's
1796
+ // operations, so a switch while it is open drops it rather than letting
1797
+ // Confirm act on a branch the dialog never described.
1798
+ const [openConfirm, setOpenConfirm] = useState<
1799
+ { request: TreeConfirmRequest; workspaceId: string | null } | null
1800
+ >(null);
1801
+ const confirmRequest =
1802
+ openConfirm && openConfirm.workspaceId === workspaceId ? openConfirm.request : null;
1803
+ const askConfirm = useCallback(
1804
+ (request: TreeConfirmRequest) => setOpenConfirm({ request, workspaceId }),
1805
+ [workspaceId],
1806
+ );
1807
+ // Dropped outright, so switching back does not bring it back either.
1808
+ useEffect(() => {
1809
+ setOpenConfirm((open) => (open && open.workspaceId !== workspaceId ? null : open));
1810
+ }, [workspaceId]);
1811
+ // Whether the caller may write the move's destination: null until known.
1812
+ // The same three short-circuits as `useFileAccess` (and the upload's
1813
+ // suggestion routing): drafts and paths outside the KB are writable
1814
+ // without asking, and a failed lookup warns about nothing — the server
1815
+ // is the gate either way, and the dialog never waits on this.
1816
+ // Keyed by the request it answers, so a stale answer never reaches the next one.
1817
+ const [writableAnswer, setWritableAnswer] = useState<
1818
+ { request: TreeConfirmRequest; canWrite: boolean } | null
1819
+ >(null);
1820
+ const destinationWritable =
1821
+ writableAnswer && writableAnswer.request === confirmRequest ? writableAnswer.canWrite : null;
1822
+ const focusAfterConfirm = useRef<(() => HTMLElement | null) | null>(null);
1823
+ useEffect(() => {
1824
+ if (confirmRequest?.kind !== 'move' || !workspaceId || !kbDirName) return;
1825
+ if (!isProtectedBranch(decodeURIComponent(workspaceId))) return;
1826
+ const prefix = `${kbDirName}/`;
1827
+ if (!confirmRequest.targetDir.startsWith(prefix)) return;
1828
+ let cancelled = false;
1829
+ fetchFileAccess(workspaceId, confirmRequest.targetDir.slice(prefix.length), 'folder')
1830
+ .then((res) => { if (!cancelled) setWritableAnswer({ request: confirmRequest, canWrite: res.canWrite }); })
1831
+ .catch(() => {});
1832
+ return () => { cancelled = true; };
1833
+ }, [confirmRequest, workspaceId, kbDirName]);
1834
+ // Who the move costs access and who it gains it for. The dialog opens at
1835
+ // once and fills this in: the answer describes the move, it does not gate
1836
+ // it, and Move is enabled the whole time. Keyed by the request it answers,
1837
+ // so a late answer never decorates the next move.
1838
+ const [accessAnswer, setAccessAnswer] = useState<
1839
+ { request: TreeConfirmRequest; change: MoveAccessChange } | null
1840
+ >(null);
1841
+ const moveRequest = confirmRequest?.kind === 'move' ? confirmRequest : null;
1842
+ // Both ends have to sit inside the KB clone for the access tree to govern
1843
+ // them; outside it there are no rules to compare, and the dialog says
1844
+ // nothing about access it cannot resolve. `kbDirName` alone is the KB root.
1845
+ const insideKb = (path: string) =>
1846
+ !!kbDirName && (path === kbDirName || path.startsWith(`${kbDirName}/`));
1847
+ const accessLookup =
1848
+ moveRequest && workspaceId && kbDirName
1849
+ && !moveRequest.sourceIsDirectory
1850
+ && moveRequest.sourcePath.startsWith(`${kbDirName}/`)
1851
+ && insideKb(moveRequest.targetDir)
1852
+ ? moveRequest
1853
+ : null;
1854
+ const moveAccessChange: MoveAccessChange = !accessLookup
1855
+ ? { status: 'unavailable' }
1856
+ : accessAnswer?.request === accessLookup
1857
+ ? accessAnswer.change
1858
+ : { status: 'loading' };
1859
+ useEffect(() => {
1860
+ if (!accessLookup || !workspaceId || !kbDirName) return;
1861
+ const prefix = `${kbDirName}/`;
1862
+ const controller = new AbortController();
1863
+ // Two seconds is the whole budget; past it the answer is no longer wanted
1864
+ // and the dialog falls back to saying it could not work the change out.
1865
+ const timer = setTimeout(() => controller.abort(), ACCESS_LOOKUP_TIMEOUT_MS);
1866
+ let cancelled = false;
1867
+ fetchProspectiveAccess(
1868
+ workspaceId,
1869
+ accessLookup.sourcePath.slice(prefix.length),
1870
+ accessLookup.targetDir === kbDirName ? '' : accessLookup.targetDir.slice(prefix.length),
1871
+ controller.signal,
1872
+ )
1873
+ .then((access) => {
1874
+ if (cancelled) return;
1875
+ setAccessAnswer({
1876
+ request: accessLookup,
1877
+ change: { status: 'ready', ...accessChangeOf(access) },
1878
+ });
1879
+ })
1880
+ .catch((err) => {
1881
+ if (cancelled) return;
1882
+ // Running out of the two seconds is a designed outcome, not a fault:
1883
+ // the abort is ours, and the dialog already says what it means. Only
1884
+ // a genuine failure is worth a line in the console.
1885
+ if ((err as { name?: string } | null)?.name !== 'AbortError') {
1886
+ console.warn('[FileExplorer] prospective access:', err);
1887
+ }
1888
+ setAccessAnswer({ request: accessLookup, change: { status: 'failed' } });
1889
+ })
1890
+ .finally(() => clearTimeout(timer));
1891
+ return () => {
1892
+ cancelled = true;
1893
+ clearTimeout(timer);
1894
+ controller.abort();
1895
+ };
1896
+ }, [accessLookup, workspaceId, kbDirName]);
1897
+ // A folder delete asks which open change requests propose files in the
1898
+ // folder. It asks for EVERY knowledge-base folder: the shared list may still
1899
+ // be loading, or have failed, and its silence is not "no proposals". A
1900
+ // folder the list shows no proposals under opens the plain dialog at once
1901
+ // (its Delete is "Delete current content only") and switches to the three-way one
1902
+ // if the answer names requests. Keyed by the request it answers.
1903
+ const [proposalsAnswer, setProposalsAnswer] = useState<
1904
+ { request: TreeConfirmRequest; proposals: FolderProposals } | null
1905
+ >(null);
1906
+ const deleteFolder =
1907
+ confirmRequest?.kind === 'delete' && confirmRequest.entry.type === 'directory' && kbDirName
1908
+ && confirmRequest.entry.relativePath.startsWith(`${kbDirName}/`)
1909
+ ? confirmRequest
1910
+ : null;
1911
+ const folderHasProposals =
1912
+ deleteFolder !== null
1913
+ && [...openChangeRequests.paths].some((p) => p.startsWith(`${deleteFolder.entry.relativePath}/`));
1914
+ const answered = proposalsAnswer && proposalsAnswer.request === confirmRequest ? proposalsAnswer.proposals : null;
1915
+ const folderProposals: FolderProposals = folderHasProposals
1916
+ ? (answered ?? { status: 'loading' })
1917
+ // With no proposals in the list, only an answer that names requests
1918
+ // changes the dialog; a failed check has nothing to warn about.
1919
+ : answered?.status === 'ready' && answered.requests.length > 0
1920
+ ? answered
1921
+ : { status: 'none' };
1922
+ useEffect(() => {
1923
+ if (!deleteFolder || !kbDirName) return;
1924
+ let cancelled = false;
1925
+ listChangeRequestsUnderFolder(deleteFolder.entry.relativePath.slice(kbDirName.length + 1))
1926
+ .then((requests) => {
1927
+ if (!cancelled) setProposalsAnswer({ request: deleteFolder, proposals: { status: 'ready', requests } });
1928
+ })
1929
+ .catch((err) => {
1930
+ console.warn('[FileExplorer] change requests under folder:', err);
1931
+ if (!cancelled) setProposalsAnswer({ request: deleteFolder, proposals: { status: 'failed' } });
1932
+ });
1933
+ return () => { cancelled = true; };
1934
+ }, [deleteFolder, kbDirName]);
1935
+ const closeConfirm = (andRun: boolean, mode: DeleteMode = 'folder-only') => {
1936
+ if (!confirmRequest) return;
1937
+ focusAfterConfirm.current = andRun ? confirmRequest.focusAfterRun : confirmRequest.returnFocusTo;
1938
+ setOpenConfirm(null);
1939
+ if (!andRun) return;
1940
+ if (mode === 'with-proposals' && confirmRequest.kind === 'delete' && confirmRequest.runWithProposals) {
1941
+ void confirmRequest.runWithProposals();
1942
+ } else {
1943
+ void confirmRequest.run();
1944
+ }
1945
+ };
1946
+ // Focus goes back to the row once the dialog has unmounted — after the
1947
+ // Dialog's own restore, which would otherwise hand it to the (gone) menu.
1948
+ useEffect(() => {
1949
+ if (confirmRequest || !focusAfterConfirm.current) return;
1950
+ focusAfterConfirm.current()?.focus();
1951
+ focusAfterConfirm.current = null;
1952
+ }, [confirmRequest]);
1030
1953
 
1031
1954
  return (
1032
1955
  <>
1956
+ <TreeConfirmContext.Provider value={askConfirm}>
1033
1957
  <TreeNavContext.Provider value={nav}>
1958
+ <UploadTargetContext.Provider value={uploadTarget}>
1034
1959
  <PinnedContext.Provider value={pinned ?? NO_PINNING}>
1035
- <ManageAccessContext.Provider value={setAccessTarget}>
1960
+ <ManageAccessContext.Provider value={openAccess}>
1036
1961
  <SuggestionsContext.Provider value={suggestionsController}>
1037
1962
  {children}
1038
1963
  </SuggestionsContext.Provider>
1039
1964
  </ManageAccessContext.Provider>
1040
1965
  </PinnedContext.Provider>
1966
+ </UploadTargetContext.Provider>
1041
1967
  </TreeNavContext.Provider>
1042
- {openSuggestionCr && (
1968
+ </TreeConfirmContext.Provider>
1969
+ {confirmRequest && (
1970
+ <TreeActionConfirmDialog
1971
+ request={confirmRequest}
1972
+ warnings={
1973
+ confirmRequest.kind === 'move'
1974
+ ? moveWarnings({ ...confirmRequest, kbDirName, canWrite: destinationWritable, isAdmin })
1975
+ : []
1976
+ }
1977
+ accessChange={moveAccessChange}
1978
+ proposals={folderProposals}
1979
+ onCancel={() => closeConfirm(false)}
1980
+ onConfirm={(mode) => closeConfirm(true, mode)}
1981
+ />
1982
+ )}
1983
+ {openSuggestion && (
1043
1984
  <ChangeRequestDialog
1044
- cr={openSuggestionCr}
1045
- onClose={() => setOpenSuggestionCr(null)}
1985
+ // Remounted when the query names a different file, so the seeded
1986
+ // selection below is re-read instead of being a one-time landing.
1987
+ key={`${openSuggestion.cr.number}:${openSuggestion.file}`}
1988
+ cr={openSuggestion.cr}
1989
+ initialPath={openSuggestion.file}
1990
+ onClose={() => setOpenSuggestion(null)}
1046
1991
  onResolved={() => {
1047
- setOpenSuggestionCr(null);
1992
+ setOpenSuggestion(null);
1048
1993
  window.dispatchEvent(new Event(PR_STALE_EVENT));
1049
1994
  }}
1050
1995
  />
1051
1996
  )}
1052
1997
  {accessTarget && (
1053
1998
  <ManageAccessDialog
1054
- key={accessTarget.relativePath}
1999
+ key={`${accessTarget.relativePath}@${accessProposal?.branch ?? ''}`}
1055
2000
  entry={accessTarget}
2001
+ proposal={accessProposal}
1056
2002
  // The dialog is keyed on the path, so pointing it at a parent remounts
1057
- // it against that folder — the whole retarget is this one setter.
1058
- onManageAncestor={setAccessTarget}
1059
- onClose={() => setAccessTarget(null)}
2003
+ // it against that folder, on the same branch the grant was read on.
2004
+ onManageAncestor={(ancestor) => {
2005
+ setInheritedProposal(accessProposal);
2006
+ setAccessTarget(ancestor);
2007
+ }}
2008
+ onClose={() => {
2009
+ setInheritedProposal(undefined);
2010
+ setAccessTarget(null);
2011
+ }}
1060
2012
  />
1061
2013
  )}
1062
2014
  </>
1063
2015
  );
1064
2016
  }
1065
2017
 
2018
+ /** Shown when the read filter kept entries out and none are left on screen. */
2019
+ export const NOTHING_SHARED_MESSAGE = 'Nothing here is shared with you yet. Ask an admin to grant you access.';
2020
+ /** Shown when the knowledge base has nothing in it at all. */
2021
+ export const KB_EMPTY_MESSAGE = 'This knowledge base is empty.';
2022
+ /**
2023
+ * Shown when `<kbDirName>/` is not in the workspace tree at all. Not the same
2024
+ * emptiness as the one above: the knowledge base is not empty, it is not
2025
+ * THERE, and the next step is an operator's (the clone failed, or the
2026
+ * deployment names a folder that was never checked out) rather than a
2027
+ * writer's. Before this existed the sidebars guessed a root instead, and
2028
+ * rendered whatever directory happened to sit beside the missing one.
2029
+ */
2030
+ export const CHECKOUT_MISSING_MESSAGE = 'Nothing to show here: the repository checkout is missing.';
2031
+
2032
+ /**
2033
+ * Why a tree has nothing in it, when it has nothing in it. Read is
2034
+ * default-deny, so an empty sidebar has two causes that look identical and
2035
+ * call for different next steps: the caller may read none of what exists
2036
+ * (ask an admin), or nothing exists yet (make something — said only to a
2037
+ * caller who may write at `rootPath`, the surface's root folder).
2038
+ *
2039
+ * Renders nothing while the tree loads and once a single entry is visible.
2040
+ * The Knowledge explorer and the Library's trees both render it, from the
2041
+ * same merged listing, so they give the same answer — each for what IT shows.
2042
+ * Knowledge shows the knowledge base (`scope: 'tree'`, the default: the
2043
+ * reserved roots aside, an entry anywhere counts, because a stray top-level
2044
+ * folder is folded into Knowledge). A Library tree shows one root
2045
+ * (`scope: 'root'`): it is empty when that root is, whatever the notes
2046
+ * beside it hold.
2047
+ */
2048
+ export function EmptyTreeNotice({ rootPath, scope = 'tree' }: { rootPath: string | null; scope?: 'tree' | 'root' }) {
2049
+ const { kbDirName } = useWorkspace();
2050
+ const { tree, withheld: listingWithheld } = useMergedWorkspaceTree();
2051
+ const oneRoot = scope === 'root' && rootPath !== null;
2052
+ const empty = tree !== null && (oneRoot ? !subtreeHasVisibleEntries(tree, rootPath) : !treeHasVisibleEntries(tree, kbDirName));
2053
+ // What was kept out of what THIS notice covers: one root's own count, or
2054
+ // the listing's — a Skills tree emptied by the rules says so; a Skills tree
2055
+ // that is simply empty beside a withheld Knowledge does not.
2056
+ const withheld = oneRoot ? subtreeWithheld(tree, rootPath) : listingWithheld;
2057
+ // Asked only when the message would carry the hint: a withheld tree never does.
2058
+ const canWrite = useCanWriteFolder(empty && withheld === 0 ? rootPath : null);
2059
+ if (!empty) return null;
2060
+ if (withheld > 0) {
2061
+ return (
2062
+ <div data-testid="tree-empty-notice" role="status" className="px-3 py-2 text-xs text-ink-muted">
2063
+ {NOTHING_SHARED_MESSAGE}
2064
+ </div>
2065
+ );
2066
+ }
2067
+ // After the withheld check, not before: a reader who may open nothing sees
2068
+ // a tree the filter emptied, and "the checkout is missing" would be a
2069
+ // diagnosis of the wrong thing. Only a tree nothing was kept out of can
2070
+ // say the folder is genuinely not there.
2071
+ if (checkoutRoot(tree, kbDirName) === null) {
2072
+ return (
2073
+ <div data-testid="tree-empty-notice" role="status" className="px-3 py-2 text-xs text-ink-muted">
2074
+ {CHECKOUT_MISSING_MESSAGE}
2075
+ </div>
2076
+ );
2077
+ }
2078
+ return (
2079
+ <div data-testid="tree-empty-notice" role="status" className="px-3 py-2 text-xs text-ink-muted">
2080
+ {KB_EMPTY_MESSAGE}
2081
+ {canWrite && (
2082
+ <>
2083
+ {' '}
2084
+ <span data-testid="tree-empty-create-hint">
2085
+ Use New file or New folder on the folder above, or drop files here.
2086
+ </span>
2087
+ </>
2088
+ )}
2089
+ </div>
2090
+ );
2091
+ }
2092
+
2093
+ /**
2094
+ * Whether the caller may write into a workspace-relative folder; false until
2095
+ * known, and on a failed lookup — it decides a hint, never a gate. The same
2096
+ * short-circuits as `useFileAccess`: a path outside the KB and a draft branch
2097
+ * are writable without asking.
2098
+ */
2099
+ function useCanWriteFolder(workspacePath: string | null): boolean {
2100
+ const { workspaceId, kbDirName } = useWorkspace();
2101
+ const [answer, setAnswer] = useState<{ key: string; canWrite: boolean } | null>(null);
2102
+ const prefix = kbDirName ? `${kbDirName}/` : null;
2103
+ const key = workspacePath && workspaceId && prefix ? `${workspaceId}|${workspacePath}` : null;
2104
+ // The KB clone's own folder (a tree that predates the split) is the repo
2105
+ // root: inside the KB, and sent as-is — the server reads a bare kbDirName as ''.
2106
+ const isKbRoot = workspacePath !== null && workspacePath === kbDirName;
2107
+ const shortCircuit =
2108
+ key !== null &&
2109
+ ((!isKbRoot && !workspacePath!.startsWith(prefix!)) || !isProtectedBranch(decodeURIComponent(workspaceId!)));
2110
+ useEffect(() => {
2111
+ if (key === null || shortCircuit) return;
2112
+ let cancelled = false;
2113
+ fetchFileAccess(workspaceId!, isKbRoot ? workspacePath! : workspacePath!.slice(prefix!.length), 'folder')
2114
+ .then((res) => { if (!cancelled) setAnswer({ key, canWrite: res.canWrite }); })
2115
+ .catch(() => { if (!cancelled) setAnswer({ key, canWrite: false }); });
2116
+ return () => { cancelled = true; };
2117
+ }, [key, shortCircuit, isKbRoot, workspaceId, workspacePath, prefix]);
2118
+ if (key === null) return false;
2119
+ if (shortCircuit) return true;
2120
+ return answer?.key === key && answer.canWrite;
2121
+ }
2122
+
1066
2123
  /**
1067
- * The upload banners: the last upload's error, or the one non-error notice
1068
- * (it landed on the suggestions branch). Rendered by every tree that can
1069
- * upload, because the state is the workspace's and a drop into a tree with no
1070
- * banner would fail — or succeed elsewhere — in silence.
2124
+ * The upload banners for THIS tree: the last upload's error, or its one
2125
+ * non-error notice (the upload is under way, or it landed on the suggestions
2126
+ * branch). Every tree that can upload renders a pair, because the state is
2127
+ * the workspace's and a drop into a tree with no banner would fail — or
2128
+ * succeed elsewhere — in silence. Each pair shows only the banners stamped
2129
+ * with its own `uploadTarget`, which is what keeps one drop from painting
2130
+ * the same notice in both of the Library sidebar's trees.
2131
+ *
2132
+ * The error says everything in the banner, on as many lines as it takes:
2133
+ * the file's name, the server's reason in full, and what to do next. It used
2134
+ * to be one `truncate`d line with the reason in a `title` — a tooltip nobody
2135
+ * on a touch device could open, over text that had already cut the reason off.
1071
2136
  */
1072
2137
  export function UploadNotices() {
1073
- const { uploadError, clearUploadError, uploadNotice, clearUploadNotice } = useWorkspace();
2138
+ const { uploadErrors, clearUploadError, uploadNotices, clearUploadNotice } = useWorkspace();
2139
+ const target = useUploadTarget();
2140
+ const error = uploadErrors.get(target) ?? null;
2141
+ const notice = uploadNotices.get(target) ?? null;
1074
2142
  return (
1075
2143
  <>
1076
- {uploadError && (
2144
+ {error && (
1077
2145
  <div
1078
2146
  role="alert"
1079
2147
  className="flex items-start gap-1 px-2 py-1 text-xs text-danger bg-danger-soft border-b border-danger/30 shrink-0"
1080
2148
  >
1081
- <span className="flex-1 truncate" title={uploadError.reason}>
1082
- Couldn't add {uploadError.filename}: {uploadError.reason}
1083
- </span>
2149
+ <div className="flex-1 min-w-0 space-y-0.5 whitespace-pre-wrap break-words">
2150
+ <div className="font-medium">Couldn't add {error.filename}</div>
2151
+ <div>{error.reason}</div>
2152
+ <div className="text-ink-muted">{uploadErrorNextStep(error.status)}</div>
2153
+ </div>
1084
2154
  <IconButton
1085
2155
  size={18}
1086
2156
  tone="danger"
1087
2157
  title="Dismiss"
1088
2158
  aria-label="Dismiss upload error"
1089
- onClick={clearUploadError}
2159
+ onClick={() => clearUploadError(target)}
1090
2160
  >
1091
2161
  <X size={12} />
1092
2162
  </IconButton>
1093
2163
  </div>
1094
2164
  )}
1095
- {/* Not an error: the upload LANDED, on the suggestions branch. Saying
1096
- so is load-bearing — nothing appears in the tree where the user
1097
- dropped the files, and silence there reads as a failed upload. */}
1098
- {uploadNotice && (
2165
+ {/* Either "this is happening" or "it LANDED, on the suggestions
2166
+ branch". Both are load-bearing: a suggestion-routed upload puts
2167
+ nothing in the tree where the user dropped the files, and silence
2168
+ there reads as a failed upload. */}
2169
+ {notice && (
1099
2170
  <div
1100
2171
  role="status"
2172
+ data-testid="upload-notice"
1101
2173
  className="flex items-start gap-1 px-2 py-1 text-xs text-ink bg-wait-soft border-b border-line shrink-0"
1102
2174
  >
1103
- <span className="flex-1" title={uploadNotice}>
1104
- {uploadNotice}
1105
- </span>
1106
- <IconButton
1107
- size={18}
1108
- title="Dismiss"
1109
- aria-label="Dismiss upload notice"
1110
- onClick={clearUploadNotice}
1111
- >
1112
- <X size={12} />
1113
- </IconButton>
2175
+ <span className="flex-1 min-w-0 whitespace-pre-wrap break-words">{notice.message}</span>
2176
+ {/* Nothing to dismiss about an upload still running — it clears
2177
+ itself the moment it has a result to show instead. */}
2178
+ {notice.kind !== 'progress' && (
2179
+ <IconButton
2180
+ size={18}
2181
+ title="Dismiss"
2182
+ aria-label="Dismiss upload notice"
2183
+ onClick={() => clearUploadNotice(target)}
2184
+ >
2185
+ <X size={12} />
2186
+ </IconButton>
2187
+ )}
1114
2188
  </div>
1115
2189
  )}
1116
2190
  </>
1117
2191
  );
1118
2192
  }
1119
2193
 
1120
- /**
1121
- * Walk down to the node that actually holds the KB content. The file tree roots
1122
- * at the per-branch workspace dir and wraps the KB clone a level or two deep
1123
- * (`<branch>/<kbDir>/{KnowledgeBase,Data,Agents,Pipelines,Skills,Tools,…}`), so
1124
- * the split lives below the visible root. Returns the first node whose children
1125
- * include one of those well-known root directories, or null when there's no
1126
- * such split (legacy clones).
1127
- */
1128
- // (`findKbRoot` lives in `../utils/fileTree` — shared with registry-
1129
- // contributed explorer items.)
2194
+ // (`checkoutRoot` lives in `../utils/fileTree` — the one lookup every
2195
+ // surface that reads the workspace tree goes through.)
1130
2196
 
1131
2197
  export function FileExplorer() {
1132
- const { openFilePath, dispatchUpload } = useWorkspace();
2198
+ const { openFilePath, dispatchUpload, kbDirName } = useWorkspace();
1133
2199
  const { openFile } = useFileNav();
1134
2200
  const [dragOver, setDragOver] = useState(false);
1135
- // Download is now a per-path permission (resolved server-side from the
1136
- // access tree's `download:` verb), so there's no global preflight gate
1137
- // here anymore. The menu items always render; if the user clicks on a
1138
- // file they don't have download permission for, the backend returns 403
1139
- // and `handleDownload` shows the error.
2201
+ // Download is a per-path permission (resolved server-side from the access
2202
+ // tree's `download:` verb), so there is no global gate here: the menu asks
2203
+ // about the entry it was opened on (`useDownloadVerdict`) and disables the
2204
+ // item with the reason. A 403 that still lands — the permission changed
2205
+ // while the menu was open — becomes the row's own inline notice.
1140
2206
  const { tree: mergedTree, suggestionOnlyPaths } = useMergedWorkspaceTree();
2207
+ // THE root, for every row this explorer draws: the repository checkout, by
2208
+ // the name the deployment gave it. Nothing beside it in the workspace — a
2209
+ // stray `KnowledgeBase/`, a loose upload, another clone — is reachable from
2210
+ // anything below, because nothing above the checkout is ever read. Null
2211
+ // when the workspace holds no checkout, which is its own empty state
2212
+ // rather than a cue to go looking for a root that looks about right.
2213
+ const checkout = useMemo(() => checkoutRoot(mergedTree, kbDirName), [mergedTree, kbDirName]);
1141
2214
  // The pane workspace's own navigation: the open tab is the current row, and
1142
2215
  // a click opens the file on the checked-out branch.
1143
2216
  const nav = useMemo<TreeNav>(() => ({ activePath: openFilePath, open: openFile }), [openFilePath, openFile]);
@@ -1163,14 +2236,17 @@ export function FileExplorer() {
1163
2236
  );
1164
2237
  // Resolve pinned paths to live tree entries, dropping any that no longer
1165
2238
  // exist on this branch (a folder pinned elsewhere may be absent here).
2239
+ // Resolved from the CHECKOUT, not the workspace root, for the same reason
2240
+ // the sections are: a pin is a shortcut into the repository, and a path
2241
+ // that lands beside it resolves to nothing rather than to a row.
1166
2242
  const pinnedEntries = useMemo(
1167
2243
  () =>
1168
- mergedTree
2244
+ checkout
1169
2245
  ? pinnedPaths
1170
- .map((p) => findEntryByPath(mergedTree, p))
2246
+ .map((p) => findEntryByPath(checkout, p))
1171
2247
  .filter((e): e is FileTreeEntry => e != null)
1172
2248
  : [],
1173
- [mergedTree, pinnedPaths],
2249
+ [checkout, pinnedPaths],
1174
2250
  );
1175
2251
 
1176
2252
  // Registry-contributed rows for the Pinned section (rendered below the
@@ -1202,9 +2278,7 @@ export function FileExplorer() {
1202
2278
  // created by core (see `CORE_REQUIRED_DIRS`) — a deployment that owns the
1203
2279
  // agentic execution layer seeds them, and this reads whatever is there.
1204
2280
  const sections = useMemo(() => {
1205
- // Descend past the workspace / KB-clone wrapper levels to the node that
1206
- // actually holds the well-known root dirs, then split that level.
1207
- const kids = findKbRoot(mergedTree)?.children;
2281
+ const kids = checkout?.children;
1208
2282
  if (!kids) return null;
1209
2283
  const findDir = (name: string) =>
1210
2284
  kids.find((c) => c.type === 'directory' && c.name === name);
@@ -1249,23 +2323,33 @@ export function FileExplorer() {
1249
2323
  pipelines: pipelinesRoot,
1250
2324
  looseFiles: kids.filter((c) => c.type === 'file'),
1251
2325
  };
1252
- }, [mergedTree]);
2326
+ }, [checkout]);
1253
2327
 
1254
2328
  const handleDrop = useCallback(
1255
2329
  (e: React.DragEvent) => {
2330
+ // Nothing to drop INTO: the tree below renders no row and says the
2331
+ // checkout is missing, and this drop used to be sent with an empty
2332
+ // target — the workspace root, beside the missing folder, where
2333
+ // nothing this sidebar shows can ever live. Refused before
2334
+ // `preventDefault`, so the browser's own cursor says "not here".
2335
+ if (!checkout) return;
1256
2336
  e.preventDefault();
1257
2337
  setDragOver(false);
1258
2338
  // Only handle external file/folder drops at the root level.
1259
2339
  if (e.dataTransfer.getData(DRAG_MIME)) return;
2340
+ // The background of the tree is the tree's ROOT — the checkout — not
2341
+ // the workspace directory that happens to contain it.
2342
+ const target = checkout.relativePath;
1260
2343
  const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
1261
2344
  if (entries.length > 0) {
1262
- dispatchUpload({ kind: 'items', entries }, '');
2345
+ // Outside the `TreeChrome` below, so this one names the tree itself.
2346
+ dispatchUpload({ kind: 'items', entries }, target, KNOWLEDGE_UPLOAD_TARGET);
1263
2347
  return;
1264
2348
  }
1265
2349
  const files = Array.from(e.dataTransfer.files);
1266
- if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
2350
+ if (files.length > 0) dispatchUpload({ kind: 'files', files }, target, KNOWLEDGE_UPLOAD_TARGET);
1267
2351
  },
1268
- [dispatchUpload],
2352
+ [checkout, dispatchUpload],
1269
2353
  );
1270
2354
 
1271
2355
  return (
@@ -1285,6 +2369,9 @@ export function FileExplorer() {
1285
2369
  }`}
1286
2370
  onDrop={handleDrop}
1287
2371
  onDragOver={(e) => {
2372
+ // Same refusal as the drop: no checkout, no drop target, so no
2373
+ // highlight promising one.
2374
+ if (!checkout) return;
1288
2375
  e.preventDefault();
1289
2376
  setDragOver(true);
1290
2377
  }}
@@ -1312,6 +2399,10 @@ export function FileExplorer() {
1312
2399
  <div className="mx-3 my-2 border-t border-line" />
1313
2400
  {!mergedTree ? (
1314
2401
  <div className="px-3 py-4 text-xs text-ink-muted">Loading...</div>
2402
+ ) : !checkout ? (
2403
+ // No checkout in the workspace: no tree, and no guessing at one
2404
+ // from whatever else is there. `EmptyTreeNotice` below says why.
2405
+ null
1315
2406
  ) : sections ? (
1316
2407
  <>
1317
2408
  {sections.knowledge && (
@@ -1336,10 +2427,23 @@ export function FileExplorer() {
1336
2427
  )}
1337
2428
  </>
1338
2429
  ) : (
1339
- <FileTreeNode entry={mergedTree} depth={0} />
2430
+ // A clone that predates the split: no named roots to section by, so
2431
+ // the checkout folder itself is the tree. Still the checkout — the
2432
+ // fallback is a different SHAPE, never a different directory — and
2433
+ // it is the ROOT row, not a folder inside one: the workspace
2434
+ // directory above it is not something this explorer shows.
2435
+ <FileTreeNode entry={checkout} depth={0} root />
1340
2436
  )}
2437
+ {/* Under the (empty) roots, so the hint's "folder above" is on
2438
+ screen: Knowledge's own folder is where a first page goes. A tree
2439
+ that predates the split has no Knowledge section, so the checkout
2440
+ folder itself is where a first page goes — and when there is no
2441
+ checkout at all the notice says THAT instead, and there is no
2442
+ folder to offer. */}
2443
+ <EmptyTreeNotice
2444
+ rootPath={sections ? sections.knowledge?.relativePath ?? null : checkout?.relativePath ?? null}
2445
+ />
1341
2446
  </div>
1342
- <PullRequestsForMe />
1343
2447
  </div>
1344
2448
  </TreeChrome>
1345
2449
  );