@bevel-software/platform-core-frontend 0.14.0 → 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 (360) hide show
  1. package/THIRD-PARTY-NOTICES.md +2 -2
  2. package/package.json +3 -3
  3. package/src/core/CoreAppShell.tsx +34 -26
  4. package/src/core/__tests__/AppChrome.test.tsx +0 -3
  5. package/src/core/__tests__/bootstrap.test.ts +33 -1
  6. package/src/core/__tests__/events.test.ts +43 -0
  7. package/src/core/bootstrap.ts +38 -1
  8. package/src/core/events.ts +85 -3
  9. package/src/core/registry.ts +1 -1
  10. package/src/lib/__tests__/api.test.ts +38 -0
  11. package/src/lib/__tests__/email.test.ts +44 -0
  12. package/src/lib/api.ts +19 -2
  13. package/src/lib/email.ts +37 -1
  14. package/src/lib/utils.ts +2 -0
  15. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +141 -0
  16. package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +204 -0
  17. package/src/modules/access/__tests__/ManageAccessDialog.download-read.test.tsx +234 -0
  18. package/src/modules/access/__tests__/ManageAccessDialog.edited-row-visible.test.tsx +160 -0
  19. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +2 -2
  20. package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +166 -0
  21. package/src/modules/access/__tests__/ManageAccessDialog.restrict.test.tsx +510 -0
  22. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-axes.test.tsx +299 -0
  23. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-width.test.tsx +226 -0
  24. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +781 -76
  25. package/src/modules/access/__tests__/ManageAccessDialog.unknown-email.test.tsx +314 -0
  26. package/src/modules/access/__tests__/manage-access-affordance.test.ts +14 -0
  27. package/src/modules/access/__tests__/plugin-token.test.ts +21 -0
  28. package/src/modules/access/__tests__/tailwindDeclarations.ts +210 -0
  29. package/src/modules/access/api.ts +192 -10
  30. package/src/modules/access/components/ManageAccessDialog.tsx +1337 -570
  31. package/src/modules/access/manage-access-affordance.ts +17 -0
  32. package/src/modules/admin/__tests__/AddMemberInput.test.tsx +297 -0
  33. package/src/modules/admin/__tests__/AdminRolesPage.capabilities.test.tsx +2 -2
  34. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +189 -0
  35. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +1 -1
  36. package/src/modules/admin/__tests__/ConnectionKeysPage.test.tsx +266 -0
  37. package/src/modules/admin/__tests__/DirectoryGroupsPage.suggest.test.tsx +182 -0
  38. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +165 -14
  39. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +401 -4
  40. package/src/modules/admin/__tests__/group-members-path.test.ts +27 -0
  41. package/src/modules/admin/components/AddMemberInput.tsx +268 -0
  42. package/src/modules/admin/components/AdminRolesPage.tsx +97 -132
  43. package/src/modules/admin/components/ConnectionKeysPage.tsx +269 -0
  44. package/src/modules/admin/components/DirectoryGroupsPage.tsx +91 -39
  45. package/src/modules/admin/components/UserAccountsPage.tsx +271 -37
  46. package/src/modules/admin/components/connection-keys-grouping.ts +43 -0
  47. package/src/modules/admin/components/group-members-path.ts +32 -0
  48. package/src/modules/admin/services/connection-keys.api.ts +47 -0
  49. package/src/modules/admin/services/roles.api.ts +12 -1
  50. package/src/modules/auth/__tests__/AccountPage.test.tsx +50 -2
  51. package/src/modules/auth/components/AccountPage.tsx +73 -54
  52. package/src/modules/auth/components/LoginScreen.tsx +1 -0
  53. package/src/modules/auth/services/account.api.ts +78 -4
  54. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +144 -0
  55. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +422 -0
  56. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +431 -0
  57. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +193 -0
  58. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +142 -0
  59. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +202 -0
  60. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +205 -13
  61. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +271 -0
  62. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +208 -0
  63. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +286 -0
  64. package/src/modules/change-requests/__tests__/propose.concurrent.test.ts +273 -0
  65. package/src/modules/change-requests/__tests__/readFailure.test.ts +122 -0
  66. package/src/modules/change-requests/__tests__/useCrFileDiffs.test.tsx +238 -0
  67. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +56 -1
  68. package/src/modules/change-requests/__tests__/useForkPointFile.test.tsx +79 -0
  69. package/src/modules/change-requests/components/BranchFilePreview.tsx +357 -0
  70. package/src/modules/change-requests/components/ChangeBox.tsx +31 -2
  71. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +862 -72
  72. package/src/modules/change-requests/components/CrFileTree.tsx +74 -58
  73. package/src/modules/change-requests/components/FileChangeBoxes.tsx +19 -15
  74. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +41 -7
  75. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +181 -23
  76. package/src/modules/change-requests/hooks/useFileOnBranch.ts +70 -7
  77. package/src/modules/change-requests/hooks/useForkPointFile.ts +77 -0
  78. package/src/modules/change-requests/services/change-requests.api.ts +57 -1
  79. package/src/modules/change-requests/services/denied-file.api.ts +53 -0
  80. package/src/modules/change-requests/services/propose.api.ts +97 -8
  81. package/src/modules/change-requests/utils/approval.ts +15 -0
  82. package/src/modules/change-requests/utils/author.ts +32 -0
  83. package/src/modules/change-requests/utils/readFailure.ts +110 -0
  84. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +20 -0
  85. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +65 -1
  86. package/src/modules/git/components/FileHistoryPanel.tsx +5 -0
  87. package/src/modules/git/components/GitSyncFailedBanner.tsx +68 -5
  88. package/src/modules/git/components/PullRequestsForMe.tsx +51 -24
  89. package/src/modules/git/services/__tests__/error-messages.test.ts +29 -0
  90. package/src/modules/git/services/error-messages.ts +12 -0
  91. package/src/modules/git/services/pr-prompts.ts +5 -5
  92. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +401 -0
  93. package/src/modules/layout/__tests__/SidebarFooterGrid.test.tsx +286 -0
  94. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +61 -0
  95. package/src/modules/layout/components/AppLayout.tsx +2 -0
  96. package/src/modules/layout/components/MobileChatLayout.tsx +4 -1
  97. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +4 -1
  98. package/src/modules/layout/components/SidebarFrame.tsx +109 -4
  99. package/src/modules/library/__tests__/AddToPluginDialog.test.tsx +171 -5
  100. package/src/modules/library/__tests__/DeleteToolDialog.test.tsx +356 -0
  101. package/src/modules/library/__tests__/IntegrationsSetupReminder.test.tsx +60 -0
  102. package/src/modules/library/__tests__/LibraryCard.test.tsx +91 -10
  103. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +242 -107
  104. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +104 -99
  105. package/src/modules/library/__tests__/LinkSkillPanel.test.tsx +136 -0
  106. package/src/modules/library/__tests__/LockedPluginView.test.tsx +103 -7
  107. package/src/modules/library/__tests__/NewPluginDialog.test.tsx +18 -8
  108. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +79 -3
  109. package/src/modules/library/__tests__/PersonalPluginPage.test.tsx +201 -0
  110. package/src/modules/library/__tests__/PluginExtras.test.tsx +115 -9
  111. package/src/modules/library/__tests__/PluginJoinRequests.test.tsx +60 -1
  112. package/src/modules/library/__tests__/PluginPage.test.tsx +453 -7
  113. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +17 -57
  114. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +161 -97
  115. package/src/modules/library/__tests__/PluginsSidebarMenu.test.tsx +16 -0
  116. package/src/modules/library/__tests__/SharedViaPlugins.test.tsx +106 -0
  117. package/src/modules/library/__tests__/SkillPage.test.tsx +391 -78
  118. package/src/modules/library/__tests__/SkillsTree.test.tsx +461 -0
  119. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +582 -71
  120. package/src/modules/library/__tests__/ToolPage.test.tsx +94 -4
  121. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +279 -21
  122. package/src/modules/library/__tests__/auth-harness.tsx +9 -9
  123. package/src/modules/library/__tests__/card-row-menu.test.tsx +320 -0
  124. package/src/modules/library/__tests__/library-data.mapping.test.tsx +98 -0
  125. package/src/modules/library/__tests__/library-data.stale.test.tsx +183 -0
  126. package/src/modules/library/__tests__/library-data.test.ts +7 -0
  127. package/src/modules/library/__tests__/library-paths.test.ts +75 -0
  128. package/src/modules/library/__tests__/link-membership.test.ts +129 -0
  129. package/src/modules/library/__tests__/name-with-badges.test.tsx +273 -0
  130. package/src/modules/library/__tests__/newSkillMarkdown.test.ts +30 -0
  131. package/src/modules/library/__tests__/owner-pill.test.tsx +357 -0
  132. package/src/modules/library/__tests__/pending-tools.test.tsx +400 -0
  133. package/src/modules/library/__tests__/plugin-entries.test.ts +122 -0
  134. package/src/modules/library/__tests__/plugin-summary.test.ts +67 -0
  135. package/src/modules/library/__tests__/status.test.ts +82 -2
  136. package/src/modules/library/__tests__/tools.api.test.ts +44 -1
  137. package/src/modules/library/__tests__/useJoinRequests.test.tsx +46 -0
  138. package/src/modules/library/components/AccessRequestsBanner.tsx +85 -47
  139. package/src/modules/library/components/AddDialogTabs.tsx +103 -0
  140. package/src/modules/library/components/AddToPluginDialog.tsx +107 -18
  141. package/src/modules/library/components/IntegrationsSetupReminder.tsx +59 -0
  142. package/src/modules/library/components/ItemActionsMenu.tsx +288 -0
  143. package/src/modules/library/components/LibraryCard.tsx +149 -34
  144. package/src/modules/library/components/LibraryLayout.tsx +120 -247
  145. package/src/modules/library/components/LibraryPage.tsx +172 -39
  146. package/src/modules/library/components/LinkSkillPanel.tsx +169 -0
  147. package/src/modules/library/components/LockedPluginView.tsx +63 -35
  148. package/src/modules/library/components/NameWithBadges.tsx +164 -0
  149. package/src/modules/library/components/NewPluginDialog.tsx +19 -5
  150. package/src/modules/library/components/PageActions.tsx +31 -9
  151. package/src/modules/library/components/{PendingSkillReview.tsx → PendingItemReview.tsx} +14 -7
  152. package/src/modules/library/components/PersonalAddDialog.tsx +68 -18
  153. package/src/modules/library/components/PersonalPluginPage.tsx +123 -23
  154. package/src/modules/library/components/PluginExtras.tsx +143 -18
  155. package/src/modules/library/components/PluginIndexRow.tsx +47 -12
  156. package/src/modules/library/components/PluginPage.tsx +234 -38
  157. package/src/modules/library/components/PluginRows.tsx +286 -0
  158. package/src/modules/library/components/PluginsSidebar.tsx +271 -238
  159. package/src/modules/library/components/PluginsSidebarMenu.tsx +26 -1
  160. package/src/modules/library/components/RenamePluginDialog.tsx +136 -0
  161. package/src/modules/library/components/ShareButton.tsx +17 -0
  162. package/src/modules/library/components/SkillsTree.tsx +204 -0
  163. package/src/modules/library/components/StatusDot.tsx +1 -0
  164. package/src/modules/library/components/TeamRoute.tsx +15 -0
  165. package/src/modules/library/components/__tests__/upload-notices-once-per-page.test.tsx +144 -0
  166. package/src/modules/library/components/plugin-page-parts.tsx +132 -23
  167. package/src/modules/library/components/skill-page/SharedViaPlugins.tsx +212 -0
  168. package/src/modules/library/components/skill-page/SkillFilePane.tsx +5 -0
  169. package/src/modules/library/components/skill-page/SkillPage.tsx +337 -121
  170. package/src/modules/library/components/tool-page/DeleteToolDialog.tsx +218 -0
  171. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +79 -178
  172. package/src/modules/library/components/tool-page/ToolPage.tsx +116 -17
  173. package/src/modules/library/components/tool-page/ToolVarRow.tsx +42 -41
  174. package/src/modules/library/hooks/__tests__/useLibraryData.test.ts +98 -0
  175. package/src/modules/library/hooks/useJoinRequests.ts +48 -18
  176. package/src/modules/library/hooks/useLibraryData.ts +92 -19
  177. package/src/modules/library/routes/LibraryRoutes.tsx +14 -11
  178. package/src/modules/library/routes/WorkspaceItemRoute.tsx +229 -82
  179. package/src/modules/library/routes/library-paths.ts +46 -35
  180. package/src/modules/library/services/library.api.ts +89 -17
  181. package/src/modules/library/services/plugins.api.ts +161 -9
  182. package/src/modules/library/services/teams.api.ts +15 -0
  183. package/src/modules/library/services/tools.api.ts +78 -0
  184. package/src/modules/library/state/library-data.tsx +268 -37
  185. package/src/modules/library/utils/personal-plugin.ts +13 -15
  186. package/src/modules/library/utils/plugin-entries.ts +134 -0
  187. package/src/modules/library/utils/plugin-summary.ts +102 -0
  188. package/src/modules/library/utils/status.ts +204 -35
  189. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +11 -3
  190. package/src/modules/onboarding/__tests__/onboarding.test.tsx +853 -760
  191. package/src/modules/onboarding/agent-clients.ts +55 -23
  192. package/src/modules/onboarding/components/ConnectAgentPill.tsx +5 -1
  193. package/src/modules/onboarding/components/WelcomePage.tsx +98 -62
  194. package/src/modules/pr/services/pr-merge.api.ts +2 -1
  195. package/src/modules/review/components/MarkdownDiffViewer.tsx +53 -8
  196. package/src/modules/review/components/ReviewPanel.tsx +15 -17
  197. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +64 -0
  198. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +25 -1
  199. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +454 -117
  200. package/src/modules/secrets-vault/components/SecretsPage.tsx +48 -7
  201. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +84 -5
  202. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +425 -0
  203. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +417 -82
  204. package/src/modules/secrets-vault/components/__tests__/ToolSecretsPanel.test.tsx +105 -0
  205. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +407 -0
  206. package/src/modules/secrets-vault/probe/SavedKeyProbeResult.tsx +98 -0
  207. package/src/modules/secrets-vault/probe/__tests__/probe-verdict.test.ts +160 -0
  208. package/src/modules/secrets-vault/probe/probe-verdict.ts +108 -0
  209. package/src/modules/secrets-vault/probe/useSavedKeyProbe.ts +228 -0
  210. package/src/modules/secrets-vault/services/connect.api.ts +36 -5
  211. package/src/modules/secrets-vault/utils/connect-status.ts +98 -0
  212. package/src/modules/settings/components/ClaudeConnectionCard.tsx +154 -0
  213. package/src/modules/settings/components/ClaudeConnectionFields.tsx +23 -0
  214. package/src/modules/settings/components/DeploymentPage.tsx +16 -22
  215. package/src/modules/settings/components/MarketplaceSection.tsx +152 -0
  216. package/src/modules/settings/components/__tests__/ClaudeConnectionCard.test.tsx +63 -0
  217. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +74 -1
  218. package/src/modules/settings/components/__tests__/MarketplaceSection.test.tsx +325 -0
  219. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +5 -5
  220. package/src/modules/settings/services/github-facade.api.ts +66 -0
  221. package/src/modules/settings/settings-nav-items.tsx +10 -2
  222. package/src/modules/setup/__tests__/setup.oidc.test.tsx +172 -0
  223. package/src/modules/setup/__tests__/setup.probe-refusal.test.tsx +123 -0
  224. package/src/modules/setup/__tests__/setup.test.tsx +615 -4
  225. package/src/modules/setup/__tests__/useSetupStatus.test.tsx +130 -0
  226. package/src/modules/setup/components/SetupGate.tsx +16 -16
  227. package/src/modules/setup/components/SetupScreen.tsx +711 -40
  228. package/src/modules/setup/hooks/useSetupStatus.ts +93 -0
  229. package/src/modules/setup/services/setup.api.ts +218 -3
  230. package/src/modules/setup/utils/__tests__/root-folders.test.ts +72 -0
  231. package/src/modules/setup/utils/root-folders.ts +46 -0
  232. package/src/modules/toolbar/assets/claude-setup/01-add-manually.webp +0 -0
  233. package/src/modules/toolbar/assets/claude-setup/02-add-configuration.webp +0 -0
  234. package/src/modules/toolbar/assets/claude-setup/03-connect-account.webp +0 -0
  235. package/src/modules/toolbar/assets/claude-setup/04-pick-instance.webp +0 -0
  236. package/src/modules/toolbar/assets/claude-setup/05-plugins-add.webp +0 -0
  237. package/src/modules/toolbar/assets/claude-setup/06-add-marketplace.webp +0 -0
  238. package/src/modules/toolbar/assets/claude-setup/07-paste-url-sync.webp +0 -0
  239. package/src/modules/toolbar/assets/claude-setup/08-install-plugins.webp +0 -0
  240. package/src/modules/toolbar/assets/claude-setup/09-select-repository.webp +0 -0
  241. package/src/modules/toolbar/assets/claude-setup/10-connector-not-added.webp +0 -0
  242. package/src/modules/toolbar/assets/claude-setup/11-add-custom-connector.webp +0 -0
  243. package/src/modules/toolbar/assets/claude-setup/README.md +68 -0
  244. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +296 -0
  245. package/src/modules/toolbar/components/ClaudeMarketplaceCarousel.tsx +107 -0
  246. package/src/modules/toolbar/components/ClaudeRegistrationSteps.tsx +127 -0
  247. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +100 -0
  248. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +395 -124
  249. package/src/modules/toolbar/components/ScreenshotStep.tsx +77 -0
  250. package/src/modules/toolbar/components/SetupCarousel.tsx +177 -0
  251. package/src/modules/toolbar/components/__tests__/AgentInstructionsCard.test.tsx +370 -0
  252. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +659 -36
  253. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +2 -2
  254. package/src/modules/toolbar/components/__tests__/claude-setup-shots.test.ts +104 -0
  255. package/src/modules/toolbar/components/claude-connector-slide.tsx +38 -0
  256. package/src/modules/toolbar/components/claude-setup-shots.ts +167 -0
  257. package/src/modules/toolbar/components/deployment-address.ts +29 -0
  258. package/src/modules/toolbar/components/setup-step-parts.tsx +35 -0
  259. package/src/modules/toolbar/services/__tests__/agent-instructions.api.test.ts +89 -0
  260. package/src/modules/toolbar/services/agent-instructions.api.ts +167 -0
  261. package/src/modules/toolbar/services/external-api-keys.api.ts +8 -0
  262. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +43 -0
  263. package/src/modules/workflow/state/EventBusProvider.tsx +122 -11
  264. package/src/modules/workflow/state/__tests__/EventBusProvider.storage.test.tsx +87 -0
  265. package/src/modules/workflow/state/__tests__/EventBusProvider.watch.test.tsx +223 -0
  266. package/src/modules/workflow/state/event-bus.context.ts +10 -0
  267. package/src/modules/workspace/__tests__/testFixtures.ts +6 -3
  268. package/src/modules/workspace/components/FileExplorer.tsx +1527 -367
  269. package/src/modules/workspace/components/FileRoute.tsx +376 -22
  270. package/src/modules/workspace/components/FileViewer.tsx +166 -45
  271. package/src/modules/workspace/components/KbDocumentShell.tsx +50 -6
  272. package/src/modules/workspace/components/KbPageHeader.tsx +120 -55
  273. package/src/modules/workspace/components/TreeActionConfirm.tsx +350 -0
  274. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +2473 -129
  275. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +768 -16
  276. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +332 -12
  277. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +39 -0
  278. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +33 -20
  279. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +4 -5
  280. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +13 -4
  281. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +4 -3
  282. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +8 -14
  283. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +75 -16
  284. package/src/modules/workspace/components/renderers/KbImage.tsx +180 -0
  285. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +22 -6
  286. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +48 -22
  287. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +4 -5
  288. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +4 -3
  289. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +4 -3
  290. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +12 -0
  291. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +57 -9
  292. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +13 -1
  293. package/src/modules/workspace/components/renderers/__tests__/ImageRenderer.test.tsx +163 -0
  294. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +237 -0
  295. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +108 -14
  296. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +14 -1
  297. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +16 -1
  298. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +66 -1
  299. package/src/modules/workspace/components/renderers/index.ts +53 -2
  300. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +25 -4
  301. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +40 -0
  302. package/src/modules/workspace/hooks/__tests__/useImageRevision.test.tsx +174 -0
  303. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +179 -1
  304. package/src/modules/workspace/hooks/__tests__/useWorkspaceImageResolver.test.tsx +122 -0
  305. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +892 -7
  306. package/src/modules/workspace/hooks/useImageRevision.ts +101 -0
  307. package/src/modules/workspace/hooks/useMergedWorkspaceTree.ts +89 -0
  308. package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +55 -0
  309. package/src/modules/workspace/hooks/useWorkspaceState.ts +438 -66
  310. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +279 -3
  311. package/src/modules/workspace/routing/kb-routes.ts +207 -30
  312. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +57 -1
  313. package/src/modules/workspace/services/workspace.api.ts +57 -4
  314. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +343 -0
  315. package/src/modules/workspace/state/__tests__/upload-lands-where-it-was-dropped.test.tsx +158 -0
  316. package/src/modules/workspace/state/open-change-requests.tsx +100 -12
  317. package/src/modules/workspace/state/workspace.context.ts +130 -16
  318. package/src/modules/workspace/utils/__tests__/file-trace.test.ts +73 -0
  319. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +234 -5
  320. package/src/modules/workspace/utils/__tests__/pasteLink.test.ts +76 -0
  321. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +364 -0
  322. package/src/modules/workspace/utils/__tests__/uploadError.test.ts +35 -0
  323. package/src/modules/workspace/utils/file-trace.ts +50 -0
  324. package/src/modules/workspace/utils/fileTree.ts +126 -52
  325. package/src/modules/workspace/utils/frontmatter.ts +8 -4
  326. package/src/modules/workspace/utils/pasteLink.ts +90 -0
  327. package/src/modules/workspace/utils/treeConfirm.ts +338 -0
  328. package/src/modules/workspace/utils/uploadError.ts +29 -0
  329. package/src/shared/__tests__/marketplace-url.test.ts +59 -0
  330. package/src/shared/components/Badge.tsx +3 -1
  331. package/src/shared/components/Banner.tsx +5 -1
  332. package/src/shared/components/Button.tsx +16 -2
  333. package/src/shared/components/Dialog.tsx +27 -11
  334. package/src/shared/components/Menu.tsx +13 -1
  335. package/src/shared/components/PageShell.tsx +13 -8
  336. package/src/shared/components/__tests__/primitives.test.tsx +116 -2
  337. package/src/shared/components/__tests__/useFocusHandoff.test.tsx +192 -0
  338. package/src/shared/components/index.ts +2 -0
  339. package/src/shared/components/useDismissableMenu.ts +32 -10
  340. package/src/shared/components/useFocusHandoff.ts +51 -0
  341. package/src/shared/components/useLatestRef.ts +28 -0
  342. package/src/shared/markdown/Markdown.tsx +12 -3
  343. package/src/shared/markdown/__tests__/escapeSpacesInLinkDestinations.test.ts +39 -0
  344. package/src/shared/markdown/hrefs.ts +50 -0
  345. package/src/shared/marketplace-url.ts +118 -0
  346. package/src/shared/mcp/ChatGptInstallLink.tsx +3 -3
  347. package/src/shared/mcp/ConnectionInstructions.tsx +38 -27
  348. package/src/shared/mcp/__tests__/connect-snippets.test.ts +3 -3
  349. package/src/shared/mcp/connect-snippets.ts +14 -9
  350. package/src/shared/mcp/index.ts +1 -1
  351. package/src/shared/theme/__tests__/header-band.test.ts +197 -0
  352. package/src/shared/theme/header.ts +75 -0
  353. package/src/shared/theme/measure.ts +7 -4
  354. package/src/shared/theme/tokens.css +34 -0
  355. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +0 -363
  356. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +0 -97
  357. package/src/modules/library/components/PluginsIndexPage.tsx +0 -265
  358. package/src/modules/update-check/__tests__/UpdateBanner.test.tsx +0 -126
  359. package/src/modules/update-check/components/UpdateBanner.tsx +0 -92
  360. package/src/modules/update-check/services/update-check.api.ts +0 -24
@@ -1,20 +1,23 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { render, screen, fireEvent, waitFor, act, cleanup } from '@testing-library/react';
2
+ import { render, screen, fireEvent, waitFor, act, cleanup, within } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
- import { MemoryRouter } from 'react-router-dom';
5
- import type { FileTreeEntry } from '@bevel-software/platform-shared';
4
+ import { MemoryRouter, useLocation } from 'react-router-dom';
5
+ import { configureBranchModel, type FileTreeEntry } from '@bevel-software/platform-shared';
6
6
  import { FileExplorer } from '../FileExplorer';
7
- import { WorkspaceContext, type UploadError, type WorkspaceContextValue } from '../../state/workspace.context';
7
+ import {
8
+ KNOWLEDGE_UPLOAD_TARGET,
9
+ WorkspaceContext,
10
+ type UploadError,
11
+ type UploadNotice,
12
+ type UploadTarget,
13
+ type WorkspaceContextValue,
14
+ } from '../../state/workspace.context';
8
15
  import { makeWorkspaceFixture } from '../../__tests__/testFixtures';
9
16
  import { GitContext, type GitContextValue } from '../../../git/state/git.context';
10
17
  import { AuthContext, type AuthContextValue } from '../../../auth/state/auth.context';
11
18
  import { OpenChangeRequestsContext } from '../../state/open-change-requests.context';
12
-
13
- // PullRequestsForMe pulls in router/git wiring we don't want to exercise here;
14
- // stub it so the toolbar can be tested in isolation.
15
- vi.mock('../../../git/components/PullRequestsForMe', () => ({
16
- PullRequestsForMe: () => null,
17
- }));
19
+ import { AdminContext, type AdminContextValue } from '../../../admin/state/admin.context';
20
+ import { PR_STALE_EVENT } from '../../../../core/events';
18
21
 
19
22
  // authFetch is the bearer-token wrapper around window.fetch. The Download
20
23
  // click test asserts the URL + ?download=1 flag, so we mock it at the
@@ -24,6 +27,44 @@ vi.mock('../../../../lib/api', () => ({
24
27
  authFetch: (...args: unknown[]) => mockAuthFetch(...args),
25
28
  }));
26
29
 
30
+ // The author-cancel the sidebar's Withdraw reuses — the same function the
31
+ // file page's change box calls. The tree's job is to call it with the right
32
+ // request number and let the refetch take the rows away; the cancel itself
33
+ // is the pr module's.
34
+ const cancelMocks = vi.hoisted(() => ({
35
+ cancelPullRequest: vi.fn(),
36
+ deleteChangeRequest: vi.fn(),
37
+ }));
38
+ vi.mock('../../../pr/services/pr-cancel.api', () => cancelMocks);
39
+
40
+ // The sheet itself is covered by the access module's own tests; here only
41
+ // WHICH workspace and proposal the tree hands it matters.
42
+ vi.mock('../../../access/components/ManageAccessDialog', () => ({
43
+ ManageAccessDialog: (props: {
44
+ entry: FileTreeEntry;
45
+ workspaceId?: string;
46
+ proposal?: { number: number; branch: string | null };
47
+ onManageAncestor?: (entry: FileTreeEntry) => void;
48
+ }) => (
49
+ <div
50
+ data-testid="manage-access-dialog"
51
+ data-path={props.entry.relativePath}
52
+ data-workspace={props.workspaceId ?? ''}
53
+ data-proposal={JSON.stringify(props.proposal ?? null)}
54
+ >
55
+ {/* Stands in for the sheet's `Manage <folder> →` on an inherited grant. */}
56
+ <button
57
+ type="button"
58
+ onClick={() =>
59
+ props.onManageAncestor?.({ name: 'docs', relativePath: 'docs', type: 'directory', children: [] })
60
+ }
61
+ >
62
+ Manage docs →
63
+ </button>
64
+ </div>
65
+ ),
66
+ }));
67
+
27
68
  const EMPTY_TREE: FileTreeEntry = {
28
69
  name: '.',
29
70
  relativePath: '.',
@@ -31,6 +72,67 @@ const EMPTY_TREE: FileTreeEntry = {
31
72
  children: [],
32
73
  };
33
74
 
75
+ /**
76
+ * The name the deployment gives the repository checkout — `makeWorkspaceFixture`'s
77
+ * `kbDirName`, and the only child of the workspace root the explorer reads.
78
+ */
79
+ const KB_DIR = 'knowledge-base';
80
+
81
+ /**
82
+ * The fixtures that write their own workspace paths (`knowledge-base/...`)
83
+ * rather than short ones. Membership is stated by the fixture, never read off
84
+ * its shape — see `inCheckout`.
85
+ */
86
+ const CHECKOUT_ROOTED = new WeakSet<FileTreeEntry>();
87
+
88
+ /** Declare a fixture already rooted at the checkout. Returns it unchanged. */
89
+ function rootedAtCheckout(tree: FileTreeEntry): FileTreeEntry {
90
+ CHECKOUT_ROOTED.add(tree);
91
+ return tree;
92
+ }
93
+
94
+ /**
95
+ * Put a fixture's contents INSIDE the checkout, which is where the explorer
96
+ * takes its root from: the tree it is handed roots at the workspace and
97
+ * carries `<kbDirName>/` as a child, and NOTHING above that child is read.
98
+ * Every path is rewritten too, because a path is where a row lives — the
99
+ * overlays that merge pending uploads and proposed files into the tree walk
100
+ * it by path, and a short path would land them beside the checkout.
101
+ *
102
+ * Skipped only for a fixture that SAYS it already writes workspace paths, via
103
+ * `rootedAtCheckout`. It used to guess that from a child named
104
+ * `knowledge-base`, which is not something the shape can tell: a short-path
105
+ * fixture whose own top-level folder is called `knowledge-base` is the same
106
+ * data as a checkout-rooted one, so it would have been passed through,
107
+ * `atPath` would have stayed the identity, and every path the harness names
108
+ * would have been short with nothing to say so.
109
+ */
110
+ function inCheckout(tree: FileTreeEntry): FileTreeEntry {
111
+ if (CHECKOUT_ROOTED.has(tree)) return tree;
112
+ const under = (e: FileTreeEntry): FileTreeEntry => ({
113
+ ...e,
114
+ relativePath: kbPath(e.relativePath),
115
+ children: e.children?.map(under),
116
+ });
117
+ return {
118
+ ...tree,
119
+ name: '.',
120
+ relativePath: '.',
121
+ type: 'directory',
122
+ children: [
123
+ {
124
+ name: KB_DIR,
125
+ relativePath: KB_DIR,
126
+ type: 'directory',
127
+ children: (tree.children ?? []).map(under),
128
+ },
129
+ ],
130
+ };
131
+ }
132
+
133
+ /** A fixture's short path (`docs/a.md`) as the workspace holds it. */
134
+ const kbPath = (p: string): string => `${KB_DIR}/${p}`;
135
+
34
136
  function makeAuth(): AuthContextValue {
35
137
  return {
36
138
  user: null,
@@ -64,20 +166,60 @@ function makeGit(): GitContextValue {
64
166
  };
65
167
  }
66
168
 
67
-
68
169
  interface RenderOptions {
69
170
  dispatchUpload?: ReturnType<typeof vi.fn>;
70
171
  clearUploadError?: ReturnType<typeof vi.fn>;
71
172
  isUploading?: boolean;
173
+ /** Which tree the banner belongs to — the Knowledge explorer by default. */
174
+ uploadTarget?: UploadTarget;
72
175
  uploadError?: UploadError | null;
176
+ uploadNotice?: UploadNotice | null;
177
+ clearUploadNotice?: ReturnType<typeof vi.fn>;
73
178
  fileTree?: FileTreeEntry | null;
74
179
  createFile?: ReturnType<typeof vi.fn>;
75
180
  deleteEntry?: ReturnType<typeof vi.fn>;
181
+ moveEntry?: ReturnType<typeof vi.fn>;
182
+ /** The workspace id — the encoded branch name, so it decides "protected". */
183
+ workspaceId?: string;
76
184
  openFilePath?: string | null;
77
185
  /** Workspace-relative paths with an open change request. */
78
186
  openChangeRequestPaths?: string[];
79
187
  /** The caller's own open requests: workspace-relative path → CR number. */
80
188
  minePaths?: Map<string, number>;
189
+ /**
190
+ * Whether the signed-in person is an admin. Only the platform-file rows
191
+ * read it: an admin may drag a MISPLACED one back where the platform reads
192
+ * it, so the row lets that drag start and the server decides the rest.
193
+ * Omitted means no `AdminProvider` at all, which is nobody's admin.
194
+ */
195
+ isAdmin?: boolean;
196
+ /**
197
+ * Which of those requests the caller AUTHORED. Defaults to all of them,
198
+ * which is the real shape today — suggestion rows are synthesized from
199
+ * `/mine`. A test wanting an owner's view of SOMEONE ELSE'S proposal passes
200
+ * a narrower set, which is the only way to decouple the two here.
201
+ */
202
+ mineNumbers?: number[];
203
+ /**
204
+ * The files the synthesized request carries. One drop can become one
205
+ * request over several files, and withdrawing takes all of them; defaults
206
+ * to just the path the row is for.
207
+ */
208
+ crFiles?: string[];
209
+ /** The URL the tree mounts at — a reload lands on whatever the query says. */
210
+ initialEntries?: string[];
211
+ /**
212
+ * The fixture is the workspace tree EXACTLY as the API returns it — do not
213
+ * put it inside the checkout. For the trees whose point is what sits beside
214
+ * the checkout, or that there is no checkout at all.
215
+ */
216
+ verbatimTree?: boolean;
217
+ }
218
+
219
+ /** The router's current query, so a test can read what a click put there. */
220
+ function LocationProbe() {
221
+ const { search } = useLocation();
222
+ return <span data-testid="location-search">{search}</span>;
81
223
  }
82
224
 
83
225
  function renderExplorer(opts: RenderOptions = {}) {
@@ -85,37 +227,46 @@ function renderExplorer(opts: RenderOptions = {}) {
85
227
  const clearUploadError = opts.clearUploadError ?? vi.fn();
86
228
  const createFile = opts.createFile ?? vi.fn().mockResolvedValue(undefined);
87
229
  const deleteEntry = opts.deleteEntry ?? vi.fn().mockResolvedValue(undefined);
230
+ const moveEntry = opts.moveEntry ?? vi.fn().mockResolvedValue(undefined);
88
231
  // Distinguish "caller wants null tree" from "caller didn't pass anything".
89
- const fileTree = 'fileTree' in opts ? opts.fileTree ?? null : EMPTY_TREE;
232
+ const given = 'fileTree' in opts ? opts.fileTree ?? null : EMPTY_TREE;
233
+ const fileTree = given && !opts.verbatimTree ? inCheckout(given) : given;
234
+ // A fixture that was wrapped had its paths rewritten with it; the options
235
+ // that NAME paths — the open file, the caller's proposals — are in the same
236
+ // space and move with them. A fixture already rooted at the checkout writes
237
+ // its own full paths and is left alone.
238
+ const wrapped = fileTree !== null && fileTree !== given;
239
+ const atPath = (path: string) => (wrapped ? kbPath(path) : path);
240
+ const bannerTarget = opts.uploadTarget ?? KNOWLEDGE_UPLOAD_TARGET;
90
241
  const workspace: WorkspaceContextValue = makeWorkspaceFixture({
91
242
  fileTree,
92
- uploadError: opts.uploadError ?? null,
243
+ uploadErrors: opts.uploadError ? new Map([[bannerTarget, opts.uploadError]]) : new Map(),
244
+ uploadNotices: opts.uploadNotice ? new Map([[bannerTarget, opts.uploadNotice]]) : new Map(),
245
+ clearUploadNotice: opts.clearUploadNotice ?? (() => {}),
93
246
  isUploading: opts.isUploading ?? false,
94
- openFilePath: opts.openFilePath ?? null,
247
+ openFilePath: opts.openFilePath ? atPath(opts.openFilePath) : null,
95
248
  refreshFileTree: async () => fileTree,
96
249
  dispatchUpload,
97
250
  clearUploadError,
98
251
  createFile,
99
252
  deleteEntry,
253
+ moveEntry,
254
+ ...(opts.workspaceId ? { workspaceId: opts.workspaceId } : {}),
100
255
  });
101
- return {
102
- dispatchUpload,
103
- clearUploadError,
104
- createFile,
105
- deleteEntry,
106
- ...render(
107
- <MemoryRouter>
256
+ const ui = (ws: WorkspaceContextValue, mine: Map<string, number>) => (
257
+ <MemoryRouter initialEntries={opts.initialEntries ?? ['/']}>
108
258
  <AuthContext.Provider value={makeAuth()}>
109
- <WorkspaceContext.Provider value={workspace}>
259
+ <AdminContext.Provider value={{ isAdmin: opts.isAdmin === true } as AdminContextValue}>
260
+ <WorkspaceContext.Provider value={ws}>
110
261
  <GitContext.Provider value={makeGit()}>
111
262
  <OpenChangeRequestsContext.Provider
112
263
  value={{
113
- paths: new Set(opts.openChangeRequestPaths ?? []),
264
+ paths: new Set((opts.openChangeRequestPaths ?? []).map(atPath)),
114
265
  // A suggestion row resolves its request through forPath —
115
266
  // synthesize a summary for every minePaths entry so the
116
267
  // shared dialog has something to open.
117
268
  forPath: (p) => {
118
- const n = opts.minePaths?.get(p);
269
+ const n = mine.get(p);
119
270
  return n === undefined
120
271
  ? []
121
272
  : ([
@@ -126,24 +277,47 @@ function renderExplorer(opts: RenderOptions = {}) {
126
277
  base: 'main',
127
278
  state: 'open',
128
279
  createdAt: '2026-08-01T00:00:00.000Z',
129
- touchedNodePaths: [p],
280
+ touchedNodePaths: opts.crFiles?.map(atPath) ?? [p],
130
281
  author: { login: 'user-x' },
131
282
  review: { approvals: 0, changesRequested: 0, pendingLogins: [] },
132
283
  url: '',
133
284
  },
134
285
  ] as never);
135
286
  },
136
- minePaths: opts.minePaths ?? new Map(),
137
- mineNumbers: new Set(opts.minePaths?.values() ?? []),
287
+ minePaths: mine,
288
+ mineNumbers: new Set(opts.mineNumbers ?? [...mine.values()]),
138
289
  }}
139
290
  >
140
291
  <FileExplorer />
292
+ <LocationProbe />
141
293
  </OpenChangeRequestsContext.Provider>
142
294
  </GitContext.Provider>
143
295
  </WorkspaceContext.Provider>
296
+ </AdminContext.Provider>
144
297
  </AuthContext.Provider>
145
- </MemoryRouter>,
146
- ),
298
+ </MemoryRouter>
299
+ );
300
+ const minePaths = new Map([...(opts.minePaths ?? new Map<string, number>())].map(([k, n]) => [atPath(k), n]));
301
+ const result = render(ui(workspace, minePaths));
302
+ return {
303
+ moveEntry,
304
+ dispatchUpload,
305
+ clearUploadError,
306
+ createFile,
307
+ deleteEntry,
308
+ ...result,
309
+ /** Re-render the same explorer as though the user switched workspace. */
310
+ switchWorkspace: (workspaceId: string) =>
311
+ result.rerender(ui({ ...workspace, workspaceId }, minePaths)),
312
+ /**
313
+ * What the refetch behind a PR_STALE_EVENT does to a tree whose request
314
+ * is gone: `/mine` stops listing it, so its paths leave `minePaths`. The
315
+ * same mounted tree, re-rendered — never a reload.
316
+ */
317
+ requestWithdrawn: (crNumber: number) => {
318
+ const next = new Map([...minePaths].filter(([, n]) => n !== crNumber));
319
+ result.rerender(ui(workspace, next));
320
+ },
147
321
  };
148
322
  }
149
323
 
@@ -205,7 +379,9 @@ describe('FileExplorer toolbar', () => {
205
379
  expect(uploadInput.kind).toBe('files');
206
380
  expect(uploadInput.files).toHaveLength(1);
207
381
  expect(uploadInput.files[0].name).toBe('note.md');
208
- expect(dir).toBe('');
382
+ // The root row IS the checkout folder, and a write into it is addressed
383
+ // like any other folder's — not as a bare '' at the workspace root.
384
+ expect(dir).toBe(KB_DIR);
209
385
  });
210
386
 
211
387
  it('passes every file when multiple are selected at once', async () => {
@@ -279,6 +455,93 @@ describe('FileExplorer toolbar', () => {
279
455
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();
280
456
  });
281
457
 
458
+ // The reported banner: "Couldn't add knowledge-base/K…" — one truncated
459
+ // line whose reason lived in a `title` tooltip. Everything the user needs
460
+ // is in the banner now, wrapping over as many lines as it takes.
461
+ it('shows the whole reason in the banner, wrapped, with no tooltip-only text', () => {
462
+ const reason =
463
+ 'You don\u2019t have permission to write to Knowledge/Legal. '
464
+ + 'The folder is owned by the Legal group, and its access rules grant write '
465
+ + 'to that group only.';
466
+ renderExplorer({ uploadError: { filename: 'quarterly-report.pdf', reason } });
467
+ const alert = screen.getByRole('alert');
468
+ expect(alert).toHaveTextContent("Couldn't add quarterly-report.pdf");
469
+ // In full, not cut at the width of one line.
470
+ expect(alert.textContent).toContain(reason);
471
+ // Nothing is hidden behind a hover: no part of the message lives in a
472
+ // `title`, and nothing is clipped to a single line.
473
+ const titles = [...alert.querySelectorAll('[title]')].map((el) => el.getAttribute('title') ?? '');
474
+ expect(titles.some((t) => t.includes('permission'))).toBe(false);
475
+ expect(alert.querySelectorAll('.truncate')).toHaveLength(0);
476
+ expect(alert.querySelector('.whitespace-pre-wrap')).not.toBeNull();
477
+ });
478
+
479
+ // The next step comes from the STATUS, so the backend can reword its
480
+ // refusals — as it has — without the banner's advice going wrong. The
481
+ // reasons here are deliberately not the ones the old wording-matcher knew.
482
+ it('ends the error banner with what to do about it', () => {
483
+ renderExplorer({
484
+ uploadError: {
485
+ filename: 'brief.docx',
486
+ reason: 'Knowledge/Legal is owned by the Legal group; writing needs the Legal role',
487
+ status: 403,
488
+ },
489
+ });
490
+ expect(screen.getByRole('alert')).toHaveTextContent('Try another folder or ask its owner.');
491
+ cleanup();
492
+
493
+ renderExplorer({
494
+ uploadError: { filename: 'huge.bin', reason: 'File exceeds 52428800 byte limit', status: 413 },
495
+ });
496
+ expect(screen.getByRole('alert')).toHaveTextContent('try a smaller one');
497
+ cleanup();
498
+
499
+ renderExplorer({ uploadError: { filename: 'note.md', reason: 'Upstream is unreachable' } });
500
+ expect(screen.getByRole('alert')).toHaveTextContent('Try again, or pick another folder.');
501
+ });
502
+
503
+ // One shared piece of state, one banner per page: a drop into the Library's
504
+ // Skills tree must not paint its banner over the Knowledge explorer.
505
+ it('ignores banners stamped with another tree', () => {
506
+ renderExplorer({
507
+ uploadTarget: 'library:Skills',
508
+ uploadError: { filename: 'note.md', reason: 'nope' },
509
+ uploadNotice: { kind: 'suggestion', message: 'became a suggestion' },
510
+ });
511
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
512
+ expect(screen.queryByTestId('upload-notice')).not.toBeInTheDocument();
513
+ });
514
+
515
+ it('renders exactly one notice for its own tree', () => {
516
+ renderExplorer({
517
+ uploadNotice: {
518
+ kind: 'suggestion',
519
+ message: "You can't write to that folder, so the upload became a suggestion.",
520
+ },
521
+ });
522
+ const notices = screen.getAllByTestId('upload-notice');
523
+ expect(notices).toHaveLength(1);
524
+ expect(notices[0]).toHaveTextContent('became a suggestion');
525
+ });
526
+
527
+ // Nothing to dismiss about an upload that has not finished; the result
528
+ // notice that replaces it is the one the user closes.
529
+ it('offers no dismiss on the in-progress notice and one on the result', async () => {
530
+ const user = userEvent.setup();
531
+ renderExplorer({ uploadNotice: { kind: 'progress', message: 'Adding report.pdf to Ops…' } });
532
+ expect(screen.getByTestId('upload-notice')).toHaveTextContent('Adding report.pdf to Ops');
533
+ expect(screen.queryByRole('button', { name: /Dismiss upload notice/i })).not.toBeInTheDocument();
534
+ cleanup();
535
+
536
+ const clearUploadNotice = vi.fn();
537
+ renderExplorer({
538
+ uploadNotice: { kind: 'suggestion', message: 'became a suggestion' },
539
+ clearUploadNotice,
540
+ });
541
+ await user.click(screen.getByRole('button', { name: /Dismiss upload notice/i }));
542
+ expect(clearUploadNotice).toHaveBeenCalledTimes(1);
543
+ });
544
+
282
545
  it('routes root-level drag-and-drop through dispatchUpload (parity with the button)', async () => {
283
546
  const dispatchUpload = vi.fn().mockResolvedValue(undefined);
284
547
  renderExplorer({ dispatchUpload });
@@ -298,7 +561,10 @@ describe('FileExplorer toolbar', () => {
298
561
  const [uploadInput, dir] = dispatchUpload.mock.calls[0];
299
562
  expect(uploadInput.kind).toBe('files');
300
563
  expect(uploadInput.files[0].name).toBe('dropped.md');
301
- expect(dir).toBe('');
564
+ // The tree's background is the tree's ROOT. It used to send an empty
565
+ // target, which is the workspace directory — the file landed BESIDE the
566
+ // checkout, where this sidebar can never show it again.
567
+ expect(dir).toBe(KB_DIR);
302
568
  });
303
569
 
304
570
  it('renders the loading placeholder when fileTree is null', async () => {
@@ -336,71 +602,287 @@ describe('FileExplorer right-click: Download menu (per-path access)', () => {
336
602
  ],
337
603
  };
338
604
 
605
+ /** The `/access` body, with only the verdict this menu reads varying. */
606
+ function accessBody(canDownload: boolean) {
607
+ return {
608
+ canRead: true,
609
+ canWrite: true,
610
+ canDownload,
611
+ canOwner: false,
612
+ eligible: { roles: [], users: [] },
613
+ readers: { restricted: false, roles: [], users: [] },
614
+ owners: { roles: [], users: [] },
615
+ downloaders: { roles: [], users: [] },
616
+ sources: {},
617
+ };
618
+ }
619
+
620
+ /**
621
+ * One `authFetch` for two very different calls: the menu's access preflight
622
+ * on open, and the download itself on click. Routed by URL so a test can
623
+ * state the verdict and the download outcome independently — which is the
624
+ * whole point of the late-403 case, where they disagree.
625
+ */
626
+ function routeAuthFetch(opts: { canDownload: boolean; download?: unknown }) {
627
+ mockAuthFetch.mockImplementation((url: string) =>
628
+ Promise.resolve(
629
+ url.includes('/access?')
630
+ ? { ok: true, status: 200, json: async () => accessBody(opts.canDownload), text: async () => '' }
631
+ : opts.download,
632
+ ),
633
+ );
634
+ }
635
+
636
+ /** The access lookups made so far, in order. */
637
+ const accessCalls = () =>
638
+ mockAuthFetch.mock.calls.map((c) => c[0] as string).filter((u) => u.includes('/access?'));
639
+ /** The download requests made so far — everything that is not a lookup. */
640
+ const downloadCalls = () =>
641
+ mockAuthFetch.mock.calls.map((c) => c[0] as string).filter((u) => !u.includes('/access?'));
642
+
643
+ /**
644
+ * The blob-URL pair the download path uses. `Object.assign` rather than a
645
+ * cast: happy-dom's URL has no object-URL methods to widen, and the cast
646
+ * every caller used to write is the one thing a helper should absorb.
647
+ */
648
+ function stubObjectUrls(url = 'blob:fake-url') {
649
+ const createObjectURL = vi.fn(() => url);
650
+ const revokeObjectURL = vi.fn();
651
+ Object.assign(globalThis.URL, { createObjectURL, revokeObjectURL });
652
+ return { createObjectURL, revokeObjectURL };
653
+ }
654
+
339
655
  function renderWithTree() {
340
656
  return renderExplorer({ fileTree: TREE_WITH_BOTH });
341
657
  }
342
658
 
343
- // Under the path-scoped `download:` verb model there is no global
344
- // preflight: the menu items always render. The backend returns 403 at
345
- // click time for users without permission on that specific path; the
346
- // click handler surfaces it via an alert.
659
+ /** Right-click a row and wait for the menu's access lookup to land. */
660
+ async function openMenuOn(label: string) {
661
+ fireEvent.contextMenu(screen.getByText(label));
662
+ await act(async () => {});
663
+ }
664
+
665
+ it('asks for the entry access once when the menu opens, and enables Download', async () => {
666
+ routeAuthFetch({ canDownload: true });
667
+ renderWithTree();
668
+ await openMenuOn('brief.md');
669
+
670
+ expect(accessCalls()).toHaveLength(1);
671
+ expect(accessCalls()[0]).toContain(`/api/workspace/ws-1/access?path=${encodeURIComponent(kbPath('brief.md'))}`);
672
+ expect(accessCalls()[0]).toContain('kind=file');
673
+ const item = screen.getByRole('menuitem', { name: 'Download' });
674
+ expect(item).not.toHaveAttribute('aria-disabled');
675
+ expect(item).not.toHaveAttribute('title');
676
+ });
677
+
678
+ it('disables Download with the reason on a file the caller may only read', async () => {
679
+ routeAuthFetch({ canDownload: false });
680
+ renderWithTree();
681
+ await openMenuOn('brief.md');
682
+
683
+ const item = screen.getByRole('menuitem', { name: 'Download' });
684
+ expect(item).toHaveAttribute('aria-disabled', 'true');
685
+ expect(item).toHaveAttribute('title', "You don't have download permission for this item");
686
+ // Nothing is attempted on a click, and the menu stays open saying why.
687
+ fireEvent.click(item);
688
+ expect(downloadCalls()).toHaveLength(0);
689
+ expect(screen.getByRole('menuitem', { name: 'Download' })).toBeInTheDocument();
690
+ });
691
+
692
+ it('disables Download as zip with the reason on a folder, asked as a folder', async () => {
693
+ routeAuthFetch({ canDownload: false });
694
+ renderWithTree();
695
+ await openMenuOn('reports');
696
+
697
+ expect(accessCalls()).toHaveLength(1);
698
+ expect(accessCalls()[0]).toContain(`path=${encodeURIComponent(kbPath('reports'))}`);
699
+ expect(accessCalls()[0]).toContain('kind=folder');
700
+ const item = screen.getByRole('menuitem', { name: 'Download as zip' });
701
+ expect(item).toHaveAttribute('aria-disabled', 'true');
702
+ expect(item).toHaveAttribute('title', "You don't have download permission for this item");
703
+ fireEvent.click(item);
704
+ expect(downloadCalls()).toHaveLength(0);
705
+ });
706
+
707
+ /**
708
+ * `aria-disabled`, not `disabled`, is what keeps the reason reachable — so
709
+ * the item is still focusable, and refusing the ACTIVATION (not the click
710
+ * event) is what has to stop the keyboard path.
711
+ */
712
+ it('cannot be triggered from the keyboard while it is disabled', async () => {
713
+ const user = userEvent.setup();
714
+ routeAuthFetch({ canDownload: false });
715
+ renderWithTree();
716
+ await openMenuOn('brief.md');
717
+
718
+ const item = screen.getByRole('menuitem', { name: 'Download' });
719
+ item.focus();
720
+ expect(document.activeElement).toBe(item);
721
+ await user.keyboard('{Enter}');
722
+ await user.keyboard(' ');
723
+ expect(downloadCalls()).toHaveLength(0);
724
+ // The menu did not close either: nothing happened at all.
725
+ expect(screen.getByRole('menuitem', { name: 'Download' })).toBeInTheDocument();
726
+ });
727
+
728
+ // The control for the test above: the same keys DO activate the item when
729
+ // the verdict allows it, so the refusal above is the guard working and not
730
+ // a menu that simply cannot be driven from the keyboard.
731
+ it('activates Download from the keyboard when the verdict allows it', async () => {
732
+ const user = userEvent.setup();
733
+ routeAuthFetch({
734
+ canDownload: true,
735
+ download: { ok: true, status: 200, blob: async () => new Blob(['bytes']), text: async () => '' },
736
+ });
737
+ stubObjectUrls();
738
+ renderWithTree();
739
+ await openMenuOn('brief.md');
740
+
741
+ screen.getByRole('menuitem', { name: 'Download' }).focus();
742
+ await act(async () => {
743
+ await user.keyboard('{Enter}');
744
+ });
745
+ expect(downloadCalls()).toHaveLength(1);
746
+ });
347
747
 
348
- it('shows Download on files (no preflight gate)', () => {
748
+ it('leaves Download enabled while the lookup is still in flight', async () => {
749
+ // Never resolves: the verdict is unknown for the whole test.
750
+ mockAuthFetch.mockImplementation(() => new Promise(() => {}));
349
751
  renderWithTree();
350
752
  fireEvent.contextMenu(screen.getByText('brief.md'));
351
- expect(screen.getByText('Download')).toBeInTheDocument();
753
+
754
+ const item = screen.getByRole('menuitem', { name: 'Download' });
755
+ expect(item).not.toHaveAttribute('aria-disabled');
352
756
  });
353
757
 
354
- it('shows Download as zip on folders (no preflight gate)', () => {
758
+ it('leaves Download enabled when the lookup itself fails', async () => {
759
+ mockAuthFetch.mockImplementation((url: string) =>
760
+ url.includes('/access?')
761
+ ? Promise.resolve({ ok: false, status: 500, json: async () => ({ error: 'boom' }), text: async () => 'boom' })
762
+ : Promise.resolve({ ok: true, status: 200, blob: async () => new Blob(['b']), text: async () => '' }),
763
+ );
355
764
  renderWithTree();
356
- fireEvent.contextMenu(screen.getByText('reports'));
357
- expect(screen.getByText('Download as zip')).toBeInTheDocument();
765
+ await openMenuOn('brief.md');
766
+
767
+ expect(screen.getByRole('menuitem', { name: 'Download' })).not.toHaveAttribute('aria-disabled');
358
768
  });
359
769
 
360
- it('surfaces a 403 from the backend as an alert when the user lacks download on the clicked path', async () => {
361
- mockAuthFetch.mockResolvedValue({
362
- ok: false,
363
- status: 403,
364
- text: async () => '{"error":"Download permission required"}',
770
+ /**
771
+ * The late 403 — permission changed between the menu opening and the click.
772
+ * It is reported where the row is, never through `window.alert`: a modal
773
+ * popup for a refused download stops the whole app to say one line.
774
+ */
775
+ it('shows an inline notice, not an alert, when a download is refused after the menu opened', async () => {
776
+ routeAuthFetch({
777
+ canDownload: true,
778
+ download: { ok: false, status: 403, text: async () => '{"error":"Download permission required"}' },
365
779
  });
366
780
  const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
367
781
  try {
368
782
  renderWithTree();
369
- fireEvent.contextMenu(screen.getByText('brief.md'));
783
+ await openMenuOn('brief.md');
370
784
  await act(async () => {
371
- fireEvent.click(screen.getByText('Download'));
785
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }));
372
786
  });
373
- expect(alertSpy).toHaveBeenCalledTimes(1);
374
- const msg = alertSpy.mock.calls[0][0] as string;
375
- expect(msg).toContain('brief.md');
376
- expect(msg).toContain('403');
787
+
788
+ expect(alertSpy).not.toHaveBeenCalled();
789
+ const notice = await screen.findByTestId('tree-download-error');
790
+ expect(notice).toHaveAttribute('role', 'alert');
791
+ expect(notice.textContent).toContain('brief.md');
792
+ expect(notice.textContent).toContain("You don't have download permission for this item");
793
+
794
+ // Dismissible, like every other banner in this tree.
795
+ fireEvent.click(screen.getByRole('button', { name: /Dismiss download error/i }));
796
+ expect(screen.queryByTestId('tree-download-error')).toBeNull();
797
+ } finally {
798
+ alertSpy.mockRestore();
799
+ }
800
+ });
801
+
802
+ it('reports a non-403 download failure inline too', async () => {
803
+ routeAuthFetch({
804
+ canDownload: true,
805
+ download: { ok: false, status: 500, text: async () => 'boom' },
806
+ });
807
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
808
+ try {
809
+ renderWithTree();
810
+ await openMenuOn('brief.md');
811
+ await act(async () => {
812
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }));
813
+ });
814
+ expect(alertSpy).not.toHaveBeenCalled();
815
+ const notice = await screen.findByTestId('tree-download-error');
816
+ expect(notice.textContent).toContain('500');
377
817
  } finally {
378
818
  alertSpy.mockRestore();
379
819
  }
380
820
  });
381
821
 
822
+ /**
823
+ * Two downloads for the same row can overlap — the menu closes on click but
824
+ * the ROW does not, so a second Download is one reopen away — and the two
825
+ * can land out of order. The notice speaks for the LATEST attempt only:
826
+ * a slow refusal arriving after a fast success would otherwise report a
827
+ * failed download the user had just watched succeed.
828
+ */
829
+ it('ignores a superseded download outcome instead of reporting a stale failure', async () => {
830
+ let releaseRefusal: () => void = () => {};
831
+ const slowRefusal = new Promise<unknown>((resolve) => {
832
+ releaseRefusal = () =>
833
+ resolve({ ok: false, status: 403, text: async () => '{"error":"Download permission required"}' });
834
+ });
835
+ let downloadsSeen = 0;
836
+ mockAuthFetch.mockImplementation((url: string) => {
837
+ if (url.includes('/access?')) {
838
+ return Promise.resolve({ ok: true, status: 200, json: async () => accessBody(true), text: async () => '' });
839
+ }
840
+ downloadsSeen += 1;
841
+ // First click hangs, second answers at once — the out-of-order case.
842
+ return downloadsSeen === 1
843
+ ? slowRefusal
844
+ : Promise.resolve({ ok: true, status: 200, blob: async () => new Blob(['bytes']), text: async () => '' });
845
+ });
846
+ stubObjectUrls();
847
+
848
+ renderWithTree();
849
+ await openMenuOn('brief.md');
850
+ await act(async () => {
851
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }));
852
+ });
853
+ // Reopen and click again while the first attempt is still in flight.
854
+ await openMenuOn('brief.md');
855
+ await act(async () => {
856
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }));
857
+ });
858
+ expect(downloadCalls()).toHaveLength(2);
859
+ expect(screen.queryByTestId('tree-download-error')).toBeNull();
860
+
861
+ // The stale refusal lands last. It belongs to a download two clicks ago.
862
+ await act(async () => {
863
+ releaseRefusal();
864
+ await slowRefusal;
865
+ });
866
+ expect(screen.queryByTestId('tree-download-error')).toBeNull();
867
+ });
868
+
382
869
  it('calls /file/raw?download=1 with the entry path and saves the blob', async () => {
383
- mockAuthFetch.mockResolvedValue({
384
- ok: true,
385
- status: 200,
386
- blob: async () => new Blob(['bytes']),
387
- text: async () => '',
870
+ routeAuthFetch({
871
+ canDownload: true,
872
+ download: { ok: true, status: 200, blob: async () => new Blob(['bytes']), text: async () => '' },
388
873
  });
389
- const createObjectURL = vi.fn(() => 'blob:fake-url');
390
- const revokeObjectURL = vi.fn();
391
- (globalThis.URL as any).createObjectURL = createObjectURL;
392
- (globalThis.URL as any).revokeObjectURL = revokeObjectURL;
874
+ const { createObjectURL, revokeObjectURL } = stubObjectUrls();
393
875
 
394
876
  renderWithTree();
395
- fireEvent.contextMenu(screen.getByText('brief.md'));
877
+ await openMenuOn('brief.md');
396
878
  await act(async () => {
397
- fireEvent.click(screen.getByText('Download'));
879
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }));
398
880
  });
399
881
 
400
- expect(mockAuthFetch).toHaveBeenCalledTimes(1);
401
- const url = mockAuthFetch.mock.calls[0][0] as string;
882
+ expect(downloadCalls()).toHaveLength(1);
883
+ const url = downloadCalls()[0];
402
884
  expect(url).toContain('/api/workspace/ws-1/file/raw');
403
- expect(url).toContain('path=brief.md');
885
+ expect(url).toContain(`path=${encodeURIComponent(kbPath('brief.md'))}`);
404
886
  expect(url).toContain('download=1');
405
887
  expect(createObjectURL).toHaveBeenCalled();
406
888
  // The revoke is DEFERRED a tick (setTimeout 0) so the click's download
@@ -409,16 +891,11 @@ describe('FileExplorer right-click: Download menu (per-path access)', () => {
409
891
  });
410
892
 
411
893
  it('calls /folder/zip?download=1 and triggers a <folder>.zip save when clicking Download as zip on a folder', async () => {
412
- mockAuthFetch.mockResolvedValue({
413
- ok: true,
414
- status: 200,
415
- blob: async () => new Blob(['PK', 'bytes']),
416
- text: async () => '',
894
+ routeAuthFetch({
895
+ canDownload: true,
896
+ download: { ok: true, status: 200, blob: async () => new Blob(['PK', 'bytes']), text: async () => '' },
417
897
  });
418
- const createObjectURL = vi.fn(() => 'blob:fake-zip-url');
419
- const revokeObjectURL = vi.fn();
420
- (globalThis.URL as any).createObjectURL = createObjectURL;
421
- (globalThis.URL as any).revokeObjectURL = revokeObjectURL;
898
+ stubObjectUrls('blob:fake-zip-url');
422
899
 
423
900
  // Spy on anchor `.download` to confirm we save as <folder>.zip.
424
901
  const anchorDownloadValues: string[] = [];
@@ -440,15 +917,15 @@ describe('FileExplorer right-click: Download menu (per-path access)', () => {
440
917
  // level and contaminates later tests.
441
918
  try {
442
919
  renderWithTree();
443
- fireEvent.contextMenu(screen.getByText('reports'));
920
+ await openMenuOn('reports');
444
921
  await act(async () => {
445
- fireEvent.click(screen.getByText('Download as zip'));
922
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download as zip' }));
446
923
  });
447
924
 
448
- expect(mockAuthFetch).toHaveBeenCalledTimes(1);
449
- const url = mockAuthFetch.mock.calls[0][0] as string;
925
+ expect(downloadCalls()).toHaveLength(1);
926
+ const url = downloadCalls()[0];
450
927
  expect(url).toContain('/api/workspace/ws-1/folder/zip');
451
- expect(url).toContain('path=reports');
928
+ expect(url).toContain(`path=${encodeURIComponent(kbPath('reports'))}`);
452
929
  expect(url).toContain('download=1');
453
930
  expect(anchorDownloadValues).toContain('reports.zip');
454
931
  } finally {
@@ -493,7 +970,10 @@ describe('FileExplorer chevron collapse: userIntent vs autoExpanded', () => {
493
970
  openFilePath: string | null;
494
971
  fileTree: FileTreeEntry;
495
972
  }) {
496
- const workspace = makeWorkspaceFixture({ fileTree, openFilePath });
973
+ const workspace = makeWorkspaceFixture({
974
+ fileTree: inCheckout(fileTree),
975
+ openFilePath: openFilePath && kbPath(openFilePath),
976
+ });
497
977
  return (
498
978
  <MemoryRouter>
499
979
  <AuthContext.Provider value={makeAuth()}>
@@ -770,16 +1250,97 @@ describe('FileExplorer rows: the prototype tree', () => {
770
1250
  expect(row.querySelectorAll('svg')).toHaveLength(0);
771
1251
  });
772
1252
 
773
- it('gives a childless folder no caret and does not toggle it', async () => {
1253
+ it('gives a childless folder the caret, like any folder', () => {
774
1254
  renderExplorer({ fileTree: TREE });
1255
+ // Without the caret an empty folder reads as a file.
775
1256
  const empty = screen.getByText('reports').closest('button')!;
776
- expect(empty.querySelectorAll('svg')).toHaveLength(0);
1257
+ expect(empty.querySelectorAll('svg')).toHaveLength(1);
777
1258
  expect(empty).toHaveAttribute('aria-expanded');
778
1259
 
779
1260
  const withKids = screen.getByText('docs').closest('button')!;
780
1261
  expect(withKids.querySelectorAll('svg')).toHaveLength(1);
781
1262
  });
782
1263
 
1264
+ it('shows one muted, inert "Empty" row under an open empty folder', () => {
1265
+ const tree: FileTreeEntry = {
1266
+ name: '.',
1267
+ relativePath: '.',
1268
+ type: 'directory',
1269
+ children: [
1270
+ {
1271
+ name: 'outer',
1272
+ relativePath: 'outer',
1273
+ type: 'directory',
1274
+ children: [{ name: 'reports', relativePath: 'outer/reports', type: 'directory', children: [] }],
1275
+ },
1276
+ ],
1277
+ };
1278
+ renderExplorer({ fileTree: tree });
1279
+ // Depth 2 starts closed, so nothing says "Empty" until it is opened.
1280
+ const reports = screen.getByText('reports').closest('button')!;
1281
+ expect(reports).toHaveAttribute('aria-expanded', 'false');
1282
+ expect(screen.queryByText('Empty')).not.toBeInTheDocument();
1283
+
1284
+ fireEvent.click(reports);
1285
+ expect(reports).toHaveAttribute('aria-expanded', 'true');
1286
+ const emptyRows = screen.getAllByText('Empty');
1287
+ expect(emptyRows).toHaveLength(1);
1288
+ const emptyRow = emptyRows[0].closest('[data-tree-empty]') as HTMLElement;
1289
+ expect(emptyRow).toHaveClass('text-ink-faint');
1290
+ // A statement, not a row: no controls, no path, nothing to focus.
1291
+ expect(emptyRow.querySelector('button, [tabindex], svg')).toBeNull();
1292
+ expect(emptyRow).not.toHaveAttribute('data-tree-path');
1293
+ // One indent step deeper than the folder, where a first child would sit.
1294
+ expect(emptyRow.style.paddingLeft).toBe(`${parseInt(reports.parentElement!.style.paddingLeft) + 13}px`);
1295
+
1296
+ fireEvent.click(reports);
1297
+ expect(screen.queryByText('Empty')).not.toBeInTheDocument();
1298
+ });
1299
+
1300
+ it('truncates a long file name in the middle, keeping its last 8 characters', () => {
1301
+ const name = 'Sidebar-Rows-Say-What-They-Are.md';
1302
+ const tree: FileTreeEntry = {
1303
+ name: '.',
1304
+ relativePath: '.',
1305
+ type: 'directory',
1306
+ children: [{ name, relativePath: name, type: 'file' }],
1307
+ };
1308
+ renderExplorer({ fileTree: tree });
1309
+ const row = screen.getByRole('button', { name });
1310
+ const lead = row.querySelector('[data-name-lead]')!;
1311
+ const tail = row.querySelector('[data-name-tail]')!;
1312
+ // The lead is what shrinks behind an ellipsis; the tail never does.
1313
+ expect(lead.textContent).toBe('Sidebar-Rows-Say-What-The');
1314
+ expect(lead).toHaveClass('truncate');
1315
+ expect(tail.textContent).toBe('y-Are.md');
1316
+ expect(tail).toHaveClass('flex-none');
1317
+ expect(tail).not.toHaveClass('truncate');
1318
+ // Together they are the whole name, so a name that fits is unchanged.
1319
+ expect(`${lead.textContent}${tail.textContent}`).toBe(name);
1320
+ });
1321
+
1322
+ it('renders a short file name whole, in one piece', () => {
1323
+ renderExplorer({ fileTree: TREE });
1324
+ const name = screen.getByText('brief.md');
1325
+ expect(name.tagName).toBe('SPAN');
1326
+ expect(name).toHaveClass('truncate');
1327
+ expect(name.closest('button')!.querySelector('[data-name-tail]')).toBeNull();
1328
+ });
1329
+
1330
+ it('keeps end truncation for a folder name — no extension to protect', () => {
1331
+ const folder = 'a-very-long-folder-name-that-will-not-fit';
1332
+ const tree: FileTreeEntry = {
1333
+ name: '.',
1334
+ relativePath: '.',
1335
+ type: 'directory',
1336
+ children: [{ name: folder, relativePath: folder, type: 'directory', children: [] }],
1337
+ };
1338
+ renderExplorer({ fileTree: tree });
1339
+ const name = screen.getByText(folder);
1340
+ expect(name).toHaveClass('truncate');
1341
+ expect(name.closest('button')!.querySelector('[data-name-tail]')).toBeNull();
1342
+ });
1343
+
783
1344
  it('marks directory rows with aria-expanded and the open file with aria-current', () => {
784
1345
  renderExplorer({ fileTree: TREE, openFilePath: 'docs/a.md' });
785
1346
  expect(screen.getByText('docs').closest('button')).toHaveAttribute('aria-expanded', 'true');
@@ -788,7 +1349,9 @@ describe('FileExplorer rows: the prototype tree', () => {
788
1349
  });
789
1350
 
790
1351
  // The one prototype context-menu item the platform never had.
791
- it('offers Copy path in the context menu and writes the entry path', async () => {
1352
+ // Root-anchored, so the text pasted into a Markdown link opens the file from
1353
+ // any folder rather than resolving against the linking file's own folder.
1354
+ it('offers Copy path in the context menu and writes the root-anchored entry path', async () => {
792
1355
  const writeText = vi.fn(async () => {});
793
1356
  Object.defineProperty(navigator, 'clipboard', {
794
1357
  value: { writeText },
@@ -800,7 +1363,33 @@ describe('FileExplorer rows: the prototype tree', () => {
800
1363
  await act(async () => {
801
1364
  fireEvent.click(screen.getByRole('menuitem', { name: /Copy path/i }));
802
1365
  });
803
- expect(writeText).toHaveBeenCalledWith('brief.md');
1366
+ expect(writeText).toHaveBeenCalledWith(`/${kbPath('brief.md')}`);
1367
+ });
1368
+
1369
+ it('copies a nested entry as its full root-anchored path', async () => {
1370
+ const writeText = vi.fn(async () => {});
1371
+ Object.defineProperty(navigator, 'clipboard', {
1372
+ value: { writeText },
1373
+ configurable: true,
1374
+ });
1375
+ renderExplorer({ fileTree: TREE });
1376
+
1377
+ fireEvent.contextMenu(screen.getByText('a.md'));
1378
+ await act(async () => {
1379
+ fireEvent.click(screen.getByRole('menuitem', { name: /Copy path/i }));
1380
+ });
1381
+ expect(writeText).toHaveBeenCalledWith(`/${kbPath('docs/a.md')}`);
1382
+ });
1383
+
1384
+ // The root row is the CHECKOUT folder — copying its path hands over the
1385
+ // repository, which is not a destination anything links to.
1386
+ it('does not offer Copy path on the tree\'s root row', () => {
1387
+ renderExplorer({ fileTree: TREE });
1388
+ fireEvent.contextMenu(screen.getByText('reports'));
1389
+ expect(screen.getByRole('menuitem', { name: /Copy path/i })).toBeInTheDocument();
1390
+ fireEvent.keyDown(document, { key: 'Escape' });
1391
+ fireEvent.contextMenu(screen.getAllByText(KB_DIR)[0]);
1392
+ expect(screen.queryByRole('menuitem', { name: /Copy path/i })).not.toBeInTheDocument();
804
1393
  });
805
1394
 
806
1395
  it('offers Copy path on a folder row too', () => {
@@ -835,14 +1424,18 @@ describe('FileExplorer rows: the prototype tree', () => {
835
1424
  expect(screen.queryByRole('menu')).not.toBeInTheDocument();
836
1425
  });
837
1426
 
838
- it('still deletes from the context menu', async () => {
1427
+ it('still deletes from the context menu, once confirmed', async () => {
839
1428
  const deleteEntry = vi.fn(async () => {});
840
1429
  renderExplorer({ fileTree: TREE, deleteEntry });
841
1430
  fireEvent.contextMenu(screen.getByText('brief.md'));
842
1431
  await act(async () => {
843
1432
  fireEvent.click(screen.getByRole('menuitem', { name: /Delete/i }));
844
1433
  });
845
- expect(deleteEntry).toHaveBeenCalledWith('brief.md');
1434
+ expect(deleteEntry).not.toHaveBeenCalled();
1435
+ await act(async () => {
1436
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
1437
+ });
1438
+ expect(deleteEntry).toHaveBeenCalledWith(kbPath('brief.md'));
846
1439
  });
847
1440
 
848
1441
  // WP6: the tree consumes the SHARED, workspace-relative set. The two path
@@ -919,53 +1512,308 @@ describe('FileExplorer rows: the prototype tree', () => {
919
1512
  fireEvent.click(row);
920
1513
  expect(screen.queryByRole('dialog')).toBeNull();
921
1514
  });
922
- });
923
1515
 
924
- // ── The right-click menu has to land on screen ──
925
- //
926
- // The panel is `position: fixed`, so whatever falls past the bottom edge of
927
- // the window is unreachable: the page will not scroll to a fixed box, and the
928
- // wheel scrolls the tree out from under a menu that stays where it was. A
929
- // folder's menu is nine rows, so pinning it to the raw pointer put `Manage
930
- // access`, `Rename` and `Delete` below the fold for any right-click in the
931
- // lower quarter of the sidebar.
932
- /** jsdom's own viewport, read at import before any test has stubbed it. */
933
- const REAL_VIEWPORT = { width: window.innerWidth, height: window.innerHeight };
934
-
935
- describe('FileExplorer right-click: the menu stays inside the window', () => {
936
- const TREE: FileTreeEntry = {
937
- name: '.',
938
- relativePath: '.',
939
- type: 'directory',
940
- children: [
941
- { name: 'reports', relativePath: 'reports', type: 'directory', children: [] },
942
- { name: 'brief.md', relativePath: 'brief.md', type: 'file' },
943
- ],
944
- };
1516
+ /**
1517
+ * A proposed-only file's access lives where the file does: on the change
1518
+ * request's branch. Its right-click offers Manage access, and the sheet is
1519
+ * handed that request — never the viewed branch, where the file is absent.
1520
+ */
1521
+ it('opens Manage access on a proposed-only file against its change request', () => {
1522
+ renderExplorer({
1523
+ fileTree: TREE,
1524
+ minePaths: new Map([['docs/new-idea.md', 12]]),
1525
+ });
945
1526
 
946
- const MENU_W = 200;
947
- const MENU_H = 300;
1527
+ const row = screen.getByTitle('Proposed by you: opens the change request').closest('button')!;
1528
+ fireEvent.contextMenu(row, { clientX: 40, clientY: 40 });
948
1529
 
949
- // jsdom lays nothing out, so every `offsetWidth`/`offsetHeight` is 0 and the
950
- // placement would have nothing to react to. Give a size to the one element
951
- // the hook measures: the fixed wrapper, identified by the `role="menu"`
952
- // panel it holds.
953
- const isMenuBox = (el: HTMLElement) => el.firstElementChild?.getAttribute('role') === 'menu';
954
- let restoreLayout: (() => void) | null = null;
1530
+ // Only what applies to a file this branch does not have.
1531
+ expect(screen.queryByRole('menuitem', { name: /Rename/i })).toBeNull();
1532
+ expect(screen.queryByRole('menuitem', { name: /Delete/i })).toBeNull();
1533
+ expect(screen.queryByRole('menuitem', { name: /Download/i })).toBeNull();
1534
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
955
1535
 
956
- function stubViewport(width: number, height: number) {
957
- const w = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth')!;
958
- const h = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')!;
959
- // jsdom defines these as own accessors on `window`, so the descriptor is
960
- // real and putting it back restores the getter rather than freezing a
961
- // number in its place.
962
- const iw = Object.getOwnPropertyDescriptor(window, 'innerWidth')!;
963
- const ih = Object.getOwnPropertyDescriptor(window, 'innerHeight')!;
964
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
965
- configurable: true,
966
- get(this: HTMLElement) {
967
- return isMenuBox(this) ? MENU_W : 0;
968
- },
1536
+ const dialog = screen.getByTestId('manage-access-dialog');
1537
+ expect(dialog.dataset.path).toBe(kbPath('docs/new-idea.md'));
1538
+ expect(JSON.parse(dialog.dataset.proposal!)).toEqual({
1539
+ number: 12,
1540
+ branch: 'suggestions/me/knowledge',
1541
+ });
1542
+ });
1543
+
1544
+ it('keeps an existing file on the viewed branch even when my request modifies it', () => {
1545
+ renderExplorer({
1546
+ fileTree: TREE,
1547
+ minePaths: new Map([['brief.md', 12]]),
1548
+ });
1549
+
1550
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 40, clientY: 40 });
1551
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
1552
+
1553
+ const dialog = screen.getByTestId('manage-access-dialog');
1554
+ expect(dialog.dataset.path).toBe(kbPath('brief.md'));
1555
+ // No proposal, no pinned workspace: the ambient branch, exactly as before.
1556
+ expect(JSON.parse(dialog.dataset.proposal!)).toBeNull();
1557
+ expect(dialog.dataset.workspace).toBe('');
1558
+ });
1559
+
1560
+ /**
1561
+ * An inherited grant on a proposed file was read on the request's branch, so
1562
+ * following it to the folder keeps editing there — the folder path alone
1563
+ * would resolve to the viewed branch.
1564
+ */
1565
+ it('keeps the change request when a proposed file retargets to its folder', () => {
1566
+ renderExplorer({
1567
+ fileTree: TREE,
1568
+ minePaths: new Map([['docs/new-idea.md', 12]]),
1569
+ });
1570
+
1571
+ const row = screen.getByTitle('Proposed by you: opens the change request').closest('button')!;
1572
+ fireEvent.contextMenu(row, { clientX: 40, clientY: 40 });
1573
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
1574
+ fireEvent.click(screen.getByRole('button', { name: 'Manage docs →' }));
1575
+
1576
+ const dialog = screen.getByTestId('manage-access-dialog');
1577
+ expect(dialog.dataset.path).toBe('docs');
1578
+ expect(JSON.parse(dialog.dataset.proposal!)).toEqual({
1579
+ number: 12,
1580
+ branch: 'suggestions/me/knowledge',
1581
+ });
1582
+ });
1583
+
1584
+ it('retargets an ordinary file to its folder on the viewed branch', () => {
1585
+ renderExplorer({ fileTree: TREE });
1586
+
1587
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 40, clientY: 40 });
1588
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
1589
+ fireEvent.click(screen.getByRole('button', { name: 'Manage docs →' }));
1590
+
1591
+ const dialog = screen.getByTestId('manage-access-dialog');
1592
+ expect(dialog.dataset.path).toBe('docs');
1593
+ expect(JSON.parse(dialog.dataset.proposal!)).toBeNull();
1594
+ });
1595
+
1596
+ it('forgets a retargeted change request on the next right-click', () => {
1597
+ renderExplorer({
1598
+ fileTree: TREE,
1599
+ minePaths: new Map([['docs/new-idea.md', 12]]),
1600
+ });
1601
+
1602
+ const row = screen.getByTitle('Proposed by you: opens the change request').closest('button')!;
1603
+ fireEvent.contextMenu(row, { clientX: 40, clientY: 40 });
1604
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
1605
+ fireEvent.click(screen.getByRole('button', { name: 'Manage docs →' }));
1606
+
1607
+ // A fresh right-click on an ordinary file is a new sheet on the viewed branch.
1608
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 40, clientY: 40 });
1609
+ fireEvent.click(screen.getByRole('menuitem', { name: /Manage access/i }));
1610
+
1611
+ const dialog = screen.getByTestId('manage-access-dialog');
1612
+ expect(dialog.dataset.path).toBe(kbPath('brief.md'));
1613
+ expect(JSON.parse(dialog.dataset.proposal!)).toBeNull();
1614
+ });
1615
+ });
1616
+
1617
+ // ── Taking a suggestion back from the row that shows it ──
1618
+ //
1619
+ // Withdraw already existed — on the file page's change box, and in the
1620
+ // change-request dialog. Neither is where the accent-coloured row leads, and
1621
+ // the notice that announced the suggestion said nothing about undoing it, so
1622
+ // the reporter concluded an accidental upload was permanent. The row's
1623
+ // right-click menu is where the user looks; this is that menu.
1624
+ describe('FileExplorer: withdrawing my own suggestion from its row', () => {
1625
+ const TREE: FileTreeEntry = {
1626
+ name: '.',
1627
+ relativePath: '.',
1628
+ type: 'directory',
1629
+ children: [
1630
+ {
1631
+ name: 'docs',
1632
+ relativePath: 'docs',
1633
+ type: 'directory',
1634
+ children: [{ name: 'a.md', relativePath: 'docs/a.md', type: 'file' }],
1635
+ },
1636
+ { name: 'brief.md', relativePath: 'brief.md', type: 'file' },
1637
+ ],
1638
+ };
1639
+ const PROPOSED = 'docs/new-idea.md';
1640
+ const proposedRow = () =>
1641
+ screen.getByTitle('Proposed by you: opens the change request').closest('button')!;
1642
+
1643
+ beforeEach(() => {
1644
+ cleanup();
1645
+ mockAuthFetch.mockReset();
1646
+ cancelMocks.cancelPullRequest.mockReset();
1647
+ cancelMocks.cancelPullRequest.mockResolvedValue({ ok: true });
1648
+ });
1649
+
1650
+ it('offers Withdraw suggestion on a proposed row of my own request', () => {
1651
+ renderExplorer({ fileTree: TREE, minePaths: new Map([[PROPOSED, 12]]) });
1652
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1653
+ expect(screen.getByRole('menuitem', { name: /Withdraw suggestion/i })).toBeInTheDocument();
1654
+ });
1655
+
1656
+ /**
1657
+ * The rows are synthesized from `/mine` today, so this is the gate holding
1658
+ * the line rather than a case the tree can reach — which is exactly why it
1659
+ * is tested. An owner seeing another user's proposal must be offered no
1660
+ * Withdraw: their "no" is Decline, and it stays in the dialog.
1661
+ */
1662
+ it('offers no Withdraw on a proposed row from someone else’s request', () => {
1663
+ renderExplorer({
1664
+ fileTree: TREE,
1665
+ minePaths: new Map([[PROPOSED, 12]]),
1666
+ // The row is there; the request is not the caller's.
1667
+ mineNumbers: [],
1668
+ });
1669
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1670
+ expect(screen.getByRole('menu')).toBeInTheDocument();
1671
+ expect(screen.queryByRole('menuitem', { name: /Withdraw/i })).toBeNull();
1672
+ // And nothing else about the row changed.
1673
+ expect(screen.getByRole('menuitem', { name: /Manage access/i })).toBeInTheDocument();
1674
+ });
1675
+
1676
+ it('names the file in the confirmation when the request carries one', async () => {
1677
+ renderExplorer({ fileTree: TREE, minePaths: new Map([[PROPOSED, 12]]) });
1678
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1679
+ fireEvent.click(screen.getByRole('menuitem', { name: /Withdraw suggestion/i }));
1680
+
1681
+ const dialog = await screen.findByRole('dialog', { name: 'Withdraw suggestion' });
1682
+ expect(dialog).toHaveTextContent('Withdraw new-idea.md?');
1683
+ });
1684
+
1685
+ /**
1686
+ * Withdrawal is per REQUEST: a multi-file drop became one change request,
1687
+ * and cancelling it cancels all of it. The user right-clicked one row, so
1688
+ * the count is said before they confirm — not discovered afterwards.
1689
+ */
1690
+ it('says the whole suggestion goes when the request carries several files', async () => {
1691
+ renderExplorer({
1692
+ fileTree: TREE,
1693
+ minePaths: new Map([[PROPOSED, 12]]),
1694
+ crFiles: ['docs/new-idea.md', 'docs/budget.csv', 'docs/plan.md'],
1695
+ });
1696
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1697
+ fireEvent.click(screen.getByRole('menuitem', { name: /Withdraw suggestion/i }));
1698
+
1699
+ const dialog = await screen.findByRole('dialog', { name: 'Withdraw suggestion' });
1700
+ expect(dialog).toHaveTextContent('This withdraws the whole suggestion: 3 files');
1701
+ // The single-file sentence must not also be there — it would name one of
1702
+ // the three and contradict the count.
1703
+ expect(dialog).not.toHaveTextContent('new-idea.md');
1704
+ });
1705
+
1706
+ it('cancels the request and the row goes, without a reload', async () => {
1707
+ const view = renderExplorer({ fileTree: TREE, minePaths: new Map([[PROPOSED, 12]]) });
1708
+ const stale = vi.fn();
1709
+ window.addEventListener(PR_STALE_EVENT, stale);
1710
+ try {
1711
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1712
+ fireEvent.click(screen.getByRole('menuitem', { name: /Withdraw suggestion/i }));
1713
+ const dialog = await screen.findByRole('dialog', { name: 'Withdraw suggestion' });
1714
+
1715
+ // Nothing is sent until Confirm.
1716
+ expect(cancelMocks.cancelPullRequest).not.toHaveBeenCalled();
1717
+ await act(async () => {
1718
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Withdraw' }));
1719
+ });
1720
+
1721
+ // The existing author-cancel path, called with the REQUEST number —
1722
+ // not the path, and not a new endpoint of the tree's own.
1723
+ expect(cancelMocks.cancelPullRequest).toHaveBeenCalledWith(12);
1724
+ // The signal every consumer of the request list listens for. This is
1725
+ // what takes the row away: `/mine` stops carrying the request.
1726
+ expect(stale).toHaveBeenCalled();
1727
+
1728
+ view.requestWithdrawn(12);
1729
+ expect(screen.queryByTitle('Proposed by you: opens the change request')).toBeNull();
1730
+ expect(screen.queryByText('new-idea.md')).toBeNull();
1731
+ } finally {
1732
+ window.removeEventListener(PR_STALE_EVENT, stale);
1733
+ }
1734
+ });
1735
+
1736
+ /**
1737
+ * Already applied, or declined meanwhile. The rows must still re-read from
1738
+ * the server — a refused cancel means the row was describing something no
1739
+ * longer open, and leaving it there is the one outcome worse than the error.
1740
+ */
1741
+ it('refreshes the rows even when the cancel is refused', async () => {
1742
+ cancelMocks.cancelPullRequest.mockRejectedValue(new Error('Change request #12 is already merged'));
1743
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
1744
+ const stale = vi.fn();
1745
+ window.addEventListener(PR_STALE_EVENT, stale);
1746
+ try {
1747
+ renderExplorer({ fileTree: TREE, minePaths: new Map([[PROPOSED, 12]]) });
1748
+ fireEvent.contextMenu(proposedRow(), { clientX: 40, clientY: 40 });
1749
+ fireEvent.click(screen.getByRole('menuitem', { name: /Withdraw suggestion/i }));
1750
+ const dialog = await screen.findByRole('dialog', { name: 'Withdraw suggestion' });
1751
+ await act(async () => {
1752
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Withdraw' }));
1753
+ });
1754
+
1755
+ await waitFor(() => expect(alertSpy).toHaveBeenCalled());
1756
+ expect(String(alertSpy.mock.calls[0][0])).toMatch(/already merged/);
1757
+ expect(stale).toHaveBeenCalled();
1758
+ } finally {
1759
+ window.removeEventListener(PR_STALE_EVENT, stale);
1760
+ alertSpy.mockRestore();
1761
+ }
1762
+ });
1763
+
1764
+ it('leaves an ordinary row’s menu without a Withdraw', () => {
1765
+ renderExplorer({ fileTree: TREE, minePaths: new Map([[PROPOSED, 12]]) });
1766
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 40, clientY: 40 });
1767
+ expect(screen.queryByRole('menuitem', { name: /Withdraw/i })).toBeNull();
1768
+ expect(screen.getByRole('menuitem', { name: /Delete/i })).toBeInTheDocument();
1769
+ });
1770
+ });
1771
+
1772
+ // ── The right-click menu has to land on screen ──
1773
+ //
1774
+ // The panel is `position: fixed`, so whatever falls past the bottom edge of
1775
+ // the window is unreachable: the page will not scroll to a fixed box, and the
1776
+ // wheel scrolls the tree out from under a menu that stays where it was. A
1777
+ // folder's menu is nine rows, so pinning it to the raw pointer put `Manage
1778
+ // access`, `Rename` and `Delete` below the fold for any right-click in the
1779
+ // lower quarter of the sidebar.
1780
+ /** jsdom's own viewport, read at import before any test has stubbed it. */
1781
+ const REAL_VIEWPORT = { width: window.innerWidth, height: window.innerHeight };
1782
+
1783
+ describe('FileExplorer right-click: the menu stays inside the window', () => {
1784
+ const TREE: FileTreeEntry = {
1785
+ name: '.',
1786
+ relativePath: '.',
1787
+ type: 'directory',
1788
+ children: [
1789
+ { name: 'reports', relativePath: 'reports', type: 'directory', children: [] },
1790
+ { name: 'brief.md', relativePath: 'brief.md', type: 'file' },
1791
+ ],
1792
+ };
1793
+
1794
+ const MENU_W = 200;
1795
+ const MENU_H = 300;
1796
+
1797
+ // jsdom lays nothing out, so every `offsetWidth`/`offsetHeight` is 0 and the
1798
+ // placement would have nothing to react to. Give a size to the one element
1799
+ // the hook measures: the fixed wrapper, identified by the `role="menu"`
1800
+ // panel it holds.
1801
+ const isMenuBox = (el: HTMLElement) => el.firstElementChild?.getAttribute('role') === 'menu';
1802
+ let restoreLayout: (() => void) | null = null;
1803
+
1804
+ function stubViewport(width: number, height: number) {
1805
+ const w = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth')!;
1806
+ const h = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')!;
1807
+ // jsdom defines these as own accessors on `window`, so the descriptor is
1808
+ // real and putting it back restores the getter rather than freezing a
1809
+ // number in its place.
1810
+ const iw = Object.getOwnPropertyDescriptor(window, 'innerWidth')!;
1811
+ const ih = Object.getOwnPropertyDescriptor(window, 'innerHeight')!;
1812
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
1813
+ configurable: true,
1814
+ get(this: HTMLElement) {
1815
+ return isMenuBox(this) ? MENU_W : 0;
1816
+ },
969
1817
  });
970
1818
  Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
971
1819
  configurable: true,
@@ -1089,3 +1937,1499 @@ describe('FileExplorer right-click: the viewport stub cleans up after itself', (
1089
1937
  expect(window.innerHeight).toBe(REAL_VIEWPORT.height);
1090
1938
  });
1091
1939
  });
1940
+
1941
+ // Delete asked nothing and a drop moved a file into another folder without a
1942
+ // word about what that means. Both now ask first — and a move says that access
1943
+ // follows the destination, plus whatever else about it is worth knowing.
1944
+ describe('FileExplorer: delete and move ask first', () => {
1945
+ const DRAG_MIME = 'application/x-workspace-path';
1946
+ const DRAG_KIND_MIME = 'application/x-workspace-kind';
1947
+ const KB = 'knowledge-base';
1948
+ const TREE: FileTreeEntry = rootedAtCheckout({
1949
+ name: '.',
1950
+ relativePath: '.',
1951
+ type: 'directory',
1952
+ children: [
1953
+ {
1954
+ name: KB,
1955
+ relativePath: KB,
1956
+ type: 'directory',
1957
+ children: [
1958
+ {
1959
+ name: 'KnowledgeBase',
1960
+ relativePath: `${KB}/KnowledgeBase`,
1961
+ type: 'directory',
1962
+ children: [
1963
+ {
1964
+ name: 'Legal',
1965
+ relativePath: `${KB}/KnowledgeBase/Legal`,
1966
+ type: 'directory',
1967
+ children: [
1968
+ { name: 'contract.pdf', relativePath: `${KB}/KnowledgeBase/Legal/contract.pdf`, type: 'file' },
1969
+ { name: 'access.md', relativePath: `${KB}/KnowledgeBase/Legal/access.md`, type: 'file' },
1970
+ {
1971
+ name: 'Old',
1972
+ relativePath: `${KB}/KnowledgeBase/Legal/Old`,
1973
+ type: 'directory',
1974
+ children: [
1975
+ { name: 'nda.md', relativePath: `${KB}/KnowledgeBase/Legal/Old/nda.md`, type: 'file' },
1976
+ ],
1977
+ },
1978
+ ],
1979
+ },
1980
+ { name: 'Sales', relativePath: `${KB}/KnowledgeBase/Sales`, type: 'directory', children: [] },
1981
+ ],
1982
+ },
1983
+ { name: 'Data', relativePath: `${KB}/Data`, type: 'directory', children: [] },
1984
+ ],
1985
+ },
1986
+ ],
1987
+ });
1988
+ const CONTRACT = `${KB}/KnowledgeBase/Legal/contract.pdf`;
1989
+
1990
+ /** One side of the prospective-access answer. */
1991
+ type Side = { read?: unknown[]; write?: unknown[] };
1992
+ const group = (name: string) => ({ kind: 'group', name });
1993
+ const person = (name: string, email: string) => ({ kind: 'person', name, email });
1994
+
1995
+ /**
1996
+ * Answer the move dialog's access lookup with these before/after holders,
1997
+ * and everything else (the destination-writable preflight) with a writable
1998
+ * verdict — the warnings suite covers that one on its own.
1999
+ */
2000
+ function answerAccess(before: Side, after: Side, opts: { canWrite?: boolean } = {}) {
2001
+ const side = (s: Side) => ({ read: s.read ?? [], write: s.write ?? [] });
2002
+ mockAuthFetch.mockImplementation(async (url: string) => {
2003
+ const u = String(url);
2004
+ if (u.includes('/access/prospective')) {
2005
+ return { ok: true, json: async () => ({ before: side(before), after: side(after) }) };
2006
+ }
2007
+ if (u.includes('/access?')) {
2008
+ return { ok: true, json: async () => ({ canWrite: opts.canWrite ?? true }) };
2009
+ }
2010
+ // Anything else is another case's call, left unanswered as it was
2011
+ // before the move dialog asked about access at all.
2012
+ return undefined;
2013
+ });
2014
+ }
2015
+
2016
+ /** The move dialog once its access lookup has landed. */
2017
+ async function openMoveDialog(rowName: string, sourcePath: string) {
2018
+ await dropOn(rowName, sourcePath);
2019
+ await waitFor(() =>
2020
+ expect(
2021
+ mockAuthFetch.mock.calls.some((c) => String(c[0]).includes('/access/prospective')),
2022
+ ).toBe(true),
2023
+ );
2024
+ // Let the answer render.
2025
+ await act(async () => {});
2026
+ return screen.getByRole('dialog');
2027
+ }
2028
+
2029
+ beforeEach(() => {
2030
+ cleanup();
2031
+ mockAuthFetch.mockReset();
2032
+ // Most cases are not about the access change; default to one that found
2033
+ // nothing so the dialog settles instead of sitting on its fallback note.
2034
+ answerAccess({}, {});
2035
+ });
2036
+ // The branch model is module-global; put back what the shared test setup
2037
+ // applied, so a case that protects `main` does not leak into the next suite.
2038
+ afterEach(() => {
2039
+ configureBranchModel({
2040
+ defaultBranch: 'target-company-state',
2041
+ protectedBranches: ['current-company-state', 'target-company-state'],
2042
+ });
2043
+ });
2044
+
2045
+ /** Open Legal so its rows render (Knowledge's children start collapsed). */
2046
+ function openLegal() {
2047
+ fireEvent.click(screen.getByText('Legal'));
2048
+ }
2049
+
2050
+ async function dropOn(rowName: string, sourcePath: string, kind: 'file' | 'directory' = 'file') {
2051
+ await act(async () => {
2052
+ fireEvent.drop(screen.getByText(rowName), {
2053
+ dataTransfer: {
2054
+ getData: (t: string) =>
2055
+ t === DRAG_MIME ? sourcePath : t === DRAG_KIND_MIME ? kind : '',
2056
+ files: [],
2057
+ },
2058
+ });
2059
+ });
2060
+ }
2061
+
2062
+ async function chooseDelete(rowName: string) {
2063
+ fireEvent.contextMenu(screen.getByText(rowName));
2064
+ await act(async () => {
2065
+ fireEvent.click(screen.getByRole('menuitem', { name: /Delete/i }));
2066
+ });
2067
+ }
2068
+
2069
+ describe('delete', () => {
2070
+ it('names the file and deletes it on Confirm', async () => {
2071
+ const { deleteEntry } = renderExplorer({ fileTree: TREE });
2072
+ openLegal();
2073
+ await chooseDelete('contract.pdf');
2074
+ const dialog = screen.getByRole('dialog');
2075
+ expect(dialog).toHaveTextContent('Delete contract.pdf?');
2076
+ expect(deleteEntry).not.toHaveBeenCalled();
2077
+ await act(async () => {
2078
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
2079
+ });
2080
+ expect(deleteEntry).toHaveBeenCalledWith(CONTRACT);
2081
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2082
+ });
2083
+
2084
+ it('counts every file under a folder, nested ones included', async () => {
2085
+ renderExplorer({ fileTree: TREE });
2086
+ await chooseDelete('Legal');
2087
+ expect(screen.getByRole('dialog')).toHaveTextContent('Delete Legal and its 3 files?');
2088
+ });
2089
+
2090
+ it('deletes nothing on Cancel', async () => {
2091
+ const { deleteEntry } = renderExplorer({ fileTree: TREE });
2092
+ await chooseDelete('Sales');
2093
+ expect(screen.getByRole('dialog')).toHaveTextContent('Delete Sales and its 0 files?');
2094
+ await act(async () => {
2095
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
2096
+ });
2097
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2098
+ expect(deleteEntry).not.toHaveBeenCalled();
2099
+ });
2100
+ });
2101
+
2102
+ describe('move', () => {
2103
+ it('says nobody loses or gains access when the lookup finds no change, and moves on Confirm', async () => {
2104
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2105
+ const dialog = await openMoveDialog('Sales', CONTRACT);
2106
+ expect(dialog).toHaveTextContent("Move contract.pdf to Sales? Nobody's access changes.");
2107
+ // A move between two folders of the same root, on a draft: nothing else to say.
2108
+ expect(screen.queryAllByRole('note')).toHaveLength(0);
2109
+ expect(moveEntry).not.toHaveBeenCalled();
2110
+ await act(async () => {
2111
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
2112
+ });
2113
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Sales/contract.pdf`);
2114
+ });
2115
+
2116
+ it('sends nothing on Cancel', async () => {
2117
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2118
+ await openMoveDialog('Sales', CONTRACT);
2119
+ await act(async () => {
2120
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
2121
+ });
2122
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2123
+ expect(moveEntry).not.toHaveBeenCalled();
2124
+ // The lookup describes the move; it never performs any part of it.
2125
+ expect(
2126
+ mockAuthFetch.mock.calls.every((c) => String(c[0]).includes('/access')),
2127
+ ).toBe(true);
2128
+ });
2129
+
2130
+ it('drops an open confirmation when the workspace changes under it', async () => {
2131
+ const { moveEntry, switchWorkspace } = renderExplorer({ fileTree: TREE, workspaceId: 'draft-a' });
2132
+ await dropOn('Sales', CONTRACT);
2133
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
2134
+ await act(async () => {
2135
+ switchWorkspace('draft-b');
2136
+ });
2137
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2138
+ // Nor does switching back resurrect it.
2139
+ await act(async () => {
2140
+ switchWorkspace('draft-a');
2141
+ });
2142
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2143
+ expect(moveEntry).not.toHaveBeenCalled();
2144
+ });
2145
+
2146
+ it('does nothing on a drop onto the folder the entry is already in', async () => {
2147
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2148
+ await dropOn('Legal', CONTRACT);
2149
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2150
+ expect(moveEntry).not.toHaveBeenCalled();
2151
+ });
2152
+
2153
+ it('never asks about a platform file: the move is refused, not confirmed', async () => {
2154
+ // There used to be a warning here ("moving it changes how the platform
2155
+ // reads it") on a move the dialog then went ahead with. Moving one out
2156
+ // of its folder breaks the workspace, so it is not a choice to confirm.
2157
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
2158
+ try {
2159
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2160
+ await dropOn('Sales', `${KB}/KnowledgeBase/Legal/access.md`);
2161
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2162
+ expect(moveEntry).not.toHaveBeenCalled();
2163
+ expect(alertSpy).toHaveBeenCalledWith('access.md is a platform file and stays in its folder.');
2164
+ } finally {
2165
+ alertSpy.mockRestore();
2166
+ }
2167
+ });
2168
+
2169
+ it('warns when the move crosses from one root into another', async () => {
2170
+ renderExplorer({ fileTree: TREE });
2171
+ await openMoveDialog('Data', CONTRACT);
2172
+ expect(screen.getByRole('note')).toHaveTextContent(
2173
+ 'This moves it out of KnowledgeBase/ into Data/ — the two roots are handled differently.',
2174
+ );
2175
+ });
2176
+
2177
+ it('warns that a move into a folder the caller cannot write will be refused', async () => {
2178
+ configureBranchModel({ defaultBranch: 'main', protectedBranches: ['main'] });
2179
+ answerAccess({}, {}, { canWrite: false });
2180
+ renderExplorer({ fileTree: TREE, workspaceId: 'main' });
2181
+ await dropOn('Sales', CONTRACT);
2182
+ expect(await screen.findByRole('note')).toHaveTextContent(
2183
+ "You can't write to Sales — the move will be refused.",
2184
+ );
2185
+ // The lookup is the folder's, repo-relative — what the access route resolves.
2186
+ const writable = mockAuthFetch.mock.calls
2187
+ .map((c) => String(c[0]))
2188
+ .find((u) => u.includes('/access?'));
2189
+ expect(writable).toContain(
2190
+ `/api/workspace/main/access?path=${encodeURIComponent('KnowledgeBase/Sales')}&kind=folder`,
2191
+ );
2192
+ });
2193
+
2194
+ it('adds no refusal warning when the caller can write the destination', async () => {
2195
+ configureBranchModel({ defaultBranch: 'main', protectedBranches: ['main'] });
2196
+ renderExplorer({ fileTree: TREE, workspaceId: 'main' });
2197
+ await openMoveDialog('Sales', CONTRACT);
2198
+ expect(screen.queryAllByRole('note')).toHaveLength(0);
2199
+ });
2200
+ });
2201
+
2202
+ /**
2203
+ * A rename or a drop onto a name that is taken is refused by the server —
2204
+ * nothing is overwritten — and the sentence it sends ("A file named X
2205
+ * already exists in Y.") is what the sidebar shows, where the action was.
2206
+ * Neither refusal goes through `window.alert`, and neither moves a row.
2207
+ */
2208
+ describe('a destination that is already taken', () => {
2209
+ const TAKEN = 'A file named nda.md already exists in Legal.';
2210
+
2211
+ async function startRename(rowName: string) {
2212
+ fireEvent.contextMenu(screen.getByText(rowName));
2213
+ await act(async () => {
2214
+ fireEvent.click(screen.getByRole('menuitem', { name: /Rename/i }));
2215
+ });
2216
+ return screen.getByRole('textbox') as HTMLInputElement;
2217
+ }
2218
+
2219
+ async function typeAndSubmit(input: HTMLInputElement, name: string) {
2220
+ await act(async () => {
2221
+ fireEvent.change(input, { target: { value: name } });
2222
+ fireEvent.keyDown(input, { key: 'Enter' });
2223
+ });
2224
+ }
2225
+
2226
+ it('shows the refusal in the rename box and keeps the box open on the name that was typed', async () => {
2227
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
2228
+ try {
2229
+ const moveEntry = vi.fn().mockRejectedValue(new Error(TAKEN));
2230
+ renderExplorer({ fileTree: TREE, moveEntry });
2231
+ openLegal();
2232
+
2233
+ const input = await startRename('contract.pdf');
2234
+ await typeAndSubmit(input, 'nda.md');
2235
+
2236
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Legal/nda.md`);
2237
+ expect(screen.getByTestId('rename-error')).toHaveTextContent(TAKEN);
2238
+ // Still open, still holding what was typed: the name is there to fix.
2239
+ expect(screen.getByRole('textbox')).toHaveValue('nda.md');
2240
+ expect(alertSpy).not.toHaveBeenCalled();
2241
+ } finally {
2242
+ alertSpy.mockRestore();
2243
+ }
2244
+ });
2245
+
2246
+ it('sends the rename once more after the name is changed, and closes the box when it lands', async () => {
2247
+ const moveEntry = vi.fn()
2248
+ .mockRejectedValueOnce(new Error(TAKEN))
2249
+ .mockResolvedValueOnce(undefined);
2250
+ renderExplorer({ fileTree: TREE, moveEntry });
2251
+ openLegal();
2252
+
2253
+ const input = await startRename('contract.pdf');
2254
+ await typeAndSubmit(input, 'nda.md');
2255
+ expect(screen.getByTestId('rename-error')).toBeInTheDocument();
2256
+
2257
+ // Editing clears the refusal — the new name has not been refused.
2258
+ await act(async () => {
2259
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'deal.pdf' } });
2260
+ });
2261
+ expect(screen.queryByTestId('rename-error')).not.toBeInTheDocument();
2262
+
2263
+ await act(async () => {
2264
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
2265
+ });
2266
+ expect(moveEntry).toHaveBeenLastCalledWith(CONTRACT, `${KB}/KnowledgeBase/Legal/deal.pdf`);
2267
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
2268
+ });
2269
+
2270
+ it('ignores edits made while the rename is in flight, so the answer lands on the name it was about', async () => {
2271
+ // A name typed while the request is out would be thrown away by the row
2272
+ // unmounting on success, and a refusal coming back would appear under a
2273
+ // name it was never about. The box is frozen for that window instead.
2274
+ let land: (() => void) | undefined;
2275
+ const moveEntry = vi.fn().mockImplementation(
2276
+ () => new Promise<void>((resolve) => { land = resolve; }),
2277
+ );
2278
+ renderExplorer({ fileTree: TREE, moveEntry });
2279
+ openLegal();
2280
+
2281
+ const input = await startRename('contract.pdf');
2282
+ await typeAndSubmit(input, 'nda.md');
2283
+ expect(moveEntry).toHaveBeenCalledTimes(1);
2284
+
2285
+ const inFlight = screen.getByRole('textbox') as HTMLInputElement;
2286
+ expect(inFlight).toHaveAttribute('readonly');
2287
+ await act(async () => {
2288
+ fireEvent.change(inFlight, { target: { value: 'something-else.md' } });
2289
+ fireEvent.keyDown(inFlight, { key: 'Enter' });
2290
+ });
2291
+ // Neither the edit nor the second Enter took: one request, one name.
2292
+ expect(screen.getByRole('textbox')).toHaveValue('nda.md');
2293
+ expect(moveEntry).toHaveBeenCalledTimes(1);
2294
+
2295
+ await act(async () => { land?.(); });
2296
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
2297
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Legal/nda.md`);
2298
+ });
2299
+
2300
+ it('an ordinary rename closes the box and moves the file, as before', async () => {
2301
+ const moveEntry = vi.fn().mockResolvedValue(undefined);
2302
+ renderExplorer({ fileTree: TREE, moveEntry });
2303
+ openLegal();
2304
+
2305
+ const input = await startRename('contract.pdf');
2306
+ await typeAndSubmit(input, 'agreement.pdf');
2307
+
2308
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Legal/agreement.pdf`);
2309
+ expect(screen.queryByTestId('rename-error')).not.toBeInTheDocument();
2310
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
2311
+ });
2312
+
2313
+ it('a refused drop says so under the row and leaves both entries where they were', async () => {
2314
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
2315
+ try {
2316
+ const clash = 'A file named contract.pdf already exists in Sales.';
2317
+ const moveEntry = vi.fn().mockRejectedValue(new Error(clash));
2318
+ renderExplorer({ fileTree: TREE, moveEntry });
2319
+ openLegal();
2320
+
2321
+ await dropOn('Sales', CONTRACT);
2322
+ await act(async () => {
2323
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
2324
+ });
2325
+
2326
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Sales/contract.pdf`);
2327
+ const notice = screen.getByTestId('tree-move-error');
2328
+ expect(notice).toHaveTextContent(clash);
2329
+ expect(notice).toHaveAttribute('role', 'alert');
2330
+ expect(alertSpy).not.toHaveBeenCalled();
2331
+ // The dragged row and the row it was dropped on both stayed.
2332
+ expect(screen.getByText('contract.pdf')).toBeInTheDocument();
2333
+ expect(screen.getByText('Sales')).toBeInTheDocument();
2334
+
2335
+ await act(async () => {
2336
+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss move error' }));
2337
+ });
2338
+ expect(screen.queryByTestId('tree-move-error')).not.toBeInTheDocument();
2339
+ } finally {
2340
+ alertSpy.mockRestore();
2341
+ }
2342
+ });
2343
+
2344
+ it('a drop that lands says nothing', async () => {
2345
+ renderExplorer({ fileTree: TREE });
2346
+ openLegal();
2347
+
2348
+ await dropOn('Sales', CONTRACT);
2349
+ await act(async () => {
2350
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
2351
+ });
2352
+
2353
+ expect(screen.queryByTestId('tree-move-error')).not.toBeInTheDocument();
2354
+ });
2355
+ });
2356
+
2357
+ // The move warning this replaced said only that access would follow the
2358
+ // destination's rules. A tester read that and could not tell what it meant
2359
+ // for anyone, so the dialog now names who loses and who gains — by the
2360
+ // group, role or person the grant names, never expanded into members.
2361
+ describe('move: who loses and who gains access', () => {
2362
+ it('names the group that loses access and the one that gains it', async () => {
2363
+ renderExplorer({ fileTree: TREE });
2364
+ answerAccess(
2365
+ { read: [group('Engineering')], write: [group('Engineering')] },
2366
+ { read: [group('Product')] },
2367
+ );
2368
+ const dialog = await openMoveDialog('Sales', CONTRACT);
2369
+
2370
+ expect(dialog).toHaveTextContent('Move contract.pdf to Sales?');
2371
+ expect(dialog).not.toHaveTextContent("Nobody's access changes.");
2372
+ expect(screen.getByText('Will lose access:')).toBeInTheDocument();
2373
+ expect(screen.getByText('Engineering: can no longer open')).toBeInTheDocument();
2374
+ expect(screen.getByText('Engineering: can no longer edit')).toBeInTheDocument();
2375
+ expect(screen.getByText('Will gain access:')).toBeInTheDocument();
2376
+ expect(screen.getByText('Product: can open')).toBeInTheDocument();
2377
+ });
2378
+
2379
+ it('shows only the lose block when nobody gains', async () => {
2380
+ renderExplorer({ fileTree: TREE });
2381
+ answerAccess({ write: [group('Engineering')] }, {});
2382
+ await openMoveDialog('Sales', CONTRACT);
2383
+
2384
+ expect(screen.getByText('Engineering: can no longer edit')).toBeInTheDocument();
2385
+ expect(screen.queryByText('Will gain access:')).not.toBeInTheDocument();
2386
+ });
2387
+
2388
+ it('shows only the gain block when nobody loses', async () => {
2389
+ renderExplorer({ fileTree: TREE });
2390
+ answerAccess({}, { read: [group('Product')] });
2391
+ await openMoveDialog('Sales', CONTRACT);
2392
+
2393
+ expect(screen.getByText('Product: can open')).toBeInTheDocument();
2394
+ expect(screen.queryByText('Will lose access:')).not.toBeInTheDocument();
2395
+ });
2396
+
2397
+ it('names a directly granted person, not the group they might be in', async () => {
2398
+ renderExplorer({ fileTree: TREE });
2399
+ answerAccess({ read: [person('Ali Raza', 'ali@bevel.software')] }, {});
2400
+ await openMoveDialog('Sales', CONTRACT);
2401
+
2402
+ expect(screen.getByText('Ali Raza: can no longer open')).toBeInTheDocument();
2403
+ });
2404
+
2405
+ it('shows six lines and folds the rest into "and N more"', async () => {
2406
+ renderExplorer({ fileTree: TREE });
2407
+ answerAccess({ read: Array.from({ length: 9 }, (_, i) => group(`Team ${i + 1}`)) }, {});
2408
+ await openMoveDialog('Sales', CONTRACT);
2409
+
2410
+ expect(screen.getByText('Team 6: can no longer open')).toBeInTheDocument();
2411
+ expect(screen.queryByText('Team 7: can no longer open')).not.toBeInTheDocument();
2412
+ expect(screen.getByText('and 3 more')).toBeInTheDocument();
2413
+ });
2414
+
2415
+ it('asks the destination FOLDER, repo-relative, for the file being moved', async () => {
2416
+ renderExplorer({ fileTree: TREE, workspaceId: 'main' });
2417
+ await openMoveDialog('Sales', CONTRACT);
2418
+
2419
+ const url = mockAuthFetch.mock.calls
2420
+ .map((c) => String(c[0]))
2421
+ .find((u) => u.includes('/access/prospective'))!;
2422
+ expect(url).toContain('/api/workspace/main/access/prospective');
2423
+ expect(url).toContain(`from=${encodeURIComponent('KnowledgeBase/Legal/contract.pdf')}`);
2424
+ expect(url).toContain(`toDir=${encodeURIComponent('KnowledgeBase/Sales')}`);
2425
+ });
2426
+
2427
+ it('falls back to the one-sentence form, with a note, when the lookup fails — and Move stays enabled', async () => {
2428
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2429
+ mockAuthFetch.mockImplementation(async (url: string) => {
2430
+ if (String(url).includes('/access/prospective')) throw new Error('network down');
2431
+ return { ok: true, json: async () => ({ canWrite: true }) };
2432
+ });
2433
+ // The lookup is still made; it just never answers usefully.
2434
+ const dialog = await openMoveDialog('Sales', CONTRACT);
2435
+
2436
+ expect(dialog).toHaveTextContent(
2437
+ "Move contract.pdf to Sales? Access to it will follow Sales' rules from now on.",
2438
+ );
2439
+ expect(screen.getByRole('note')).toHaveTextContent("Couldn't work out the access change.");
2440
+ expect(screen.queryByText('Will lose access:')).not.toBeInTheDocument();
2441
+
2442
+ const move = screen.getByRole('button', { name: 'Move' });
2443
+ expect(move).toBeEnabled();
2444
+ await act(async () => {
2445
+ fireEvent.click(move);
2446
+ });
2447
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Sales/contract.pdf`);
2448
+ });
2449
+
2450
+ it('leaves Move enabled while the lookup is still out', async () => {
2451
+ renderExplorer({ fileTree: TREE });
2452
+ mockAuthFetch.mockImplementation(async (url: string) =>
2453
+ String(url).includes('/access/prospective')
2454
+ ? new Promise(() => {}) // never settles — the two-second budget is the caller's
2455
+ : { ok: true, json: async () => ({ canWrite: true }) },
2456
+ );
2457
+ await dropOn('Sales', CONTRACT);
2458
+
2459
+ expect(screen.getByRole('button', { name: 'Move' })).toBeEnabled();
2460
+ expect(screen.getByRole('dialog')).toHaveTextContent('Move contract.pdf to Sales?');
2461
+ expect(screen.queryByRole('note')).not.toBeInTheDocument();
2462
+ });
2463
+
2464
+ it('names a group and a role that share a name as two separate lines', async () => {
2465
+ renderExplorer({ fileTree: TREE });
2466
+ answerAccess(
2467
+ { read: [group('Engineering'), { kind: 'role', name: 'Engineering' }] },
2468
+ {},
2469
+ );
2470
+ await openMoveDialog('Sales', CONTRACT);
2471
+
2472
+ // Two principals whose lines READ the same are still two principals; the
2473
+ // block shows both rather than collapsing them into one.
2474
+ expect(screen.getAllByText('Engineering: can no longer open')).toHaveLength(2);
2475
+ });
2476
+
2477
+ it('asks nothing about a folder being dragged, and says only what it always said', async () => {
2478
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2479
+ // A folder's access is its own access.md plus every file under it — not
2480
+ // the question this lookup answers, so it is not asked.
2481
+ await dropOn('Sales', `${KB}/KnowledgeBase/Legal/Old`, 'directory');
2482
+
2483
+ const dialog = screen.getByRole('dialog');
2484
+ expect(dialog).toHaveTextContent(
2485
+ "Move Old to Sales? Access to it will follow Sales' rules from now on.",
2486
+ );
2487
+ expect(screen.queryByText('Will lose access:')).not.toBeInTheDocument();
2488
+ expect(screen.queryByText("Couldn't work out the access change.")).not.toBeInTheDocument();
2489
+ expect(
2490
+ mockAuthFetch.mock.calls.some((c) => String(c[0]).includes('/access/prospective')),
2491
+ ).toBe(false);
2492
+
2493
+ // And it is still an ordinary move.
2494
+ await act(async () => {
2495
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
2496
+ });
2497
+ expect(moveEntry).toHaveBeenCalledWith(
2498
+ `${KB}/KnowledgeBase/Legal/Old`,
2499
+ `${KB}/KnowledgeBase/Sales/Old`,
2500
+ );
2501
+ });
2502
+
2503
+ it('never decorates the next move with the last one’s answer', async () => {
2504
+ renderExplorer({ fileTree: TREE });
2505
+ answerAccess({ read: [group('Engineering')] }, {});
2506
+ await openMoveDialog('Sales', CONTRACT);
2507
+ expect(screen.getByText('Engineering: can no longer open')).toBeInTheDocument();
2508
+
2509
+ await act(async () => {
2510
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
2511
+ });
2512
+ answerAccess({}, { read: [group('Product')] });
2513
+ await openMoveDialog('Data', CONTRACT);
2514
+
2515
+ expect(screen.queryByText('Engineering: can no longer open')).not.toBeInTheDocument();
2516
+ expect(screen.getByText('Product: can open')).toBeInTheDocument();
2517
+ });
2518
+ });
2519
+
2520
+ describe('keyboard', () => {
2521
+ it('confirms on Enter and moves focus to the row it was dropped on', async () => {
2522
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
2523
+ openLegal();
2524
+ // The dragged row leaves the tree once the move lands; the target stays.
2525
+ const row = screen.getByText('Sales').closest('button')!;
2526
+ await dropOn('Sales', CONTRACT);
2527
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Move' }));
2528
+ await act(async () => {
2529
+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' });
2530
+ });
2531
+ expect(moveEntry).toHaveBeenCalledTimes(1);
2532
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2533
+ expect(document.activeElement).toBe(row);
2534
+ });
2535
+
2536
+ it('cancels on Escape and returns focus to the row', async () => {
2537
+ const { deleteEntry } = renderExplorer({ fileTree: TREE });
2538
+ openLegal();
2539
+ const row = screen.getByText('contract.pdf').closest('button')!;
2540
+ await chooseDelete('contract.pdf');
2541
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
2542
+ await act(async () => {
2543
+ fireEvent.keyDown(document, { key: 'Escape' });
2544
+ });
2545
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
2546
+ expect(deleteEntry).not.toHaveBeenCalled();
2547
+ expect(document.activeElement).toBe(row);
2548
+ });
2549
+
2550
+ it('returns focus to the containing folder after a confirmed delete', async () => {
2551
+ const { deleteEntry } = renderExplorer({ fileTree: TREE });
2552
+ openLegal();
2553
+ const folder = screen.getByText('Legal').closest('button')!;
2554
+ await chooseDelete('contract.pdf');
2555
+ await act(async () => {
2556
+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' });
2557
+ });
2558
+ expect(deleteEntry).toHaveBeenCalledWith(CONTRACT);
2559
+ expect(document.activeElement).toBe(folder);
2560
+ });
2561
+
2562
+ it('lets Enter press Cancel when Cancel has focus', async () => {
2563
+ const { deleteEntry } = renderExplorer({ fileTree: TREE });
2564
+ await chooseDelete('Sales');
2565
+ const cancel = screen.getByRole('button', { name: 'Cancel' });
2566
+ cancel.focus();
2567
+ await act(async () => {
2568
+ fireEvent.keyDown(cancel, { key: 'Enter' });
2569
+ });
2570
+ expect(deleteEntry).not.toHaveBeenCalled();
2571
+ });
2572
+ });
2573
+ });
2574
+
2575
+ // A folder holding files proposed in open change requests. Its delete used to
2576
+ // ask the plain question, count the proposed rows as files it would take, and
2577
+ // leave them behind: the folder came straight back holding only the proposed
2578
+ // rows, and deleting THAT reached the server for a path the branch did not
2579
+ // have. The dialog now names the requests and asks what to do with them.
2580
+ describe('FileExplorer: deleting a folder with proposed files', () => {
2581
+ const KB = 'knowledge-base';
2582
+ const REPORTS = `${KB}/Data/Reports`;
2583
+ const PROPOSED = `${REPORTS}/proposed.md`;
2584
+ /** One committed file on the branch; `proposed.md` exists only in request #12. */
2585
+ const TREE: FileTreeEntry = rootedAtCheckout({
2586
+ name: '.',
2587
+ relativePath: '.',
2588
+ type: 'directory',
2589
+ children: [
2590
+ {
2591
+ name: KB,
2592
+ relativePath: KB,
2593
+ type: 'directory',
2594
+ children: [
2595
+ {
2596
+ name: 'Data',
2597
+ relativePath: `${KB}/Data`,
2598
+ type: 'directory',
2599
+ children: [
2600
+ {
2601
+ name: 'Reports',
2602
+ relativePath: REPORTS,
2603
+ type: 'directory',
2604
+ children: [{ name: 'committed.md', relativePath: `${REPORTS}/committed.md`, type: 'file' }],
2605
+ },
2606
+ ],
2607
+ },
2608
+ ],
2609
+ },
2610
+ ],
2611
+ });
2612
+ /** The branch after "Delete current content only": the folder is gone, the proposal is not. */
2613
+ // Derived from a checkout-rooted fixture, so it says so itself: the
2614
+ // declaration is per-object, and a spread is a new object.
2615
+ const TREE_WITHOUT_REPORTS: FileTreeEntry = rootedAtCheckout({
2616
+ ...TREE,
2617
+ children: [
2618
+ { name: KB, relativePath: KB, type: 'directory', children: [{ name: 'Data', relativePath: `${KB}/Data`, type: 'directory', children: [] }] },
2619
+ ],
2620
+ });
2621
+
2622
+ const request = (over: Record<string, unknown> = {}) => ({
2623
+ number: 12,
2624
+ title: 'Quarterly numbers',
2625
+ authorName: 'Razvan',
2626
+ mine: true,
2627
+ paths: ['Data/Reports/proposed.md'],
2628
+ mayRemove: true,
2629
+ ...over,
2630
+ });
2631
+ const json = (body: unknown, status = 200) => ({
2632
+ ok: status < 400,
2633
+ status,
2634
+ json: async () => body,
2635
+ });
2636
+
2637
+ const removal = (over: Record<string, unknown> = {}) => ({
2638
+ number: 12,
2639
+ removedPaths: ['Data/Reports/proposed.md'],
2640
+ withdrawn: true,
2641
+ stillProposed: [],
2642
+ keptForSaves: false,
2643
+ ...over,
2644
+ });
2645
+
2646
+ function answer(requests: unknown[], results: unknown[] = [removal()]) {
2647
+ mockAuthFetch.mockImplementation(async (url: string, init?: RequestInit) => {
2648
+ if (url.startsWith('/api/workflow/change-requests/under-folder?')) return json({ requests });
2649
+ if (url === '/api/workflow/change-requests/under-folder/remove' && init?.method === 'POST') {
2650
+ return json({ results });
2651
+ }
2652
+ throw new Error(`unexpected fetch ${url}`);
2653
+ });
2654
+ }
2655
+
2656
+ const renderWithProposal = (fileTree: FileTreeEntry = TREE) =>
2657
+ renderExplorer({
2658
+ fileTree,
2659
+ minePaths: new Map([[PROPOSED, 12]]),
2660
+ openChangeRequestPaths: [PROPOSED],
2661
+ });
2662
+
2663
+ async function chooseDelete(rowName: string) {
2664
+ fireEvent.contextMenu(screen.getByText(rowName));
2665
+ await act(async () => {
2666
+ fireEvent.click(screen.getByRole('menuitem', { name: /Delete/i }));
2667
+ });
2668
+ }
2669
+
2670
+ let alertSpy: ReturnType<typeof vi.spyOn>;
2671
+ beforeEach(() => {
2672
+ cleanup();
2673
+ mockAuthFetch.mockReset();
2674
+ alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
2675
+ });
2676
+ afterEach(() => {
2677
+ alertSpy.mockRestore();
2678
+ });
2679
+
2680
+ it('names the open requests and offers the three actions, counting only the files on this branch', async () => {
2681
+ answer([request()]);
2682
+ renderWithProposal();
2683
+ await chooseDelete('Reports');
2684
+ const dialog = await screen.findByRole('dialog');
2685
+ await waitFor(() => expect(dialog).toHaveTextContent('#12 “Quarterly numbers” by you (1 proposed file)'));
2686
+ expect(dialog).toHaveTextContent('Delete Reports and its 1 file?');
2687
+ expect(mockAuthFetch).toHaveBeenCalledWith('/api/workflow/change-requests/under-folder?path=Data%2FReports');
2688
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled();
2689
+ expect(screen.getByRole('button', { name: 'Delete current content only' })).toBeEnabled();
2690
+ expect(screen.getByRole('button', { name: 'Delete folder and its proposed changes' })).toBeEnabled();
2691
+ });
2692
+
2693
+ it('"Delete current content only" deletes the branch copy and leaves the requests alone', async () => {
2694
+ answer([request()]);
2695
+ const retracted = vi.fn();
2696
+ window.addEventListener('bevel:suggestions-retracted', retracted);
2697
+ const { deleteEntry } = renderWithProposal();
2698
+ try {
2699
+ await chooseDelete('Reports');
2700
+ const onlyFolder = await screen.findByRole('button', { name: 'Delete current content only' });
2701
+ await act(async () => {
2702
+ fireEvent.click(onlyFolder);
2703
+ });
2704
+ expect(deleteEntry).toHaveBeenCalledWith(REPORTS);
2705
+ expect(mockAuthFetch).not.toHaveBeenCalledWith(
2706
+ '/api/workflow/change-requests/under-folder/remove',
2707
+ expect.anything(),
2708
+ );
2709
+ // The requests stay open, so their proposed rows stay listed.
2710
+ expect(retracted).not.toHaveBeenCalled();
2711
+ expect(alertSpy).not.toHaveBeenCalled();
2712
+ } finally {
2713
+ window.removeEventListener('bevel:suggestions-retracted', retracted);
2714
+ }
2715
+ });
2716
+
2717
+ it('"Delete folder and its proposed changes" deletes the branch copy, then empties the requests, then clears the markers', async () => {
2718
+ answer([request()]);
2719
+ const events: string[] = [];
2720
+ const onRetract = (e: Event) =>
2721
+ events.push(`retract:${(e as CustomEvent<{ folder: string }>).detail.folder}`);
2722
+ const onStale = () => events.push('stale');
2723
+ window.addEventListener('bevel:suggestions-retracted', onRetract);
2724
+ window.addEventListener('bevel:pr-stale', onStale);
2725
+ const deleteEntry = vi.fn(async () => {
2726
+ events.push('delete');
2727
+ });
2728
+ renderExplorer({
2729
+ fileTree: TREE,
2730
+ deleteEntry,
2731
+ minePaths: new Map([[PROPOSED, 12]]),
2732
+ openChangeRequestPaths: [PROPOSED],
2733
+ });
2734
+ try {
2735
+ await chooseDelete('Reports');
2736
+ const both = await screen.findByRole('button', { name: 'Delete folder and its proposed changes' });
2737
+ await waitFor(() => expect(both).toBeEnabled());
2738
+ await act(async () => {
2739
+ fireEvent.click(both);
2740
+ });
2741
+ await waitFor(() => expect(events).toContain('stale'));
2742
+ expect(deleteEntry).toHaveBeenCalledWith(REPORTS);
2743
+ const removeCall = mockAuthFetch.mock.calls.find(
2744
+ ([url]) => url === '/api/workflow/change-requests/under-folder/remove',
2745
+ );
2746
+ expect(JSON.parse((removeCall?.[1] as RequestInit).body as string)).toEqual({ path: 'Data/Reports' });
2747
+ // Branch first, requests second, markers last.
2748
+ expect(events).toEqual(['delete', 'retract:Data/Reports', 'stale']);
2749
+ expect(alertSpy).not.toHaveBeenCalled();
2750
+ } finally {
2751
+ window.removeEventListener('bevel:suggestions-retracted', onRetract);
2752
+ window.removeEventListener('bevel:pr-stale', onStale);
2753
+ }
2754
+ });
2755
+
2756
+ it('says what the removal left behind: a file proposed meanwhile, a request kept open for a save still landing', async () => {
2757
+ answer(
2758
+ [request(), request({ number: 40, mine: false, authorName: 'Ana', paths: ['Data/Reports/q3.md'] })],
2759
+ [
2760
+ removal({ withdrawn: false, stillProposed: ['Data/Reports/notes.md'] }),
2761
+ removal({ number: 40, removedPaths: ['Data/Reports/q3.md'], withdrawn: false, keptForSaves: true }),
2762
+ ],
2763
+ );
2764
+ renderWithProposal();
2765
+ await chooseDelete('Reports');
2766
+ const both = await screen.findByRole('button', { name: 'Delete folder and its proposed changes' });
2767
+ await waitFor(() => expect(both).toBeEnabled());
2768
+ await act(async () => {
2769
+ fireEvent.click(both);
2770
+ });
2771
+ await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1));
2772
+ const message = String(alertSpy.mock.calls[0]![0]);
2773
+ expect(message).toContain('Deleted Reports and its proposed changes, except:');
2774
+ expect(message).toContain('#12 still proposes Data/Reports/notes.md — added while the folder was being deleted.');
2775
+ expect(message).toContain('#40 stays open: a save to it was still landing.');
2776
+ });
2777
+
2778
+ it('does not touch the requests when the branch delete was called off', async () => {
2779
+ answer([request()]);
2780
+ const deleteEntry = vi.fn().mockResolvedValue(false);
2781
+ renderExplorer({
2782
+ fileTree: TREE,
2783
+ deleteEntry,
2784
+ minePaths: new Map([[PROPOSED, 12]]),
2785
+ openChangeRequestPaths: [PROPOSED],
2786
+ });
2787
+ await chooseDelete('Reports');
2788
+ const both = await screen.findByRole('button', { name: 'Delete folder and its proposed changes' });
2789
+ await act(async () => {
2790
+ fireEvent.click(both);
2791
+ });
2792
+ expect(deleteEntry).toHaveBeenCalled();
2793
+ expect(mockAuthFetch).not.toHaveBeenCalledWith(
2794
+ '/api/workflow/change-requests/under-folder/remove',
2795
+ expect.anything(),
2796
+ );
2797
+ });
2798
+
2799
+ it('disables the second action with the reason when one request is not the caller’s to change', async () => {
2800
+ answer([
2801
+ request(),
2802
+ request({
2803
+ number: 40,
2804
+ title: 'Colleague draft',
2805
+ authorName: 'Ana',
2806
+ mine: false,
2807
+ paths: ['Data/Reports/q3.md'],
2808
+ mayRemove: false,
2809
+ reason: '#40 was proposed by Ana; only its author, an admin or someone who can write every file it proposes here can change it.',
2810
+ }),
2811
+ ]);
2812
+ renderWithProposal();
2813
+ await chooseDelete('Reports');
2814
+ const both = await screen.findByRole('button', { name: 'Delete folder and its proposed changes' });
2815
+ expect(both).toBeDisabled();
2816
+ expect(screen.getByRole('note')).toHaveTextContent('#40 was proposed by Ana');
2817
+ expect(screen.getByRole('dialog')).toHaveTextContent('#40 “Colleague draft” by Ana (1 proposed file)');
2818
+ expect(screen.getByRole('button', { name: 'Delete current content only' })).toBeEnabled();
2819
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled();
2820
+ });
2821
+
2822
+ it('never reaches the server for a folder that only proposed files put in the tree (the reproduction case)', async () => {
2823
+ answer([request()]);
2824
+ const { deleteEntry } = renderWithProposal(TREE_WITHOUT_REPORTS);
2825
+ // The proposal alone keeps the folder in the tree.
2826
+ await chooseDelete('Reports');
2827
+ const onlyFolder = await screen.findByRole('button', { name: 'Delete current content only' });
2828
+ expect(screen.getByRole('dialog')).toHaveTextContent('Delete Reports and its 0 files?');
2829
+ await act(async () => {
2830
+ fireEvent.click(onlyFolder);
2831
+ });
2832
+ expect(deleteEntry).not.toHaveBeenCalled();
2833
+ expect(alertSpy).not.toHaveBeenCalled();
2834
+ });
2835
+
2836
+ it('opens the plain delete at once for a folder no request touches, and keeps it when the check agrees', async () => {
2837
+ answer([]);
2838
+ renderExplorer({ fileTree: TREE });
2839
+ await chooseDelete('Reports');
2840
+ expect(screen.getByRole('dialog')).toHaveTextContent('Delete Reports and its 1 file?');
2841
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled();
2842
+ await waitFor(() =>
2843
+ expect(mockAuthFetch).toHaveBeenCalledWith('/api/workflow/change-requests/under-folder?path=Data%2FReports'),
2844
+ );
2845
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled();
2846
+ expect(screen.queryByRole('button', { name: 'Delete current content only' })).not.toBeInTheDocument();
2847
+ });
2848
+
2849
+ it('still asks about proposals when the shared request list has not shown any (loading or failed)', async () => {
2850
+ answer([request()]);
2851
+ // No proposed paths in the shared list, yet the server knows of #12.
2852
+ renderExplorer({ fileTree: TREE });
2853
+ await chooseDelete('Reports');
2854
+ expect(await screen.findByRole('button', { name: 'Delete folder and its proposed changes' })).toBeEnabled();
2855
+ expect(screen.getByRole('dialog')).toHaveTextContent('#12 “Quarterly numbers” by you (1 proposed file)');
2856
+ });
2857
+
2858
+ it('says nothing about a failed check for a folder the shared list shows no proposals under', async () => {
2859
+ mockAuthFetch.mockResolvedValue(json({ error: 'boom' }, 500));
2860
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
2861
+ try {
2862
+ renderExplorer({ fileTree: TREE });
2863
+ await chooseDelete('Reports');
2864
+ await waitFor(() => expect(mockAuthFetch).toHaveBeenCalled());
2865
+ expect(screen.queryByText(/Couldn't check which change requests/)).not.toBeInTheDocument();
2866
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled();
2867
+ } finally {
2868
+ warn.mockRestore();
2869
+ }
2870
+ });
2871
+
2872
+ it('still offers the plain delete, with a note, when the requests cannot be checked', async () => {
2873
+ mockAuthFetch.mockResolvedValue(json({ error: 'boom' }, 500));
2874
+ const { deleteEntry } = renderWithProposal();
2875
+ await chooseDelete('Reports');
2876
+ await screen.findByText(/Couldn't check which change requests propose files here/);
2877
+ await act(async () => {
2878
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
2879
+ });
2880
+ expect(deleteEntry).toHaveBeenCalledWith(REPORTS);
2881
+ });
2882
+ });
2883
+
2884
+ /**
2885
+ * Read is default-deny, so an empty explorer has two causes that look the
2886
+ * same: nothing is shared with the caller, or nothing exists yet. The listing
2887
+ * root's `withheld` count tells them apart; the explorer says which, and says
2888
+ * nothing once a single entry is on screen.
2889
+ */
2890
+ describe('FileExplorer: an empty tree says why', () => {
2891
+ const KBD = 'knowledge-base';
2892
+ const dirAt = (rel: string, children: FileTreeEntry[] = []): FileTreeEntry => ({
2893
+ name: rel.split('/').pop()!,
2894
+ relativePath: rel,
2895
+ type: 'directory',
2896
+ children,
2897
+ });
2898
+ const fileAt = (rel: string): FileTreeEntry => ({ name: rel.split('/').pop()!, relativePath: rel, type: 'file' });
2899
+ /** A seeded knowledge base: the reserved roots, forced visible, with `kb` under KnowledgeBase. */
2900
+ const seeded = (kb: FileTreeEntry[], extra: Partial<FileTreeEntry> = {}, loose: FileTreeEntry[] = []): FileTreeEntry => rootedAtCheckout({
2901
+ ...dirAt('.', [
2902
+ dirAt(KBD, [
2903
+ dirAt(`${KBD}/KnowledgeBase`, kb),
2904
+ dirAt(`${KBD}/Plugins`),
2905
+ dirAt(`${KBD}/Skills`),
2906
+ ...loose,
2907
+ ]),
2908
+ ]),
2909
+ ...extra,
2910
+ });
2911
+
2912
+ beforeEach(() => {
2913
+ cleanup();
2914
+ mockAuthFetch.mockReset();
2915
+ });
2916
+ afterEach(() => {
2917
+ configureBranchModel({
2918
+ defaultBranch: 'target-company-state',
2919
+ protectedBranches: ['current-company-state', 'target-company-state'],
2920
+ });
2921
+ });
2922
+
2923
+ it('says nothing is shared when entries were withheld and none are visible', () => {
2924
+ renderExplorer({ fileTree: seeded([], { withheld: 12 }) });
2925
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent(
2926
+ 'Nothing here is shared with you yet. Ask an admin to grant you access.',
2927
+ );
2928
+ expect(screen.queryByText(/This knowledge base is empty/)).not.toBeInTheDocument();
2929
+ expect(screen.queryByTestId('tree-empty-create-hint')).not.toBeInTheDocument();
2930
+ });
2931
+
2932
+ it('says the knowledge base is empty, with the create hint, when nothing was withheld and the caller may write', () => {
2933
+ // A draft branch: writable without asking.
2934
+ renderExplorer({ fileTree: seeded([]), workspaceId: 'alice%2Fdraft' });
2935
+ const notice = screen.getByTestId('tree-empty-notice');
2936
+ expect(notice).toHaveTextContent(/^This knowledge base is empty\./);
2937
+ expect(screen.getByTestId('tree-empty-create-hint')).toBeInTheDocument();
2938
+ expect(screen.queryByText(/Nothing here is shared/)).not.toBeInTheDocument();
2939
+ expect(mockAuthFetch).not.toHaveBeenCalled();
2940
+ });
2941
+
2942
+ it('still says "empty" when the only root entry is .bevelignore', () => {
2943
+ renderExplorer({ fileTree: seeded([], {}, [fileAt(`${KBD}/.bevelignore`)]), workspaceId: 'alice%2Fdraft' });
2944
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent('This knowledge base is empty.');
2945
+ });
2946
+
2947
+ it('leaves the create hint out when the caller may not write at the root', async () => {
2948
+ mockAuthFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ canWrite: false }) });
2949
+ renderExplorer({ fileTree: seeded([]), workspaceId: 'target-company-state' });
2950
+ await waitFor(() => expect(mockAuthFetch).toHaveBeenCalled());
2951
+ const url = mockAuthFetch.mock.calls[0][0] as string;
2952
+ expect(url).toContain('/access?path=KnowledgeBase&kind=folder');
2953
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent('This knowledge base is empty.');
2954
+ expect(screen.queryByTestId('tree-empty-create-hint')).not.toBeInTheDocument();
2955
+ });
2956
+
2957
+ it('asks about the KB clone folder, not the workspace root, for a tree that predates the split', async () => {
2958
+ mockAuthFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ canWrite: false }) });
2959
+ renderExplorer({ fileTree: rootedAtCheckout(dirAt('.', [dirAt(KBD)])), workspaceId: 'target-company-state' });
2960
+ await waitFor(() => expect(mockAuthFetch).toHaveBeenCalled());
2961
+ expect(mockAuthFetch.mock.calls[0][0] as string).toContain(`/access?path=${KBD}&kind=folder`);
2962
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent('This knowledge base is empty.');
2963
+ expect(screen.queryByTestId('tree-empty-create-hint')).not.toBeInTheDocument();
2964
+ });
2965
+
2966
+ it('shows the create hint on a protected branch once the root is known writable', async () => {
2967
+ mockAuthFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ canWrite: true }) });
2968
+ renderExplorer({ fileTree: seeded([]), workspaceId: 'target-company-state' });
2969
+ expect(await screen.findByTestId('tree-empty-create-hint')).toBeInTheDocument();
2970
+ });
2971
+
2972
+ it('shows neither message with one visible entry, withheld or not', () => {
2973
+ renderExplorer({ fileTree: seeded([fileAt(`${KBD}/KnowledgeBase/Handbook.md`)], { withheld: 3 }) });
2974
+ expect(screen.queryByTestId('tree-empty-notice')).not.toBeInTheDocument();
2975
+ cleanup();
2976
+ renderExplorer({ fileTree: seeded([dirAt(`${KBD}/KnowledgeBase/Finance`)]) });
2977
+ expect(screen.queryByTestId('tree-empty-notice')).not.toBeInTheDocument();
2978
+ });
2979
+
2980
+ it('shows nothing while the tree is still loading', () => {
2981
+ renderExplorer({ fileTree: null });
2982
+ expect(screen.queryByTestId('tree-empty-notice')).not.toBeInTheDocument();
2983
+ });
2984
+ });
2985
+
2986
+ // The sidebar refuses a platform file's drag and its rename itself, with the
2987
+ // sentence the server refuses with. It is not a second opinion: the same
2988
+ // predicate decides on both sides (`@bevel-software/platform-shared`), so the
2989
+ // tree can answer without a round trip and cannot answer differently.
2990
+ describe('FileExplorer: platform files stay put', () => {
2991
+ const DRAG_MIME = 'application/x-workspace-path';
2992
+ const KB = 'knowledge-base';
2993
+ const sentence = (name: string) => `${name} is a platform file and stays in its folder.`;
2994
+
2995
+ const file = (p: string): FileTreeEntry => ({
2996
+ name: p.slice(p.lastIndexOf('/') + 1),
2997
+ relativePath: p,
2998
+ type: 'file',
2999
+ });
3000
+
3001
+ const TREE: FileTreeEntry = rootedAtCheckout({
3002
+ name: '.',
3003
+ relativePath: '.',
3004
+ type: 'directory',
3005
+ children: [
3006
+ {
3007
+ name: KB,
3008
+ relativePath: KB,
3009
+ type: 'directory',
3010
+ children: [
3011
+ file(`${KB}/access.md`),
3012
+ file(`${KB}/roles.yaml`),
3013
+ file(`${KB}/.bevelignore`),
3014
+ file(`${KB}/AGENTS.md`),
3015
+ // Read from the repository root and nowhere else, so a nested one
3016
+ // is ordinary content — the server says the same.
3017
+ file(`${KB}/Handbook/AGENTS.md`),
3018
+ file(`${KB}/Handbook/notes.md`),
3019
+ { name: 'Sales', relativePath: `${KB}/Sales`, type: 'directory', children: [] },
3020
+ ],
3021
+ },
3022
+ ],
3023
+ });
3024
+
3025
+ const PLATFORM = ['access.md', 'roles.yaml', '.bevelignore', 'AGENTS.md'];
3026
+
3027
+ let alertSpy: ReturnType<typeof vi.spyOn>;
3028
+
3029
+ beforeEach(() => {
3030
+ cleanup();
3031
+ mockAuthFetch.mockReset();
3032
+ alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
3033
+ });
3034
+ afterEach(() => {
3035
+ alertSpy.mockRestore();
3036
+ });
3037
+
3038
+ function row(name: string): HTMLElement {
3039
+ return screen.getAllByText(name)[0].closest('button')!;
3040
+ }
3041
+
3042
+ it.each(PLATFORM)('%s cannot be dragged: the row refuses to start one', (name) => {
3043
+ renderExplorer({ fileTree: TREE });
3044
+ expect(row(name)).toHaveAttribute('draggable', 'false');
3045
+ });
3046
+
3047
+ it.each(PLATFORM)('a drop carrying %s is refused with the sentence, and nothing is sent', async (name) => {
3048
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
3049
+ await act(async () => {
3050
+ fireEvent.drop(screen.getByText('Sales'), {
3051
+ dataTransfer: {
3052
+ getData: (t: string) => (t === DRAG_MIME ? `${KB}/${name}` : ''),
3053
+ files: [],
3054
+ },
3055
+ });
3056
+ });
3057
+ expect(alertSpy).toHaveBeenCalledWith(sentence(name));
3058
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
3059
+ expect(moveEntry).not.toHaveBeenCalled();
3060
+ });
3061
+
3062
+ it.each(PLATFORM)('the Rename action on %s says the sentence and opens nothing', async (name) => {
3063
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
3064
+ fireEvent.contextMenu(row(name));
3065
+ const rename = screen.getByRole('menuitem', { name: /Rename/i });
3066
+ expect(rename).toHaveAttribute('aria-disabled', 'true');
3067
+ expect(rename).toHaveAttribute('title', sentence(name));
3068
+ await act(async () => {
3069
+ fireEvent.click(rename);
3070
+ });
3071
+ // No rename box: the row still shows its name, and nothing was sent.
3072
+ expect(screen.getAllByText(name)[0]).toBeInTheDocument();
3073
+ expect(moveEntry).not.toHaveBeenCalled();
3074
+ });
3075
+
3076
+ it('an ordinary file is untouched: it drags, and Rename is on offer', async () => {
3077
+ const { moveEntry } = renderExplorer({ fileTree: TREE });
3078
+ expect(row('notes.md')).toHaveAttribute('draggable', 'true');
3079
+ fireEvent.contextMenu(row('notes.md'));
3080
+ const rename = screen.getByRole('menuitem', { name: /Rename/i });
3081
+ expect(rename).not.toHaveAttribute('aria-disabled');
3082
+ await act(async () => {
3083
+ fireEvent.drop(screen.getByText('Sales'), {
3084
+ dataTransfer: {
3085
+ getData: (t: string) => (t === DRAG_MIME ? `${KB}/Handbook/notes.md` : ''),
3086
+ files: [],
3087
+ },
3088
+ });
3089
+ });
3090
+ expect(alertSpy).not.toHaveBeenCalled();
3091
+ expect(screen.getByRole('dialog')).toHaveTextContent('Move notes.md to Sales?');
3092
+ await act(async () => {
3093
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
3094
+ });
3095
+ expect(moveEntry).toHaveBeenCalledWith(`${KB}/Handbook/notes.md`, `${KB}/Sales/notes.md`);
3096
+ });
3097
+
3098
+ // The recovery the refusal must not swallow: an admin putting a MISPLACED
3099
+ // platform file back where the platform reads it. The row cannot know the
3100
+ // destination, so it keeps only what it is sure of — the root's own copy
3101
+ // never moves, and nobody but an admin moves any of them — and lets the
3102
+ // server answer the rest, which is the only place the answer lives.
3103
+ describe('an admin may drag a misplaced one back', () => {
3104
+ const MISPLACED: FileTreeEntry = rootedAtCheckout({
3105
+ name: '.',
3106
+ relativePath: '.',
3107
+ type: 'directory',
3108
+ children: [
3109
+ {
3110
+ name: KB,
3111
+ relativePath: KB,
3112
+ type: 'directory',
3113
+ children: [
3114
+ file(`${KB}/access.md`),
3115
+ file(`${KB}/Misplaced/.bevelignore`),
3116
+ { name: 'Sales', relativePath: `${KB}/Sales`, type: 'directory', children: [] },
3117
+ ],
3118
+ },
3119
+ ],
3120
+ });
3121
+
3122
+ function misplacedRow(): HTMLElement {
3123
+ return screen.getAllByText('.bevelignore')[0].closest('button')!;
3124
+ }
3125
+
3126
+ it('the misplaced row drags, and the drop asks rather than refusing', async () => {
3127
+ const { moveEntry } = renderExplorer({ fileTree: MISPLACED, isAdmin: true });
3128
+ expect(misplacedRow()).toHaveAttribute('draggable', 'true');
3129
+ await act(async () => {
3130
+ fireEvent.drop(screen.getByText('Sales'), {
3131
+ dataTransfer: {
3132
+ getData: (t: string) => (t === DRAG_MIME ? `${KB}/Misplaced/.bevelignore` : ''),
3133
+ files: [],
3134
+ },
3135
+ });
3136
+ });
3137
+ expect(alertSpy).not.toHaveBeenCalled();
3138
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
3139
+ await act(async () => {
3140
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
3141
+ });
3142
+ expect(moveEntry).toHaveBeenCalledWith(
3143
+ `${KB}/Misplaced/.bevelignore`,
3144
+ `${KB}/Sales/.bevelignore`,
3145
+ );
3146
+ });
3147
+
3148
+ it('a drop that means the top level lands in the clone, not beside it', async () => {
3149
+ // The restore the root-only names need: a drop on the tree's own root
3150
+ // row, which resolves to no folder. Sent bare, that move would put
3151
+ // `.bevelignore` BESIDE the clone — out of the repository, where nothing
3152
+ // reads it and git never sees it again — so it resolves to the clone's
3153
+ // root instead. (The split explorer draws the clone's roots and its
3154
+ // loose files but no row for the clone itself, so there the repository
3155
+ // root is reached from the API and the agent's tool, not by dragging.)
3156
+ const { moveEntry } = renderExplorer({ fileTree: MISPLACED, isAdmin: true });
3157
+ await act(async () => {
3158
+ fireEvent.drop(screen.getByRole('button', { name: KB }), {
3159
+ dataTransfer: {
3160
+ getData: (t: string) => (t === DRAG_MIME ? `${KB}/Misplaced/.bevelignore` : ''),
3161
+ files: [],
3162
+ },
3163
+ });
3164
+ });
3165
+ expect(alertSpy).not.toHaveBeenCalled();
3166
+ expect(screen.getByRole('dialog')).toHaveTextContent('to the top level');
3167
+ await act(async () => {
3168
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
3169
+ });
3170
+ expect(moveEntry).toHaveBeenCalledWith(`${KB}/Misplaced/.bevelignore`, `${KB}/.bevelignore`);
3171
+ });
3172
+
3173
+ it("the root's own copy still cannot be dragged, admin or not", () => {
3174
+ renderExplorer({ fileTree: MISPLACED, isAdmin: true });
3175
+ expect(row('access.md')).toHaveAttribute('draggable', 'false');
3176
+ });
3177
+
3178
+ it('a non-admin gets no exception: the misplaced row is refused like any other', async () => {
3179
+ const { moveEntry } = renderExplorer({ fileTree: MISPLACED, isAdmin: false });
3180
+ expect(misplacedRow()).toHaveAttribute('draggable', 'false');
3181
+ await act(async () => {
3182
+ fireEvent.drop(screen.getByText('Sales'), {
3183
+ dataTransfer: {
3184
+ getData: (t: string) => (t === DRAG_MIME ? `${KB}/Misplaced/.bevelignore` : ''),
3185
+ files: [],
3186
+ },
3187
+ });
3188
+ });
3189
+ expect(alertSpy).toHaveBeenCalledWith(sentence('.bevelignore'));
3190
+ expect(moveEntry).not.toHaveBeenCalled();
3191
+ });
3192
+
3193
+ it('a rename is never the recovery, so an admin is refused it', async () => {
3194
+ renderExplorer({ fileTree: MISPLACED, isAdmin: true });
3195
+ fireEvent.contextMenu(misplacedRow());
3196
+ const rename = screen.getByRole('menuitem', { name: /Rename/i });
3197
+ expect(rename).toHaveAttribute('aria-disabled', 'true');
3198
+ expect(rename).toHaveAttribute('title', sentence('.bevelignore'));
3199
+ });
3200
+ });
3201
+
3202
+ it('a FOLDER named like a platform file refuses the rename too, not just the drag', () => {
3203
+ // The server reads the path, not the kind. Offering Rename here opened an
3204
+ // editor that could only fail on the round trip.
3205
+ const WITH_FOLDER: FileTreeEntry = rootedAtCheckout({
3206
+ name: '.',
3207
+ relativePath: '.',
3208
+ type: 'directory',
3209
+ children: [
3210
+ {
3211
+ name: KB,
3212
+ relativePath: KB,
3213
+ type: 'directory',
3214
+ children: [
3215
+ { name: 'access.md', relativePath: `${KB}/access.md`, type: 'directory', children: [] },
3216
+ ],
3217
+ },
3218
+ ],
3219
+ });
3220
+ renderExplorer({ fileTree: WITH_FOLDER });
3221
+ // The folder row's draggable sits on the wrapper around the name button.
3222
+ expect(screen.getByText('access.md').closest('[draggable]')).toHaveAttribute('draggable', 'false');
3223
+ fireEvent.contextMenu(row('access.md'));
3224
+ const rename = screen.getByRole('menuitem', { name: /Rename/i });
3225
+ expect(rename).toHaveAttribute('aria-disabled', 'true');
3226
+ expect(rename).toHaveAttribute('title', sentence('access.md'));
3227
+ });
3228
+
3229
+ it('a nested AGENTS.md is content, not a platform file: it drags like any other row', () => {
3230
+ renderExplorer({ fileTree: TREE });
3231
+ // Both rows are named AGENTS.md; the nested one is the second.
3232
+ const rows = screen.getAllByText('AGENTS.md').map((n) => n.closest('button')!);
3233
+ const nested = rows.find((r) => r.getAttribute('data-tree-path') === `${KB}/Handbook/AGENTS.md`);
3234
+ expect(nested).toHaveAttribute('draggable', 'true');
3235
+ });
3236
+ });
3237
+
3238
+ /**
3239
+ * A proposed row is a link to the request's view of ONE file. Clicking it has
3240
+ * to arrive there, and the URL has to carry enough for a reload to arrive
3241
+ * there too — a request bundling twenty proposals otherwise opens on whatever
3242
+ * file happens to be first.
3243
+ */
3244
+ describe('FileExplorer: a proposed row opens its request at that file', () => {
3245
+ beforeEach(() => {
3246
+ cleanup();
3247
+ mockAuthFetch.mockReset();
3248
+ // The dialog's detail read goes through authFetch; an unresolved promise
3249
+ // keeps it on its loading state, which is all these assertions need.
3250
+ mockAuthFetch.mockImplementation(() => new Promise(() => {}));
3251
+ });
3252
+
3253
+ const TREE_WITH_DOCS: FileTreeEntry = {
3254
+ name: '.',
3255
+ relativePath: '.',
3256
+ type: 'directory',
3257
+ children: [{ name: 'docs', relativePath: 'docs', type: 'directory', children: [] }],
3258
+ };
3259
+
3260
+ const search = () => screen.getByTestId('location-search').textContent;
3261
+
3262
+ it('puts the request and the clicked file in the URL', async () => {
3263
+ renderExplorer({
3264
+ fileTree: TREE_WITH_DOCS,
3265
+ minePaths: new Map([['docs/new-idea.md', 12]]),
3266
+ });
3267
+ fireEvent.click(screen.getByTitle('Proposed by you: opens the change request').closest('button')!);
3268
+
3269
+ expect(
3270
+ await screen.findByRole('dialog', { name: /Change request: Suggested change/ }),
3271
+ ).toBeInTheDocument();
3272
+ expect(search()).toBe(`?cr=12&file=${encodeURIComponent(kbPath('docs/new-idea.md'))}`);
3273
+ });
3274
+
3275
+ it('opens straight from the URL, so a reload lands on the same file', async () => {
3276
+ renderExplorer({
3277
+ fileTree: TREE_WITH_DOCS,
3278
+ minePaths: new Map([['docs/new-idea.md', 12]]),
3279
+ initialEntries: [`/workspace/main?cr=12&file=${encodeURIComponent(kbPath('docs/new-idea.md'))}`],
3280
+ });
3281
+ // No click: the query alone opened it.
3282
+ expect(
3283
+ await screen.findByRole('dialog', { name: /Change request: Suggested change/ }),
3284
+ ).toBeInTheDocument();
3285
+ });
3286
+
3287
+ it('drops both parameters when the dialog closes', async () => {
3288
+ renderExplorer({
3289
+ fileTree: TREE_WITH_DOCS,
3290
+ minePaths: new Map([['docs/new-idea.md', 12]]),
3291
+ initialEntries: [`/workspace/main?cr=12&file=${encodeURIComponent(kbPath('docs/new-idea.md'))}`],
3292
+ });
3293
+ const dialog = await screen.findByRole('dialog', { name: /Change request: Suggested change/ });
3294
+ fireEvent.click(within(dialog).getByRole('button', { name: /close/i }));
3295
+ await waitFor(() => expect(search()).toBe(''));
3296
+ });
3297
+
3298
+ it('opens nothing for a request the caller does not have', async () => {
3299
+ renderExplorer({
3300
+ fileTree: TREE_WITH_DOCS,
3301
+ minePaths: new Map([['docs/new-idea.md', 12]]),
3302
+ initialEntries: [`/workspace/main?cr=999&file=${encodeURIComponent(kbPath('docs/new-idea.md'))}`],
3303
+ });
3304
+ await waitFor(() => expect(screen.getByTestId('location-search')).toBeInTheDocument());
3305
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
3306
+ });
3307
+ });
3308
+
3309
+ /**
3310
+ * WHERE the explorer takes its root from. The repository is the `<kbDirName>/`
3311
+ * child of the workspace tree, by name, and the sections are that folder's
3312
+ * children — never a folder found by searching the tree for a well-known
3313
+ * name, which on core-staging found a stray `KnowledgeBase/` beside the
3314
+ * checkout and rendered it as the whole knowledge base.
3315
+ */
3316
+ describe('FileExplorer: the root is the checkout', () => {
3317
+ beforeEach(() => {
3318
+ cleanup();
3319
+ mockAuthFetch.mockReset();
3320
+ });
3321
+
3322
+ const d = (rel: string, children: FileTreeEntry[] = []): FileTreeEntry => ({
3323
+ name: rel.split('/').pop()!,
3324
+ relativePath: rel,
3325
+ type: 'directory',
3326
+ children,
3327
+ });
3328
+ const f = (rel: string): FileTreeEntry => ({ name: rel.split('/').pop()!, relativePath: rel, type: 'file' });
3329
+
3330
+ /** The checkout as a seeded knowledge base: the split, a stray content folder, a loose file. */
3331
+ const CHECKOUT = d(KB_DIR, [
3332
+ d(`${KB_DIR}/KnowledgeBase`, [f(`${KB_DIR}/KnowledgeBase/Handbook.md`)]),
3333
+ d(`${KB_DIR}/Data`, [f(`${KB_DIR}/Data/rows.csv`)]),
3334
+ d(`${KB_DIR}/Plugins`, [d(`${KB_DIR}/Plugins/GTM`)]),
3335
+ d(`${KB_DIR}/Skills`, [d(`${KB_DIR}/Skills/Sales`)]),
3336
+ d(`${KB_DIR}/Legal`, [f(`${KB_DIR}/Legal/Terms.md`)]),
3337
+ f(`${KB_DIR}/roles.yaml`),
3338
+ ]);
3339
+
3340
+ /** Exactly what sat beside the checkout on core-staging on 2026-09-22. */
3341
+ const STRAYS: FileTreeEntry[] = [
3342
+ d('KnowledgeBase', [f('KnowledgeBase/Planted.md')]),
3343
+ d('Plugins', [d('Plugins/zz-stray', [f('Plugins/zz-stray/plugin.json')])]),
3344
+ d('Skills', [d('Skills/stray-scope', [f('Skills/stray-scope/SKILL.md')])]),
3345
+ f('Stray.docx'),
3346
+ ];
3347
+
3348
+ const workspace = (...children: FileTreeEntry[]): FileTreeEntry => d('.', children);
3349
+
3350
+ /** Every row on screen, in order — the tree as the reader sees it. */
3351
+ const rendered = () =>
3352
+ Array.from(document.querySelectorAll('[data-tree-path]')).map(
3353
+ (el) => `${(el as HTMLElement).dataset.treePath}:${el.textContent}`,
3354
+ );
3355
+
3356
+ it('splits the checkout into its sections, and renders the same tree with strays beside it', () => {
3357
+ renderExplorer({ fileTree: workspace(CHECKOUT), verbatimTree: true });
3358
+ const clean = rendered();
3359
+ expect(clean.length).toBeGreaterThan(0);
3360
+ cleanup();
3361
+
3362
+ renderExplorer({ fileTree: workspace(...STRAYS, CHECKOUT), verbatimTree: true });
3363
+ expect(rendered()).toEqual(clean);
3364
+ });
3365
+
3366
+ it('renders no entry from outside the checkout — not one path, not one name', () => {
3367
+ renderExplorer({ fileTree: workspace(...STRAYS, CHECKOUT), verbatimTree: true });
3368
+ for (const path of rendered().map((r) => r.split(':')[0])) {
3369
+ expect(path === KB_DIR || path.startsWith(`${KB_DIR}/`)).toBe(true);
3370
+ }
3371
+ expect(screen.queryByText('Planted.md')).toBeNull();
3372
+ expect(screen.queryByText('zz-stray')).toBeNull();
3373
+ expect(screen.queryByText('stray-scope')).toBeNull();
3374
+ expect(screen.queryByText('Stray.docx')).toBeNull();
3375
+ });
3376
+
3377
+ /**
3378
+ * How the bug showed itself: with the root one level too high, the real
3379
+ * checkout was just another content folder and folded into Knowledge.
3380
+ */
3381
+ it('never folds the checkout folder itself into Knowledge', () => {
3382
+ renderExplorer({ fileTree: workspace(...STRAYS, CHECKOUT), verbatimTree: true });
3383
+ // Knowledge is drawn at the checkout's `KnowledgeBase/`, and the stray
3384
+ // content folder inside the checkout is the only thing folded in.
3385
+ expect(screen.getByText('Knowledge')).toBeInTheDocument();
3386
+ expect(screen.getByText('Legal')).toBeInTheDocument();
3387
+ expect(screen.queryByText(KB_DIR)).toBeNull();
3388
+ });
3389
+
3390
+ it('shows the empty state naming the missing checkout, and nothing else, when it is absent', () => {
3391
+ renderExplorer({ fileTree: workspace(...STRAYS), verbatimTree: true });
3392
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent(
3393
+ 'Nothing to show here: the repository checkout is missing.',
3394
+ );
3395
+ expect(rendered()).toEqual([]);
3396
+ expect(screen.queryByText('Knowledge')).toBeNull();
3397
+ expect(screen.queryByText('Planted.md')).toBeNull();
3398
+ expect(screen.queryByText('Stray.docx')).toBeNull();
3399
+ });
3400
+
3401
+ /**
3402
+ * The drop the sidebar accepts goes where the sidebar reads from. With no
3403
+ * checkout there is no such place: the notice says the repository is
3404
+ * missing, and a drop taken anyway would be written beside the missing
3405
+ * folder and never appear.
3406
+ */
3407
+ it('drops onto the background into the checkout, and refuses them when there is none', async () => {
3408
+ const drop = async () => {
3409
+ const file = new File(['drop'], 'dropped.md');
3410
+ await act(async () => {
3411
+ fireEvent.drop(screen.getByTestId('file-explorer-root'), {
3412
+ dataTransfer: { files: [file], getData: () => '' },
3413
+ });
3414
+ });
3415
+ };
3416
+
3417
+ const dispatchUpload = vi.fn().mockResolvedValue(undefined);
3418
+ renderExplorer({ fileTree: workspace(...STRAYS, CHECKOUT), verbatimTree: true, dispatchUpload });
3419
+ await drop();
3420
+ expect(dispatchUpload).toHaveBeenCalledTimes(1);
3421
+ expect(dispatchUpload.mock.calls[0][1]).toBe(KB_DIR);
3422
+ cleanup();
3423
+
3424
+ const refused = vi.fn().mockResolvedValue(undefined);
3425
+ renderExplorer({ fileTree: workspace(...STRAYS), verbatimTree: true, dispatchUpload: refused });
3426
+ await drop();
3427
+ expect(refused).not.toHaveBeenCalled();
3428
+ });
3429
+
3430
+ /** A checkout that is merely EMPTY is a different answer, and keeps its own. */
3431
+ it('says the knowledge base is empty, not missing, when the checkout is there but bare', () => {
3432
+ renderExplorer({ fileTree: workspace(d(KB_DIR, [d(`${KB_DIR}/KnowledgeBase`)])), verbatimTree: true });
3433
+ expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent(/^This knowledge base is empty\./);
3434
+ });
3435
+ });