@bevel-software/platform-core-frontend 0.15.1 → 0.20.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 (347) hide show
  1. package/THIRD-PARTY-NOTICES.md +2 -2
  2. package/package.json +3 -3
  3. package/src/core/CoreAppShell.tsx +20 -9
  4. package/src/core/__tests__/AppChrome.test.tsx +0 -3
  5. package/src/core/__tests__/events.test.ts +43 -0
  6. package/src/core/bootstrap.ts +11 -3
  7. package/src/core/events.ts +85 -3
  8. package/src/core/registry.ts +1 -1
  9. package/src/lib/__tests__/email.test.ts +44 -0
  10. package/src/lib/email.ts +37 -1
  11. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +141 -0
  12. package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +204 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.download-read.test.tsx +234 -0
  14. package/src/modules/access/__tests__/ManageAccessDialog.edited-row-visible.test.tsx +160 -0
  15. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +2 -2
  16. package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +166 -0
  17. package/src/modules/access/__tests__/ManageAccessDialog.restrict.test.tsx +510 -0
  18. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-axes.test.tsx +299 -0
  19. package/src/modules/access/__tests__/ManageAccessDialog.row-menu-width.test.tsx +226 -0
  20. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +721 -126
  21. package/src/modules/access/__tests__/ManageAccessDialog.unknown-email.test.tsx +314 -0
  22. package/src/modules/access/__tests__/manage-access-affordance.test.ts +14 -0
  23. package/src/modules/access/__tests__/tailwindDeclarations.ts +210 -0
  24. package/src/modules/access/api.ts +140 -6
  25. package/src/modules/access/components/ManageAccessDialog.tsx +1299 -561
  26. package/src/modules/access/manage-access-affordance.ts +17 -0
  27. package/src/modules/admin/__tests__/AddMemberInput.test.tsx +297 -0
  28. package/src/modules/admin/__tests__/AdminRolesPage.capabilities.test.tsx +2 -2
  29. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +189 -0
  30. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +1 -1
  31. package/src/modules/admin/__tests__/DirectoryGroupsPage.suggest.test.tsx +182 -0
  32. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +165 -14
  33. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +401 -4
  34. package/src/modules/admin/__tests__/group-members-path.test.ts +27 -0
  35. package/src/modules/admin/components/AddMemberInput.tsx +268 -0
  36. package/src/modules/admin/components/AdminRolesPage.tsx +97 -132
  37. package/src/modules/admin/components/DirectoryGroupsPage.tsx +91 -39
  38. package/src/modules/admin/components/UserAccountsPage.tsx +271 -37
  39. package/src/modules/admin/components/group-members-path.ts +32 -0
  40. package/src/modules/admin/services/roles.api.ts +12 -1
  41. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +312 -0
  42. package/src/modules/audit/components/AuditEventsPanel.tsx +319 -0
  43. package/src/modules/audit/components/AuditLogPage.tsx +373 -0
  44. package/src/modules/audit/components/principal-grouping.ts +49 -0
  45. package/src/modules/audit/services/audit.api.ts +98 -0
  46. package/src/modules/auth/__tests__/AccountPage.test.tsx +50 -2
  47. package/src/modules/auth/components/AccountPage.tsx +73 -54
  48. package/src/modules/auth/components/LoginScreen.tsx +1 -0
  49. package/src/modules/auth/services/account.api.ts +78 -4
  50. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +144 -0
  51. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +422 -0
  52. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +431 -0
  53. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +193 -0
  54. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +142 -0
  55. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +202 -0
  56. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +205 -13
  57. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +271 -0
  58. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +208 -0
  59. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +286 -0
  60. package/src/modules/change-requests/__tests__/propose.concurrent.test.ts +273 -0
  61. package/src/modules/change-requests/__tests__/readFailure.test.ts +122 -0
  62. package/src/modules/change-requests/__tests__/useCrFileDiffs.test.tsx +238 -0
  63. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +56 -1
  64. package/src/modules/change-requests/__tests__/useForkPointFile.test.tsx +79 -0
  65. package/src/modules/change-requests/components/BranchFilePreview.tsx +357 -0
  66. package/src/modules/change-requests/components/ChangeBox.tsx +31 -2
  67. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +862 -72
  68. package/src/modules/change-requests/components/CrFileTree.tsx +74 -58
  69. package/src/modules/change-requests/components/FileChangeBoxes.tsx +19 -15
  70. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +41 -7
  71. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +181 -23
  72. package/src/modules/change-requests/hooks/useFileOnBranch.ts +70 -7
  73. package/src/modules/change-requests/hooks/useForkPointFile.ts +77 -0
  74. package/src/modules/change-requests/services/change-requests.api.ts +57 -1
  75. package/src/modules/change-requests/services/denied-file.api.ts +53 -0
  76. package/src/modules/change-requests/services/propose.api.ts +97 -8
  77. package/src/modules/change-requests/utils/approval.ts +15 -0
  78. package/src/modules/change-requests/utils/author.ts +32 -0
  79. package/src/modules/change-requests/utils/readFailure.ts +110 -0
  80. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +20 -0
  81. package/src/modules/git/components/FileHistoryPanel.tsx +5 -0
  82. package/src/modules/git/components/PullRequestsForMe.tsx +51 -24
  83. package/src/modules/git/services/__tests__/error-messages.test.ts +29 -0
  84. package/src/modules/git/services/error-messages.ts +12 -0
  85. package/src/modules/git/services/pr-prompts.ts +5 -5
  86. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +401 -0
  87. package/src/modules/layout/__tests__/SidebarFooterGrid.test.tsx +286 -0
  88. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +61 -0
  89. package/src/modules/layout/components/AppLayout.tsx +2 -0
  90. package/src/modules/layout/components/MobileChatLayout.tsx +4 -1
  91. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +4 -1
  92. package/src/modules/layout/components/SidebarFrame.tsx +108 -3
  93. package/src/modules/library/__tests__/AddToPluginDialog.test.tsx +171 -5
  94. package/src/modules/library/__tests__/DeleteToolDialog.test.tsx +356 -0
  95. package/src/modules/library/__tests__/IntegrationsSetupReminder.test.tsx +60 -0
  96. package/src/modules/library/__tests__/LibraryCard.test.tsx +91 -10
  97. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +242 -107
  98. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +103 -98
  99. package/src/modules/library/__tests__/LinkSkillPanel.test.tsx +20 -5
  100. package/src/modules/library/__tests__/LockedPluginView.test.tsx +97 -7
  101. package/src/modules/library/__tests__/NewPluginDialog.test.tsx +13 -4
  102. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +79 -3
  103. package/src/modules/library/__tests__/PersonalPluginPage.test.tsx +201 -0
  104. package/src/modules/library/__tests__/PluginExtras.test.tsx +100 -9
  105. package/src/modules/library/__tests__/PluginJoinRequests.test.tsx +60 -1
  106. package/src/modules/library/__tests__/PluginPage.test.tsx +258 -6
  107. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +16 -56
  108. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +155 -152
  109. package/src/modules/library/__tests__/PluginsSidebarMenu.test.tsx +16 -0
  110. package/src/modules/library/__tests__/SharedViaPlugins.test.tsx +106 -0
  111. package/src/modules/library/__tests__/SkillPage.test.tsx +386 -80
  112. package/src/modules/library/__tests__/SkillsTree.test.tsx +293 -4
  113. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +582 -71
  114. package/src/modules/library/__tests__/ToolPage.test.tsx +87 -4
  115. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +173 -26
  116. package/src/modules/library/__tests__/auth-harness.tsx +9 -9
  117. package/src/modules/library/__tests__/card-row-menu.test.tsx +320 -0
  118. package/src/modules/library/__tests__/library-data.mapping.test.tsx +98 -0
  119. package/src/modules/library/__tests__/library-data.stale.test.tsx +121 -28
  120. package/src/modules/library/__tests__/library-data.test.ts +7 -0
  121. package/src/modules/library/__tests__/library-paths.test.ts +47 -4
  122. package/src/modules/library/__tests__/link-membership.test.ts +13 -4
  123. package/src/modules/library/__tests__/name-with-badges.test.tsx +273 -0
  124. package/src/modules/library/__tests__/newSkillMarkdown.test.ts +30 -0
  125. package/src/modules/library/__tests__/owner-pill.test.tsx +357 -0
  126. package/src/modules/library/__tests__/pending-tools.test.tsx +400 -0
  127. package/src/modules/library/__tests__/plugin-entries.test.ts +122 -0
  128. package/src/modules/library/__tests__/plugin-summary.test.ts +36 -1
  129. package/src/modules/library/__tests__/status.test.ts +82 -2
  130. package/src/modules/library/__tests__/tools.api.test.ts +44 -1
  131. package/src/modules/library/components/AccessRequestsBanner.tsx +85 -47
  132. package/src/modules/library/components/AddDialogTabs.tsx +103 -0
  133. package/src/modules/library/components/AddToPluginDialog.tsx +74 -18
  134. package/src/modules/library/components/IntegrationsSetupReminder.tsx +59 -0
  135. package/src/modules/library/components/ItemActionsMenu.tsx +288 -0
  136. package/src/modules/library/components/LibraryCard.tsx +146 -45
  137. package/src/modules/library/components/LibraryLayout.tsx +119 -256
  138. package/src/modules/library/components/LibraryPage.tsx +172 -39
  139. package/src/modules/library/components/LinkSkillPanel.tsx +1 -3
  140. package/src/modules/library/components/LockedPluginView.tsx +62 -34
  141. package/src/modules/library/components/NameWithBadges.tsx +164 -0
  142. package/src/modules/library/components/NewPluginDialog.tsx +16 -2
  143. package/src/modules/library/components/PageActions.tsx +11 -9
  144. package/src/modules/library/components/{PendingSkillReview.tsx → PendingItemReview.tsx} +14 -7
  145. package/src/modules/library/components/PersonalAddDialog.tsx +68 -18
  146. package/src/modules/library/components/PersonalPluginPage.tsx +121 -22
  147. package/src/modules/library/components/PluginExtras.tsx +140 -17
  148. package/src/modules/library/components/PluginIndexRow.tsx +47 -12
  149. package/src/modules/library/components/PluginPage.tsx +157 -41
  150. package/src/modules/library/components/PluginRows.tsx +286 -0
  151. package/src/modules/library/components/PluginsSidebar.tsx +239 -263
  152. package/src/modules/library/components/PluginsSidebarMenu.tsx +26 -1
  153. package/src/modules/library/components/ShareButton.tsx +17 -0
  154. package/src/modules/library/components/SkillsTree.tsx +141 -28
  155. package/src/modules/library/components/TeamRoute.tsx +15 -0
  156. package/src/modules/library/components/__tests__/upload-notices-once-per-page.test.tsx +144 -0
  157. package/src/modules/library/components/plugin-page-parts.tsx +103 -17
  158. package/src/modules/library/components/skill-page/SharedViaPlugins.tsx +6 -12
  159. package/src/modules/library/components/skill-page/SkillFilePane.tsx +5 -0
  160. package/src/modules/library/components/skill-page/SkillPage.tsx +274 -122
  161. package/src/modules/library/components/tool-page/DeleteToolDialog.tsx +218 -0
  162. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +79 -178
  163. package/src/modules/library/components/tool-page/ToolPage.tsx +106 -16
  164. package/src/modules/library/components/tool-page/ToolVarRow.tsx +42 -41
  165. package/src/modules/library/hooks/__tests__/useLibraryData.test.ts +98 -0
  166. package/src/modules/library/hooks/useLibraryData.ts +92 -19
  167. package/src/modules/library/routes/LibraryRoutes.tsx +14 -11
  168. package/src/modules/library/routes/WorkspaceItemRoute.tsx +77 -27
  169. package/src/modules/library/routes/library-paths.ts +26 -28
  170. package/src/modules/library/services/library.api.ts +38 -20
  171. package/src/modules/library/services/plugins.api.ts +69 -8
  172. package/src/modules/library/services/teams.api.ts +15 -0
  173. package/src/modules/library/services/tools.api.ts +78 -0
  174. package/src/modules/library/state/library-data.tsx +170 -32
  175. package/src/modules/library/utils/personal-plugin.ts +13 -15
  176. package/src/modules/library/utils/plugin-entries.ts +134 -0
  177. package/src/modules/library/utils/plugin-summary.ts +75 -9
  178. package/src/modules/library/utils/status.ts +135 -33
  179. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +8 -1
  180. package/src/modules/onboarding/__tests__/onboarding.test.tsx +853 -760
  181. package/src/modules/onboarding/agent-clients.ts +55 -23
  182. package/src/modules/onboarding/components/ConnectAgentPill.tsx +5 -1
  183. package/src/modules/onboarding/components/WelcomePage.tsx +98 -62
  184. package/src/modules/pr/services/pr-merge.api.ts +2 -1
  185. package/src/modules/review/components/MarkdownDiffViewer.tsx +53 -8
  186. package/src/modules/review/components/ReviewPanel.tsx +15 -17
  187. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +64 -0
  188. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +25 -1
  189. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +454 -117
  190. package/src/modules/secrets-vault/components/SecretsPage.tsx +48 -7
  191. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +84 -5
  192. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +425 -0
  193. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +417 -82
  194. package/src/modules/secrets-vault/components/__tests__/ToolSecretsPanel.test.tsx +105 -0
  195. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +407 -0
  196. package/src/modules/secrets-vault/probe/SavedKeyProbeResult.tsx +98 -0
  197. package/src/modules/secrets-vault/probe/__tests__/probe-verdict.test.ts +160 -0
  198. package/src/modules/secrets-vault/probe/probe-verdict.ts +108 -0
  199. package/src/modules/secrets-vault/probe/useSavedKeyProbe.ts +228 -0
  200. package/src/modules/secrets-vault/services/connect.api.ts +36 -5
  201. package/src/modules/secrets-vault/utils/connect-status.ts +98 -0
  202. package/src/modules/settings/components/ClaudeConnectionCard.tsx +9 -24
  203. package/src/modules/settings/components/ClaudeConnectionFields.tsx +23 -0
  204. package/src/modules/settings/components/DeploymentPage.tsx +10 -30
  205. package/src/modules/settings/components/MarketplaceSection.tsx +152 -0
  206. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +67 -4
  207. package/src/modules/settings/components/__tests__/MarketplaceSection.test.tsx +325 -0
  208. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +7 -6
  209. package/src/modules/settings/services/github-facade.api.ts +23 -0
  210. package/src/modules/settings/settings-nav-items.tsx +13 -3
  211. package/src/modules/setup/__tests__/setup.oidc.test.tsx +172 -0
  212. package/src/modules/setup/__tests__/setup.probe-refusal.test.tsx +123 -0
  213. package/src/modules/setup/__tests__/setup.test.tsx +497 -4
  214. package/src/modules/setup/__tests__/useSetupStatus.test.tsx +130 -0
  215. package/src/modules/setup/components/SetupGate.tsx +16 -16
  216. package/src/modules/setup/components/SetupScreen.tsx +532 -43
  217. package/src/modules/setup/hooks/useSetupStatus.ts +93 -0
  218. package/src/modules/setup/services/setup.api.ts +141 -4
  219. package/src/modules/setup/utils/__tests__/root-folders.test.ts +72 -0
  220. package/src/modules/setup/utils/root-folders.ts +46 -0
  221. package/src/modules/toolbar/assets/claude-setup/01-add-manually.webp +0 -0
  222. package/src/modules/toolbar/assets/claude-setup/02-add-configuration.webp +0 -0
  223. package/src/modules/toolbar/assets/claude-setup/03-connect-account.webp +0 -0
  224. package/src/modules/toolbar/assets/claude-setup/04-pick-instance.webp +0 -0
  225. package/src/modules/toolbar/assets/claude-setup/05-plugins-add.webp +0 -0
  226. package/src/modules/toolbar/assets/claude-setup/06-add-marketplace.webp +0 -0
  227. package/src/modules/toolbar/assets/claude-setup/07-paste-url-sync.webp +0 -0
  228. package/src/modules/toolbar/assets/claude-setup/08-install-plugins.webp +0 -0
  229. package/src/modules/toolbar/assets/claude-setup/09-select-repository.webp +0 -0
  230. package/src/modules/toolbar/assets/claude-setup/10-connector-not-added.webp +0 -0
  231. package/src/modules/toolbar/assets/claude-setup/11-add-custom-connector.webp +0 -0
  232. package/src/modules/toolbar/assets/claude-setup/README.md +68 -0
  233. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +296 -0
  234. package/src/modules/toolbar/components/ClaudeMarketplaceCarousel.tsx +107 -0
  235. package/src/modules/toolbar/components/ClaudeRegistrationSteps.tsx +127 -0
  236. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +100 -0
  237. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +177 -118
  238. package/src/modules/toolbar/components/ScreenshotStep.tsx +77 -0
  239. package/src/modules/toolbar/components/SetupCarousel.tsx +177 -0
  240. package/src/modules/toolbar/components/__tests__/AgentInstructionsCard.test.tsx +370 -0
  241. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +542 -42
  242. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +2 -2
  243. package/src/modules/toolbar/components/__tests__/claude-setup-shots.test.ts +104 -0
  244. package/src/modules/toolbar/components/claude-connector-slide.tsx +38 -0
  245. package/src/modules/toolbar/components/claude-setup-shots.ts +167 -0
  246. package/src/modules/toolbar/components/deployment-address.ts +29 -0
  247. package/src/modules/toolbar/components/setup-step-parts.tsx +35 -0
  248. package/src/modules/toolbar/services/__tests__/agent-instructions.api.test.ts +89 -0
  249. package/src/modules/toolbar/services/agent-instructions.api.ts +167 -0
  250. package/src/modules/toolbar/services/external-api-keys.api.ts +8 -0
  251. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +43 -0
  252. package/src/modules/workflow/state/EventBusProvider.tsx +122 -11
  253. package/src/modules/workflow/state/__tests__/EventBusProvider.storage.test.tsx +87 -0
  254. package/src/modules/workflow/state/__tests__/EventBusProvider.watch.test.tsx +223 -0
  255. package/src/modules/workflow/state/event-bus.context.ts +10 -0
  256. package/src/modules/workspace/__tests__/testFixtures.ts +5 -3
  257. package/src/modules/workspace/components/FileExplorer.tsx +1295 -191
  258. package/src/modules/workspace/components/FileRoute.tsx +353 -36
  259. package/src/modules/workspace/components/FileViewer.tsx +172 -46
  260. package/src/modules/workspace/components/KbDocumentShell.tsx +50 -6
  261. package/src/modules/workspace/components/KbPageHeader.tsx +120 -55
  262. package/src/modules/workspace/components/TreeActionConfirm.tsx +350 -0
  263. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +2533 -129
  264. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +731 -18
  265. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +381 -12
  266. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +39 -0
  267. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +33 -20
  268. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +4 -5
  269. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +13 -4
  270. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +4 -3
  271. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +8 -14
  272. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +75 -16
  273. package/src/modules/workspace/components/renderers/KbImage.tsx +180 -0
  274. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +22 -6
  275. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +48 -22
  276. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +4 -5
  277. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +4 -3
  278. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +4 -3
  279. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +12 -0
  280. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +57 -9
  281. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +13 -1
  282. package/src/modules/workspace/components/renderers/__tests__/ImageRenderer.test.tsx +163 -0
  283. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +237 -0
  284. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +108 -14
  285. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +14 -1
  286. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +16 -1
  287. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +66 -1
  288. package/src/modules/workspace/components/renderers/index.ts +53 -2
  289. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +25 -4
  290. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +40 -0
  291. package/src/modules/workspace/hooks/__tests__/useImageRevision.test.tsx +174 -0
  292. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +179 -1
  293. package/src/modules/workspace/hooks/__tests__/useWorkspaceImageResolver.test.tsx +122 -0
  294. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +892 -7
  295. package/src/modules/workspace/hooks/useImageRevision.ts +101 -0
  296. package/src/modules/workspace/hooks/useMergedWorkspaceTree.ts +22 -3
  297. package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +55 -0
  298. package/src/modules/workspace/hooks/useWorkspaceState.ts +424 -66
  299. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +279 -3
  300. package/src/modules/workspace/routing/kb-routes.ts +206 -29
  301. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +134 -1
  302. package/src/modules/workspace/services/workspace.api.ts +57 -4
  303. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +343 -0
  304. package/src/modules/workspace/state/__tests__/upload-lands-where-it-was-dropped.test.tsx +158 -0
  305. package/src/modules/workspace/state/open-change-requests.tsx +100 -12
  306. package/src/modules/workspace/state/workspace.context.ts +125 -19
  307. package/src/modules/workspace/utils/__tests__/file-trace.test.ts +73 -0
  308. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +220 -6
  309. package/src/modules/workspace/utils/__tests__/pasteLink.test.ts +76 -0
  310. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +364 -0
  311. package/src/modules/workspace/utils/__tests__/uploadError.test.ts +35 -0
  312. package/src/modules/workspace/utils/file-trace.ts +50 -0
  313. package/src/modules/workspace/utils/fileTree.ts +112 -36
  314. package/src/modules/workspace/utils/frontmatter.ts +8 -4
  315. package/src/modules/workspace/utils/pasteLink.ts +90 -0
  316. package/src/modules/workspace/utils/treeConfirm.ts +338 -0
  317. package/src/modules/workspace/utils/uploadError.ts +29 -0
  318. package/src/shared/__tests__/marketplace-url.test.ts +6 -1
  319. package/src/shared/components/Button.tsx +16 -2
  320. package/src/shared/components/Dialog.tsx +27 -11
  321. package/src/shared/components/Menu.tsx +13 -1
  322. package/src/shared/components/PageShell.tsx +13 -8
  323. package/src/shared/components/__tests__/primitives.test.tsx +116 -2
  324. package/src/shared/components/__tests__/useFocusHandoff.test.tsx +192 -0
  325. package/src/shared/components/index.ts +2 -0
  326. package/src/shared/components/useDismissableMenu.ts +32 -10
  327. package/src/shared/components/useFocusHandoff.ts +51 -0
  328. package/src/shared/components/useLatestRef.ts +28 -0
  329. package/src/shared/markdown/Markdown.tsx +12 -3
  330. package/src/shared/markdown/__tests__/escapeSpacesInLinkDestinations.test.ts +39 -0
  331. package/src/shared/markdown/hrefs.ts +50 -0
  332. package/src/shared/marketplace-url.ts +33 -5
  333. package/src/shared/mcp/ChatGptInstallLink.tsx +3 -3
  334. package/src/shared/mcp/ConnectionInstructions.tsx +38 -27
  335. package/src/shared/mcp/__tests__/connect-snippets.test.ts +3 -3
  336. package/src/shared/mcp/connect-snippets.ts +14 -9
  337. package/src/shared/mcp/index.ts +1 -1
  338. package/src/shared/theme/__tests__/header-band.test.ts +197 -0
  339. package/src/shared/theme/header.ts +75 -0
  340. package/src/shared/theme/measure.ts +7 -4
  341. package/src/shared/theme/tokens.css +25 -0
  342. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +0 -363
  343. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +0 -97
  344. package/src/modules/library/components/PluginsIndexPage.tsx +0 -270
  345. package/src/modules/update-check/__tests__/UpdateBanner.test.tsx +0 -126
  346. package/src/modules/update-check/components/UpdateBanner.tsx +0 -92
  347. package/src/modules/update-check/services/update-check.api.ts +0 -24
@@ -1,4 +1,5 @@
1
1
  import {
2
+ Fragment,
2
3
  useCallback,
3
4
  useEffect,
4
5
  useLayoutEffect,
@@ -6,16 +7,29 @@ import {
6
7
  useRef,
7
8
  useState,
8
9
  type ReactNode,
10
+ type RefObject,
9
11
  } from 'react';
10
- import { X, Lock, Loader2, ChevronDown, Check, Globe } from 'lucide-react';
11
- import type { FileTreeEntry } from '@bevel-software/platform-shared';
12
+ import { X, Lock, Loader2, ChevronDown, Check, Globe, CircleHelp } from 'lucide-react';
13
+ import {
14
+ canCarryFrontmatter,
15
+ conferredByOthers,
16
+ effectiveVerbs,
17
+ folderGovernsAccessMessage,
18
+ KNOWN_VERBS,
19
+ minimalGrantVerbs,
20
+ VERBS_BROADEST_FIRST,
21
+ type FileTreeEntry,
22
+ type VerbSet,
23
+ } from '@bevel-software/platform-shared';
12
24
  import {
13
25
  Badge,
14
26
  Banner,
15
27
  Button,
16
28
  Dialog,
29
+ IconButton,
17
30
  MenuItem,
18
31
  MenuPanel,
32
+ useDismissableMenu,
19
33
  } from '../../../shared/components';
20
34
  import { useWorkspace } from '../../workspace/state/workspace.context';
21
35
  import { useAuth } from '../../auth/state/auth.context';
@@ -32,13 +46,15 @@ import {
32
46
  asInheritedError,
33
47
  type AccessEligible,
34
48
  type AccessResponse,
49
+ type AccessUser,
50
+ type DenialSources,
35
51
  type GrantVerb,
36
52
  type GrantSource,
37
53
  type GrantSources,
38
54
  type Principal,
39
55
  type SuggestResponse,
40
56
  } from '../api';
41
- import { EMAIL_RE } from '../../../lib/email';
57
+ import { EMAIL_RE, initials, labelInitials } from '../../../lib/email';
42
58
 
43
59
  interface Props {
44
60
  entry: FileTreeEntry;
@@ -66,18 +82,91 @@ interface Props {
66
82
  * fallback, not a silent no-op.
67
83
  */
68
84
  onManageAncestor?: (entry: FileTreeEntry) => void;
85
+ /**
86
+ * The target exists only on an open change request's branch. Access is then
87
+ * read and written on THAT branch — the rules land in the proposed file and
88
+ * merge with it — and the sheet says so. Takes precedence over `workspaceId`.
89
+ * `branch: null` (the request could not be resolved) refuses to load rather
90
+ * than falling back to a workspace the file does not exist on.
91
+ */
92
+ proposal?: { number: number; branch: string | null };
69
93
  }
70
94
 
71
95
  type Role = 'Owner' | 'Can edit' | 'Can read' | 'Can download';
72
96
 
73
- /** Which verbs a principal holds at the target (independent flags). */
74
- interface VerbSet {
75
- owner: boolean;
76
- write: boolean;
77
- read: boolean;
78
- download: boolean;
97
+ // `VerbSet` — which verbs a principal holds at the target — and every fold
98
+ // over it (`effectiveVerbs`, `conferredByOthers`, `minimalGrantVerbs`,
99
+ // `VERBS_BROADEST_FIRST`) come from `platform-shared`: the same table the
100
+ // resolver reads, so this sheet can never disagree with it about what an
101
+ // owner may do or which lines a set needs.
102
+
103
+ /** The three tiers a row can sit at, broadest first; download is not one of them. */
104
+ type Tier = 'Owner' | 'Can edit' | 'Can read';
105
+ const TIERS: Tier[] = ['Owner', 'Can edit', 'Can read'];
106
+
107
+ /** The tier a set sits at — its highest held one — or null when it holds nothing (a denied row). */
108
+ function tierOf(v: VerbSet): Tier | null {
109
+ return v.owner ? 'Owner' : v.write ? 'Can edit' : v.read ? 'Can read' : null;
79
110
  }
80
111
 
112
+ /**
113
+ * The set a row ends up with after a click on one item of its menu, or null
114
+ * when the item has nothing to do from where the row is (the item renders
115
+ * disabled). The dialog then writes the DIFFERENCE between that set and what
116
+ * the principal effectively has here (denials for what the set drops, grants
117
+ * for what it adds — see `doApplyVerbSet`).
118
+ *
119
+ * The menu is TWO AXES, which is what its separator has always drawn, and a
120
+ * click moves one axis and leaves the other where it is:
121
+ *
122
+ * - Owner / Can edit / Can read are one exclusive tier. An unchecked tier is
123
+ * where the row goes; the held tier steps DOWN one (Owner → Can edit → Can
124
+ * read), which is what "unticking" the top of a nested set can mean. Can
125
+ * read at the top has nothing below it — taking read away is what Remove
126
+ * and Deny are for — so it is disabled there.
127
+ * - Can download toggles on its own. Under Owner it is conferred, not chosen,
128
+ * so it is disabled there; and a step down from Owner writes nothing for
129
+ * it either way (see the return). Turning it on carries read, the
130
+ * resolver's own fold (a person trusted with a copy may open it).
131
+ *
132
+ * Each item used to apply a fixed whole set instead — Can edit meant "edit and
133
+ * no download", Can download meant "download and no edit" — so raising one axis
134
+ * silently wrote a revoke or a denial on the other. That is the bug this
135
+ * function replaces.
136
+ */
137
+ function nextVerbSet(current: VerbSet, role: Role): VerbPick | null {
138
+ if (role === 'Can download') {
139
+ if (current.owner) return null;
140
+ // The fold supplies whatever the toggled download carries (read).
141
+ return effectiveVerbs({ ...current, download: !current.download });
142
+ }
143
+ const held = tierOf(current);
144
+ const target: Tier | null =
145
+ role === held ? (TIERS[TIERS.indexOf(role) + 1] ?? null) : role;
146
+ if (target === null) return null;
147
+ // Below Owner the download axis keeps what the row chose. A row coming DOWN
148
+ // from Owner is left to the file: the download it shows may be the owner
149
+ // line's fold (gone with that line) or a line of its own (which stays), and
150
+ // the view cannot tell the two apart — so nothing is revoked or granted for
151
+ // it, and the fresh view says which it was.
152
+ const leaveDownloadToFile = current.owner && target !== 'Owner';
153
+ const next = effectiveVerbs({
154
+ owner: target === 'Owner',
155
+ write: target === 'Can edit',
156
+ read: target === 'Can read',
157
+ download: !leaveDownloadToFile && current.download,
158
+ });
159
+ return leaveDownloadToFile ? { ...next, download: undefined } : next;
160
+ }
161
+
162
+ /**
163
+ * A destination for one row, as `nextVerbSet` states it: the three tier verbs
164
+ * always, and `download` either stated or LEFT OUT — "write nothing for this
165
+ * verb; whatever the file says after the other writes stands". The apply loop
166
+ * neither drops nor grants an omitted verb.
167
+ */
168
+ type VerbPick = Omit<VerbSet, 'download'> & { download?: boolean };
169
+
81
170
  interface PrincipalRow {
82
171
  key: string;
83
172
  label: string;
@@ -90,54 +179,108 @@ interface PrincipalRow {
90
179
  */
91
180
  kind: 'user' | 'role' | 'group' | 'plugin';
92
181
  isYou: boolean;
182
+ /**
183
+ * For a person row: whether an account exists for the email yet. `false`
184
+ * earns the "hasn't signed in yet" note beside the name — the grant is
185
+ * real and unaffected either way. `undefined` means the server did not say
186
+ * (an older build), which is NOT the same as "no account" and shows
187
+ * nothing.
188
+ */
189
+ hasAccount?: boolean;
93
190
  /** The principal to send on grant / revoke. */
94
191
  principal: Principal;
95
192
  /** Per-verb origin of this row's access (from the resolver). */
96
193
  sources?: GrantSources;
97
194
  /**
98
- * How this row may be managed HERE, derived from `sources` (now MECE —
99
- * every source is `direct` or `ancestor`):
100
- * - 'direct' — ≥1 verb is granted directly on the target; the verb
101
- * editor is shown and Remove acts in place.
102
- * - 'inherited' — ≥1 verb comes from an ancestor folder (and none direct);
103
- * Remove opens the "Remove from parent?" flow.
104
- * - 'external' — no file-backed source for any verb (a defensive fallback;
195
+ * Per-verb origin of this row's RESTRICTIONS — where each verb the principal
196
+ * does not hold is denied. A `direct` entry is a denial written on this
197
+ * target: the row's "restricted here", and what the menu lifts when a higher
198
+ * set is picked.
199
+ */
200
+ denials?: DenialSources;
201
+ /**
202
+ * How this row may be managed HERE, derived from its local ENTRIES — grants
203
+ * and denials alike (both MECE: every source is `direct` or `ancestor`):
204
+ * - 'direct' — ≥1 verb is granted, or denied, directly on the target.
205
+ * The row belongs to this folder's own list, and Remove
206
+ * acts in place.
207
+ * - 'inherited' — every entry naming this principal lives in an ancestor
208
+ * folder; Remove opens the "Remove from parent?" flow.
209
+ * - 'external' — no file-backed entry for any verb (a defensive fallback;
105
210
  * a real grantee row always resolves to direct/ancestor,
106
211
  * since rows are built from file-named principals). Shown
107
- * read-only with no Remove.
212
+ * with the menu but no Remove.
213
+ *
214
+ * A DENIAL counts as a local entry, and that is the whole point: a person
215
+ * restricted here has no local grant left, and classifying on grants alone
216
+ * dropped them into the collapsed inherited section looking removed.
108
217
  */
109
218
  manage: 'direct' | 'inherited' | 'external';
110
- /** The distinct ancestor access.md path(s) this row inherits any verb from. */
219
+ /**
220
+ * The distinct ancestor access.md path(s) holding ANY entry for this row —
221
+ * where the rules naming this principal live, which is what "via Sales" and
222
+ * the parent-folder grouping report.
223
+ */
111
224
  ancestors: string[];
225
+ /**
226
+ * The subset of those that GRANT — the only ones "Remove from <folder>" can
227
+ * act on. An ancestor that merely denies is not where this person's access
228
+ * comes from, and revoking them there would LIFT a restriction in answer to a
229
+ * click that asked to remove access.
230
+ */
231
+ grantAncestors: string[];
232
+ /** True when every verb is denied by an entry on this target — "Denied here". */
233
+ deniedHere: boolean;
234
+ }
235
+
236
+ /** The four grant verbs, for whole-set reasoning. */
237
+ const ALL_VERBS: readonly GrantVerb[] = KNOWN_VERBS;
238
+
239
+ /** Every source list in a per-verb map, empty entries dropped. */
240
+ function sourceLists(map: GrantSources | DenialSources | undefined): GrantSource[][] {
241
+ return map ? Object.values(map).filter((l): l is GrantSource[] => !!l && l.length > 0) : [];
242
+ }
243
+
244
+ /** The distinct ancestor `access.md` paths named across per-verb source maps. */
245
+ function ancestorPaths(...maps: (GrantSources | DenialSources | undefined)[]): string[] {
246
+ return [
247
+ ...new Set(
248
+ maps
249
+ .flatMap(sourceLists)
250
+ .flatMap((l) => l.filter((s) => s.kind === 'ancestor').map((s) => s.path)),
251
+ ),
252
+ ];
112
253
  }
113
254
 
114
255
  /**
115
- * Classify a row's manageability from its per-verb sources (now MECE — every
116
- * source is `direct` or `ancestor`):
117
- * - any `direct` verb → 'direct' (editable in place).
118
- * - else any `ancestor` verb → 'inherited' (remove-from-parent / deny-here).
119
- * - else (no source for any verb) → 'external' (defensive fallback; a real
120
- * grantee row always has a file source, since rows are built from
121
- * file-named principals).
256
+ * Classify a row's manageability from its per-verb entries — grants AND
257
+ * denials, because a restriction is as much an entry on this target as a grant:
258
+ * - any verb granted directly, or denied directly → 'direct' (this folder's
259
+ * own list; the row is edited in place).
260
+ * - else any ancestor entry → 'inherited' (remove-from-parent / restrict here).
261
+ * - else no entry at all → 'external' (defensive fallback; a real grantee row
262
+ * always has a file entry, since rows are built from file-named principals).
122
263
  */
123
- function classifyManage(sources: GrantSources | undefined): {
124
- manage: 'direct' | 'inherited' | 'external';
125
- ancestors: string[];
126
- } {
127
- const lists = sources ? Object.values(sources).filter((l): l is GrantSource[] => !!l) : [];
128
- // A row is 'direct' (editable in place) when ANY verb's WINNING source (the
129
- // closest, `[0]`) is direct — even if that same verb is ALSO inherited from a
130
- // parent (`[direct, ancestor]`); the inherited tail still feeds `ancestors`
131
- // below, so Remove can chain to the parent after stripping the direct entry.
132
- const hasDirectWinner = lists.some((l) => l[0]?.kind === 'direct');
133
- // Every ancestor named for any verb (including the tails of direct+ancestor
134
- // verbs), so the confirm flow knows all the parents to offer.
135
- const ancestors = [
136
- ...new Set(lists.flatMap((l) => l.filter((s) => s.kind === 'ancestor').map((s) => (s as { path: string }).path))),
137
- ];
138
- if (hasDirectWinner) return { manage: 'direct', ancestors };
139
- if (ancestors.length > 0) return { manage: 'inherited', ancestors };
140
- return { manage: 'external', ancestors: [] };
264
+ function classifyManage(
265
+ sources: GrantSources | undefined,
266
+ denials: DenialSources | undefined,
267
+ ): { manage: 'direct' | 'inherited' | 'external'; ancestors: string[]; grantAncestors: string[] } {
268
+ // A row is 'direct' when ANY verb's WINNING grant source (the closest, `[0]`)
269
+ // is direct — even if that verb is ALSO inherited (`[direct, ancestor]`); the
270
+ // inherited tail still feeds `ancestors`, so Remove can chain to the parent
271
+ // after stripping the direct entry. A direct DENIAL counts the same way: it is
272
+ // a rule this target holds about this principal.
273
+ const hasLocalEntry =
274
+ sourceLists(sources).some((l) => l[0]?.kind === 'direct') ||
275
+ sourceLists(denials).some((l) => l.some((s) => s.kind === 'direct'));
276
+ const ancestors = ancestorPaths(sources, denials);
277
+ // Kept apart from `ancestors` on purpose: an ancestor DENIAL is a real entry
278
+ // (it classifies the row, and it is where the rule lives) but it is not a
279
+ // place access can be removed from.
280
+ const grantAncestors = ancestorPaths(sources);
281
+ if (hasLocalEntry) return { manage: 'direct', ancestors, grantAncestors };
282
+ if (ancestors.length > 0) return { manage: 'inherited', ancestors, grantAncestors };
283
+ return { manage: 'external', ancestors: [], grantAncestors: [] };
141
284
  }
142
285
 
143
286
  /**
@@ -147,7 +290,7 @@ function classifyManage(sources: GrantSources | undefined): {
147
290
  */
148
291
  function folderLabel(accessMdPath: string): string {
149
292
  const dir = accessMdPath.replace(/\/?access\.md$/, '');
150
- if (dir === '') return 'the root folder';
293
+ if (dir === '') return WHOLE_WORKSPACE;
151
294
  const segs = dir.split('/');
152
295
  return segs[segs.length - 1];
153
296
  }
@@ -155,7 +298,58 @@ function folderLabel(accessMdPath: string): string {
155
298
  /** The full folder path (for a hover title), repo-relative. */
156
299
  function folderPath(accessMdPath: string): string {
157
300
  const dir = accessMdPath.replace(/\/?access\.md$/, '');
158
- return dir === '' ? 'the root folder' : dir;
301
+ return dir === '' ? WHOLE_WORKSPACE : dir;
302
+ }
303
+
304
+ /**
305
+ * What the repository root is called to a business user. "The root folder" is
306
+ * a repository word; a grant at the root reaches everything in the workspace,
307
+ * and that is what the reader needs to know.
308
+ */
309
+ const WHOLE_WORKSPACE = 'the whole workspace';
310
+
311
+ /** True when an ancestor `access.md` path is the repository root's. */
312
+ function isRootAccessMd(accessMdPath: string): boolean {
313
+ return accessMdPath.replace(/\/?access\.md$/, '') === '';
314
+ }
315
+
316
+ /**
317
+ * One line per kind of grantee, in business words. Shown together behind the
318
+ * "What can I share with?" control, and one at a time as the tooltip and
319
+ * accessible description of the group / role / plugin tags, so each word is
320
+ * explained where it is met.
321
+ */
322
+ const PRINCIPAL_KIND_HELP = {
323
+ user: 'People: one person, by email.',
324
+ group:
325
+ 'Groups: a way to group people together and give them access in the app. A group can be a team or department, like Engineering, or a functional group, like skill reviewers.',
326
+ role: 'Roles: special app roles that give people extra abilities in the app. They are pre-defined; you can only add or remove people. Example: Admin, which opens the platform and user management screens.',
327
+ plugin: 'Plugins: the readers, writers or owners of a plugin, whoever they are at the time.',
328
+ } as const satisfies Record<Principal['kind'], string>;
329
+
330
+ /**
331
+ * What a person with no account yet is called, beside their chip and beside
332
+ * their row. Granting ahead of a first sign-in is supported and stays
333
+ * supported — under single sign-on the account is created BY that sign-in —
334
+ * so this is a LABEL, never a warning and never a refusal: the grant saves
335
+ * exactly as any other. It is here so a mistyped address is visible, and it
336
+ * disappears on its own the first time that person signs in.
337
+ */
338
+ const NO_ACCOUNT_NOTE = "hasn't signed in yet";
339
+ const NO_ACCOUNT_HELP =
340
+ 'No account for this email yet. The grant is saved and takes effect the moment they first sign in — if you did not expect this, check the spelling.';
341
+
342
+ /** The note itself — muted and small, the same weight as a row's second line. */
343
+ function NoAccountNote() {
344
+ return (
345
+ <span
346
+ className="shrink-0 whitespace-nowrap text-detail italic text-ink-faint"
347
+ title={NO_ACCOUNT_HELP}
348
+ aria-description={NO_ACCOUNT_HELP}
349
+ >
350
+ {NO_ACCOUNT_NOTE}
351
+ </span>
352
+ );
159
353
  }
160
354
 
161
355
  /**
@@ -188,20 +382,22 @@ function lookupSources(
188
382
  return sources?.[key] ?? (key.startsWith('g:') ? sources?.[`r:${key.slice(2)}`] : undefined);
189
383
  }
190
384
 
191
- /** The distinct ancestor `access.md` path(s) named across a per-verb sources map. */
192
- function ancestorsFromSources(sources: GrantSources | undefined): string[] {
193
- if (!sources) return [];
194
- return [
195
- ...new Set(
196
- Object.values(sources)
197
- .filter((l): l is GrantSource[] => !!l)
198
- .flatMap((l) => l.filter((s) => s.kind === 'ancestor').map((s) => (s as { path: string }).path)),
199
- ),
200
- ];
385
+ /** Look a row/principal key up in a response's `denials` map, same `g:` fallback. */
386
+ function lookupDenials(
387
+ denials: AccessResponse['denials'] | undefined,
388
+ key: string,
389
+ ): DenialSources | undefined {
390
+ return denials?.[key] ?? (key.startsWith('g:') ? denials?.[`r:${key.slice(2)}`] : undefined);
201
391
  }
202
392
 
203
393
  /** The checklist order; download is independent and rendered separately. */
204
- const TIER_ROLES: Role[] = ['Owner', 'Can edit', 'Can read'];
394
+ const TIER_ROLES: Role[] = TIERS;
395
+
396
+ /**
397
+ * A row's verb menu, top to bottom — the tiers, then download, then (added by
398
+ * the row itself) Deny. Broadest first, so "less than this" reads downwards.
399
+ */
400
+ const MENU_ROLES: Role[] = [...TIER_ROLES, 'Can download'];
205
401
 
206
402
  /**
207
403
  * Muted identity tones (bg/fg pairs) — the same family as the Library's
@@ -217,13 +413,6 @@ const AVATAR_TONES = [
217
413
  { bg: '#faf0e2', fg: '#8a6a2f' },
218
414
  ];
219
415
 
220
- function initials(label: string): string {
221
- const parts = label.replace(/[<>]/g, '').trim().split(/[\s@.]+/).filter(Boolean);
222
- if (parts.length === 0) return '?';
223
- if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
224
- return (parts[0][0] + parts[1][0]).toUpperCase();
225
- }
226
-
227
416
  function avatarTone(seed: string): { bg: string; fg: string } {
228
417
  let h = 0;
229
418
  for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
@@ -259,7 +448,12 @@ function isEveryoneRole(p: Principal): boolean {
259
448
  return p.kind === 'role' && p.role.trim().toLowerCase() === 'everyone';
260
449
  }
261
450
 
262
- /** A short summary of the verbs a row holds, for the dropdown trigger. */
451
+ /**
452
+ * A short summary of the verbs a row holds, for the dropdown trigger. Read is
453
+ * folded in by write/owner/download before a `VerbSet` reaches here (see
454
+ * `effectiveNewVerbs` and the row aggregation), so a download-only grant reads
455
+ * “Can read, Can download” — what the resolver actually gives.
456
+ */
263
457
  function summarizeVerbs(v: VerbSet): string {
264
458
  const parts: string[] = [];
265
459
  if (v.owner) parts.push('Owner');
@@ -269,6 +463,37 @@ function summarizeVerbs(v: VerbSet): string {
269
463
  return parts.length ? parts.join(', ') : 'No access';
270
464
  }
271
465
 
466
+ /**
467
+ * What a row's verb menu says beside ONE verb: where it comes from, or why it
468
+ * is off. Short enough to sit in a menu item without wrapping — the leaf folder
469
+ * name, as everywhere else in the sheet.
470
+ *
471
+ * - held from a parent → "from Sales"
472
+ * - denied by an entry here → "restricted here" (the restriction this ticket
473
+ * exists to make visible; picking a set that
474
+ * includes the verb lifts it)
475
+ * - denied by a parent → "restricted in Sales"
476
+ * - held by an entry here, or simply never granted → nothing to explain.
477
+ */
478
+ function verbNote(row: PrincipalRow, verb: GrantVerb): string | undefined {
479
+ if (row.verbs[verb]) {
480
+ const winner = (row.sources?.[verb] ?? [])[0];
481
+ return winner?.kind === 'ancestor' ? `from ${folderLabel(winner.path)}` : undefined;
482
+ }
483
+ const denial = (row.denials?.[verb] ?? [])[0];
484
+ if (!denial) return undefined;
485
+ return denial.kind === 'direct' ? 'restricted here' : `restricted in ${folderLabel(denial.path)}`;
486
+ }
487
+
488
+ /**
489
+ * What a row's menu trigger reads. A wholly denied principal is not "No access"
490
+ * — that is what someone never named here would look like. It is a decision
491
+ * somebody made on this target, and the row says so.
492
+ */
493
+ function rowSummary(row: PrincipalRow): string {
494
+ return row.deniedHere ? 'Denied here' : summarizeVerbs(row.verbs);
495
+ }
496
+
272
497
  /** Gap between a trigger and its menu, and the minimum inset from a viewport edge. */
273
498
  const MENU_GAP = 4;
274
499
  const MENU_MARGIN = 8;
@@ -279,6 +504,13 @@ const MENU_MARGIN = 8;
279
504
  * trigger by the difference.
280
505
  */
281
506
  const MENU_MIN_WIDTH = 200;
507
+ /**
508
+ * The most a content-sized menu grows to before its items start truncating.
509
+ * Wide enough for "Can download · from the whole workspace ✓" on one line;
510
+ * narrow enough that a folder with a very long name cannot turn the menu
511
+ * into a banner.
512
+ */
513
+ const MENU_MAX_WIDTH = 360;
282
514
 
283
515
  /**
284
516
  * A dropdown panel that escapes the dialog's scroll container.
@@ -286,7 +518,7 @@ const MENU_MIN_WIDTH = 200;
286
518
  * `Dialog` renders its body inside `overflow-y-auto` so a long access list
287
519
  * scrolls under the pinned header and footer. An ABSOLUTELY positioned menu in
288
520
  * that box is clipped by it: open the verb menu on a low grantee row and
289
- * everything past the first item or two — "Remove access" included — is cut off
521
+ * everything past the first item or two — "Can download" included — is cut off
290
522
  * at the body's edge, unreachable without scrolling the list out from under the
291
523
  * menu.
292
524
  *
@@ -304,11 +536,38 @@ const MENU_MIN_WIDTH = 200;
304
536
  * attached yet when this component's layout effect runs (React attaches refs
305
537
  * bottom-up, children first), so the first placement would silently no-op and
306
538
  * the panel would stay hidden.
539
+ *
540
+ * Dismissal is the caller's to opt into with `onDismiss`. A menu whose open
541
+ * state is a boolean the caller owns (the verb checklists) has to close on an
542
+ * outside click and on Escape, or it sits open until something inside it is
543
+ * picked — a trap for anyone driving the app from the keyboard, and a surprise
544
+ * for everyone else. That is `useDismissableMenu`'s job, plus one thing the
545
+ * hook's own docstring warns it does NOT do: co-exist with the `Dialog` this
546
+ * menu lives in, which also listens for Escape on `document` and would close
547
+ * itself on the same keypress. Registering the open menu as a modal layer
548
+ * makes it the topmost, so `Dialog` stands down until the menu is gone. The
549
+ * suggestion list leaves `onDismiss` unset: its openness is derived from what
550
+ * is typed, not from a flag a click could clear.
307
551
  */
308
552
  function AnchoredMenu({
309
553
  /**
310
- * Panel width in px, or `'anchor'` to match the trigger (the combobox case).
311
- * Clamped up to {@link MENU_MIN_WIDTH} either way.
554
+ * Close the menu. Called on a mousedown outside the panel and its trigger,
555
+ * and on Escape (which also hands focus back to the trigger). Leave unset
556
+ * for a panel whose visibility is not an open flag.
557
+ */
558
+ onDismiss,
559
+ /**
560
+ * The control that opened us. Clicks on it are the trigger's own business
561
+ * (its handler toggles), and Escape returns focus to it. Goes with
562
+ * `onDismiss`; a stable ref, as `useDismissableMenu` lists it in its deps.
563
+ */
564
+ triggerRef,
565
+ /**
566
+ * Panel width in px, `'anchor'` to match the trigger (the combobox case), or
567
+ * `'content'` to fit the widest item (a menu whose items carry notes — "from
568
+ * the whole workspace" — that a trigger-sized panel would truncate the LABEL
569
+ * to make room for). Clamped up to {@link MENU_MIN_WIDTH} either way, and
570
+ * `'content'` is clamped down to {@link MENU_MAX_WIDTH} and the viewport.
312
571
  */
313
572
  width = MENU_MIN_WIDTH,
314
573
  /** Which edge lines up with the anchor's. */
@@ -316,12 +575,24 @@ function AnchoredMenu({
316
575
  className = '',
317
576
  children,
318
577
  }: {
319
- width?: number | 'anchor';
578
+ onDismiss?: () => void;
579
+ triggerRef?: RefObject<HTMLElement | null>;
580
+ width?: number | 'anchor' | 'content';
320
581
  align?: 'left' | 'right';
321
582
  className?: string;
322
583
  children: ReactNode;
323
584
  }) {
324
- const panelRef = useRef<HTMLDivElement>(null);
585
+ const dismissable = onDismiss !== undefined;
586
+ // The hook owns both contracts this component used to carry by hand: it
587
+ // mirrors a fresh `onDismiss` arrow into a ref itself (so its document
588
+ // listeners subscribe once per open menu), and it registers the open menu
589
+ // as a modal layer (so Escape peels it before the Dialog hosting it, and
590
+ // one press never closes two layers).
591
+ const panelRef = useDismissableMenu<HTMLDivElement>({
592
+ open: dismissable,
593
+ onClose: () => onDismiss?.(),
594
+ returnFocusTo: triggerRef,
595
+ });
325
596
  const [pos, setPos] = useState<{ top: number; left: number; width: number } | null>(null);
326
597
 
327
598
  useLayoutEffect(() => {
@@ -331,7 +602,21 @@ function AnchoredMenu({
331
602
  const el = panelRef.current;
332
603
  const anchor = el?.parentElement?.getBoundingClientRect();
333
604
  if (!anchor || !el) return;
334
- const w = Math.max(width === 'anchor' ? anchor.width : width, MENU_MIN_WIDTH);
605
+ let w: number;
606
+ if (width === 'content') {
607
+ // Let the panel take its natural width for one measurement, then pin
608
+ // it: what the widest item needs, within the caps. The observer on
609
+ // the panel sees only the pinned size, which is unchanged whenever the
610
+ // content is, so this does not feed it.
611
+ el.style.width = 'max-content';
612
+ const natural = el.offsetWidth;
613
+ w = Math.max(
614
+ MENU_MIN_WIDTH,
615
+ Math.min(natural, MENU_MAX_WIDTH, window.innerWidth - 2 * MENU_MARGIN),
616
+ );
617
+ } else {
618
+ w = Math.max(width === 'anchor' ? anchor.width : width, MENU_MIN_WIDTH);
619
+ }
335
620
  // Width BEFORE height: the panel wraps and grows taller when narrower, so
336
621
  // measuring at the wrong width picks the wrong side to open on.
337
622
  el.style.width = `${w}px`;
@@ -370,16 +655,25 @@ function AnchoredMenu({
370
655
  const observer = new ResizeObserver(place);
371
656
  if (anchorEl) observer.observe(anchorEl);
372
657
  if (panel) observer.observe(panel);
658
+ // A content-sized panel is PINNED to a width, so the resize observer above
659
+ // cannot see its items change under it — and they do while a row menu
660
+ // stays open across writes: notes ("from Sales") and check marks come and
661
+ // go with each fresh view. Re-measure on any change to what the panel
662
+ // holds. Children and text only, not attributes: `place` writes the
663
+ // panel's own style, which must not re-trigger it.
664
+ const contents = new MutationObserver(place);
665
+ if (panel) contents.observe(panel, { childList: true, subtree: true, characterData: true });
373
666
  window.addEventListener('resize', place);
374
667
  // Capture phase: the dialog body is what scrolls, and scroll events don't
375
668
  // bubble to `window`.
376
669
  window.addEventListener('scroll', place, true);
377
670
  return () => {
378
671
  observer.disconnect();
672
+ contents.disconnect();
379
673
  window.removeEventListener('resize', place);
380
674
  window.removeEventListener('scroll', place, true);
381
675
  };
382
- }, [width, align]);
676
+ }, [width, align, panelRef]);
383
677
 
384
678
  return (
385
679
  <div
@@ -399,6 +693,157 @@ function AnchoredMenu({
399
693
  );
400
694
  }
401
695
 
696
+ /**
697
+ * Every row the sheet shows for one resolved access response — ONE row per
698
+ * principal, carrying its effective verb set, where each held verb comes from,
699
+ * and where each withheld one is denied.
700
+ *
701
+ * A pure function of the response rather than a hook body, because the apply
702
+ * loop re-derives rows from each intermediate server response as it walks a
703
+ * picked set: it has to ask "does the principal still hold write after that
704
+ * call?" between requests, and the answer must come from the same aggregation
705
+ * the UI renders — not a second, subtly different reading of the payload.
706
+ */
707
+ function buildRows(data: AccessResponse | null, myEmail: string): PrincipalRow[] {
708
+ if (!data) return [];
709
+ // Aggregate the resolver lists into ONE row per principal carrying its
710
+ // independent verb set. Membership IS the displayed set — we do NOT subtract
711
+ // the rollup. The resolver already folds owner⊇write⊇read on the lower lists,
712
+ // so an owner legitimately shows owner+write+read checked; download is its own
713
+ // axis (owner folds in, write does not), sourced from `downloaders` — and it
714
+ // folds DOWN into read, so a download row shows read checked too.
715
+ const rows = new Map<string, PrincipalRow>();
716
+ // Kinded collective list for one eligible set. Older servers omit
717
+ // `principals` (version skew) — fall back to the name-only `roles`,
718
+ // treating everything as a role (the pre-groups display).
719
+ const collectivesOf = (list: AccessEligible): ResolvedPrincipal[] =>
720
+ list.principals ?? list.roles.map((name) => ({ name, kind: 'role' as const }));
721
+ const touchCollective = (c: ResolvedPrincipal): PrincipalRow => {
722
+ // Rows are keyed by KIND + name (`g:`/`r:`/`p:`) — the backend treats a
723
+ // bare `Product` (group) and `role/Product` (role) as DIFFERENT
724
+ // principals, so a group and a role sharing a name are two rows, each
725
+ // mutating its own grant. Collapsing them to one row silently pointed
726
+ // every edit at the group and hid the role's grant entirely. A plugin
727
+ // principal's name is its full `plugin/<Name>/<verb>` token.
728
+ const key =
729
+ c.kind === 'group'
730
+ ? `g:${c.name.toLowerCase()}`
731
+ : c.kind === 'plugin'
732
+ ? `p:${c.name.toLowerCase()}`
733
+ : `r:${c.name.toLowerCase()}`;
734
+ let row = rows.get(key);
735
+ if (!row) {
736
+ const plugin = c.kind === 'plugin' ? parsePluginPrincipalToken(c.name) : null;
737
+ row = {
738
+ key,
739
+ label: plugin ? pluginPrincipalLabel(plugin.plugin, plugin.verb) : c.name,
740
+ kind: c.kind,
741
+ isYou: false,
742
+ principal:
743
+ c.kind === 'group'
744
+ ? { kind: 'group', group: c.name }
745
+ : plugin
746
+ ? { kind: 'plugin', plugin: plugin.plugin, verb: plugin.verb }
747
+ : { kind: 'role', role: c.name },
748
+ verbs: { owner: false, write: false, read: false, download: false },
749
+ manage: 'direct',
750
+ ancestors: [],
751
+ grantAncestors: [],
752
+ deniedHere: false,
753
+ };
754
+ rows.set(key, row);
755
+ }
756
+ return row;
757
+ };
758
+ const touchUser = (u: AccessUser): PrincipalRow => {
759
+ const key = `u:${u.email.toLowerCase()}`;
760
+ let row = rows.get(key);
761
+ if (!row) {
762
+ const label = u.name || u.email;
763
+ row = {
764
+ key,
765
+ label,
766
+ // Only a real display name earns the second line — a nameless user
767
+ // would otherwise render the same email twice, burning a row of the
768
+ // scarce width on a duplicate.
769
+ sub: label.toLowerCase() === u.email.toLowerCase() ? undefined : u.email,
770
+ kind: 'user',
771
+ isYou: u.email.toLowerCase() === myEmail,
772
+ // Whoever names this person first wins — the lists are views of the
773
+ // same account, so the flag cannot differ between them.
774
+ hasAccount: u.hasAccount,
775
+ principal: { kind: 'user', email: u.email, displayName: u.name || u.email },
776
+ verbs: { owner: false, write: false, read: false, download: false },
777
+ manage: 'direct',
778
+ ancestors: [],
779
+ grantAncestors: [],
780
+ deniedHere: false,
781
+ };
782
+ rows.set(key, row);
783
+ }
784
+ return row;
785
+ };
786
+
787
+ for (const c of collectivesOf(data.owners)) touchCollective(c).verbs.owner = true;
788
+ for (const u of data.owners.users) touchUser(u).verbs.owner = true;
789
+ for (const c of collectivesOf(data.eligible)) touchCollective(c).verbs.write = true;
790
+ for (const u of data.eligible.users) touchUser(u).verbs.write = true;
791
+ // Read grants are rows whether or not the node is public: on a public
792
+ // node they are what MAKES it public, and a row is the ONE place any
793
+ // grant is removed. The built-in `everyone` is a row like any principal
794
+ // — when a file spells it. A derived everyone (public only through a
795
+ // plugin principal) has no line of its own; the plugin's row is that grant.
796
+ for (const c of collectivesOf(data.readers)) {
797
+ if (c.kind === 'role' && isEveryoneRole({ kind: 'role', role: c.name })) {
798
+ if (!lookupSources(data.sources, 'r:everyone')?.read?.length) continue;
799
+ const row = touchCollective(c);
800
+ row.label = 'Everyone';
801
+ row.verbs.read = true;
802
+ continue;
803
+ }
804
+ touchCollective(c).verbs.read = true;
805
+ }
806
+ for (const u of data.readers.users) touchUser(u).verbs.read = true;
807
+ for (const c of collectivesOf(data.downloaders)) touchCollective(c).verbs.download = true;
808
+ for (const u of data.downloaders.users) touchUser(u).verbs.download = true;
809
+
810
+ // The principals this target RESTRICTS. They hold nothing through it, so no
811
+ // eligible list carries them — and before the server reported them, writing a
812
+ // restriction made the person disappear from the sheet that wrote it. They get
813
+ // a row with an empty verb set; the denial map below supplies the rest.
814
+ for (const c of data.deniedHere?.principals ?? []) {
815
+ const row = touchCollective(c);
816
+ if (c.kind === 'role' && isEveryoneRole({ kind: 'role', role: c.name })) row.label = 'Everyone';
817
+ }
818
+ for (const u of data.deniedHere?.users ?? []) touchUser(u);
819
+
820
+ // Download implies read, the way write does. The server folds it into
821
+ // `readers` too, so this is belt-and-braces for an older backend — but it is
822
+ // also what makes the row's Read box render checked-and-implied next to a
823
+ // Download it cannot be unticked without.
824
+ for (const row of rows.values()) row.verbs = effectiveVerbs(row.verbs);
825
+
826
+ // Attach each row's per-verb grants and denials, and the manageability they
827
+ // imply (direct / inherited / external), keyed by the same row key (with the
828
+ // `g:` → `r:` version-skew fallback for group rows).
829
+ for (const row of rows.values()) {
830
+ row.sources = lookupSources(data.sources, row.key);
831
+ row.denials = lookupDenials(data.denials, row.key);
832
+ const { manage, ancestors, grantAncestors } = classifyManage(row.sources, row.denials);
833
+ row.manage = manage;
834
+ row.ancestors = ancestors;
835
+ row.grantAncestors = grantAncestors;
836
+ // "Denied here" is the whole-principal block: every verb denied by an entry
837
+ // on this target. A partial restriction (edit denied, read still inherited)
838
+ // is emphatically NOT this — it is a lowered set, and says so per verb.
839
+ row.deniedHere = ALL_VERBS.every((v) =>
840
+ (row.denials?.[v] ?? []).some((s) => s.kind === 'direct'),
841
+ );
842
+ }
843
+
844
+ return [...rows.values()];
845
+ }
846
+
402
847
  /**
403
848
  * Google-Drive-style "Manage access" sheet. Reads the resolved access for a KB
404
849
  * path and lets anyone who can write the path's access config share it: add one
@@ -415,15 +860,26 @@ export function ManageAccessDialog({
415
860
  onClose,
416
861
  workspaceId: workspaceIdProp,
417
862
  onManageAncestor,
863
+ proposal,
418
864
  }: Props) {
419
865
  // `kbDirName` stays context-sourced: it names the clone directory, which is
420
866
  // the same on every branch.
421
867
  const { workspaceId: ctxWorkspaceId, kbDirName } = useWorkspace();
422
- const workspaceId = workspaceIdProp ?? ctxWorkspaceId;
868
+ const proposalBranchMissing = !!proposal && !proposal.branch;
869
+ // Workspace ids are the URL-encoded branch name (see `workspaceIdForBranch`).
870
+ const workspaceId = proposal
871
+ ? proposal.branch
872
+ ? encodeURIComponent(proposal.branch)
873
+ : null
874
+ : (workspaceIdProp ?? ctxWorkspaceId);
423
875
  const { user } = useAuth();
424
876
  const [data, setData] = useState<AccessResponse | null>(null);
425
- const [loading, setLoading] = useState(true);
426
- const [error, setError] = useState<string | null>(null);
877
+ const [loading, setLoading] = useState(!proposalBranchMissing);
878
+ const [error, setError] = useState<string | null>(
879
+ proposalBranchMissing
880
+ ? `The branch of change request #${proposal.number} could not be found.`
881
+ : null,
882
+ );
427
883
 
428
884
  // Add-row state. `newVerbs` holds the (independent) verbs to grant the chips;
429
885
  // it mirrors the per-row checklist so a new person can be given several at once.
@@ -441,6 +897,16 @@ export function ManageAccessDialog({
441
897
  const [mutateError, setMutateError] = useState<string | null>(null);
442
898
  // Which existing row's verb checklist is open (one at a time).
443
899
  const [openRowKey, setOpenRowKey] = useState<string | null>(null);
900
+ // The triggers the two verb menus return focus to on Escape. One ref serves
901
+ // every grantee row: only the OPEN row's trigger carries it (one menu at a
902
+ // time), so it always names the button whose menu is on screen.
903
+ const openRowTriggerRef = useRef<HTMLButtonElement>(null);
904
+ const verbTriggerRef = useRef<HTMLButtonElement>(null);
905
+ /** The add row's text field — where the caret goes back to after a pick. */
906
+ const queryInputRef = useRef<HTMLInputElement>(null);
907
+ // The "What can I share with?" explainer beside the add field.
908
+ const [kindHelpOpen, setKindHelpOpen] = useState(false);
909
+ const kindHelpTriggerRef = useRef<HTMLButtonElement>(null);
444
910
  // When set, the "Remove from parent?" confirmation is open for this principal.
445
911
  // `ancestors` are the granting access.md path(s) (repo-relative, opaque) to
446
912
  // echo back on remove-from-parent. `verb` scopes the action to a single verb
@@ -502,6 +968,84 @@ export function ManageAccessDialog({
502
968
  // including the layering that lets the nested "Remove from parent?" modal
503
969
  // take Escape without also closing this one.
504
970
 
971
+ /**
972
+ * The LATEST thing the server said about each email — from a suggestion or
973
+ * from the loaded view, whichever spoke most recently. Not a set of
974
+ * positives: an answer that explicitly says `hasAccount: false` about
975
+ * someone previously reported as having an account (an account erased while
976
+ * this dialog is open) has to be able to take the claim back, which an
977
+ * accumulate-only set cannot do.
978
+ *
979
+ * It IS accumulated across answers rather than read off the current one, so
980
+ * an answer landing after a chip was added still corrects that chip.
981
+ *
982
+ * Version skew: a server that says nothing about a person it has named
983
+ * (`hasAccount === undefined`) is recorded as HAVING an account — silence is
984
+ * not a claim of absence, so an older build labels nobody.
985
+ */
986
+ const [accountStatus, setAccountStatus] = useState<ReadonlyMap<string, boolean>>(
987
+ () => new Map(),
988
+ );
989
+ const learnAccounts = useCallback((people: readonly AccessUser[]) => {
990
+ if (people.length === 0) return;
991
+ setAccountStatus((prev) => {
992
+ let next: Map<string, boolean> | null = null;
993
+ for (const p of people) {
994
+ const email = p.email.trim().toLowerCase();
995
+ if (!email) continue;
996
+ const has = p.hasAccount !== false;
997
+ if (prev.get(email) === has) continue;
998
+ next ??= new Map(prev);
999
+ next.set(email, has);
1000
+ }
1001
+ return next ?? prev;
1002
+ });
1003
+ }, []);
1004
+
1005
+ /**
1006
+ * Addresses an account-aware suggest answer has actually RULED ON — the
1007
+ * queries such an answer came back for, canonical. Absence from `people` is
1008
+ * evidence of "no account" only for one of these: a lookup that failed, or
1009
+ * one served by a build that does not report accounts, says nothing at all,
1010
+ * and a chip must not be labelled on a guess in either case.
1011
+ */
1012
+ const [lookedUp, setLookedUp] = useState<ReadonlySet<string>>(() => new Set());
1013
+ const noteLookedUp = useCallback((email: string) => {
1014
+ setLookedUp((prev) => (prev.has(email) ? prev : new Set(prev).add(email)));
1015
+ }, []);
1016
+
1017
+ /**
1018
+ * Whether a CHIP earns the note. Two ways to know, and nothing else counts:
1019
+ * the server said `hasAccount: false` about that address, or it answered a
1020
+ * lookup of that exact address and did not name it — which, from a build
1021
+ * that reports accounts, is the same fact stated by omission.
1022
+ *
1023
+ * Rows do NOT go through here — a row reads its own `hasAccount` straight
1024
+ * from the view, which always names the person it is a row for.
1025
+ */
1026
+ const lacksAccount = useCallback(
1027
+ (email: string): boolean => {
1028
+ const key = email.trim().toLowerCase();
1029
+ const status = accountStatus.get(key);
1030
+ return status === undefined ? lookedUp.has(key) : !status;
1031
+ },
1032
+ [accountStatus, lookedUp],
1033
+ );
1034
+
1035
+ // The loaded view is the other place accounts are named: someone already
1036
+ // granted here and already signed in must not pick the note up when their
1037
+ // address is typed again, and someone granted here who never signed in
1038
+ // should carry it on the chip as well as on the row.
1039
+ useEffect(() => {
1040
+ if (!data) return;
1041
+ learnAccounts([
1042
+ ...data.eligible.users,
1043
+ ...data.readers.users,
1044
+ ...data.owners.users,
1045
+ ...data.downloaders.users,
1046
+ ]);
1047
+ }, [data, learnAccounts]);
1048
+
505
1049
  // Debounced autocomplete. People are withheld server-side until q ≥ 2 chars.
506
1050
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
507
1051
  useEffect(() => {
@@ -514,123 +1058,30 @@ export function ManageAccessDialog({
514
1058
  }
515
1059
  debounceRef.current = setTimeout(() => {
516
1060
  suggestPrincipals(workspaceId, q)
517
- .then(setSuggest)
1061
+ .then((res) => {
1062
+ setSuggest(res);
1063
+ learnAccounts(res.people ?? []);
1064
+ // Only an answer that SAYS it rules on accounts turns "not in the
1065
+ // answer" into "no account". Without that the answer is silent on
1066
+ // the question, so the address stays unjudged and unlabelled.
1067
+ //
1068
+ // `peopleWithheld` is checked here too, not just trusted to have
1069
+ // already made `accountsKnown` false: a withheld list names nobody
1070
+ // by design (the harvesting guard), so reading it as "nobody has an
1071
+ // account" would label every address at once. Either flag alone is
1072
+ // enough to say nothing.
1073
+ if (res.accountsKnown && !res.peopleWithheld) noteLookedUp(q.toLowerCase());
1074
+ })
518
1075
  .catch(() => setSuggest(null));
519
1076
  }, 200);
520
1077
  return () => {
521
1078
  if (debounceRef.current) clearTimeout(debounceRef.current);
522
1079
  };
523
- }, [query, workspaceId, repoRelative]);
1080
+ }, [query, workspaceId, repoRelative, learnAccounts, noteLookedUp]);
524
1081
 
525
1082
  const myEmail = user?.email?.toLowerCase() ?? '';
526
1083
 
527
- const principals = useMemo<PrincipalRow[]>(() => {
528
- if (!data) return [];
529
- // Aggregate the four resolver lists into ONE row per principal carrying its
530
- // independent verb set. Membership IS the displayed set — we do NOT subtract
531
- // the rollup. The resolver already folds owner⊇write⊇read on the lower lists,
532
- // so an owner legitimately shows owner+write+read checked; download is its own
533
- // axis (owner folds in, write does not), sourced from `downloaders`.
534
- const rows = new Map<string, PrincipalRow>();
535
- // Kinded collective list for one eligible set. Older servers omit
536
- // `principals` (version skew) — fall back to the name-only `roles`,
537
- // treating everything as a role (the pre-groups display).
538
- const collectivesOf = (list: AccessEligible): ResolvedPrincipal[] =>
539
- list.principals ?? list.roles.map((name) => ({ name, kind: 'role' as const }));
540
- const touchCollective = (c: ResolvedPrincipal): PrincipalRow => {
541
- // Rows are keyed by KIND + name (`g:`/`r:`/`p:`) — the backend treats a
542
- // bare `Product` (group) and `role/Product` (role) as DIFFERENT
543
- // principals, so a group and a role sharing a name are two rows, each
544
- // mutating its own grant. Collapsing them to one row silently pointed
545
- // every edit at the group and hid the role's grant entirely. A plugin
546
- // principal's name is its full `plugin/<Name>/<verb>` token.
547
- const key =
548
- c.kind === 'group'
549
- ? `g:${c.name.toLowerCase()}`
550
- : c.kind === 'plugin'
551
- ? `p:${c.name.toLowerCase()}`
552
- : `r:${c.name.toLowerCase()}`;
553
- let row = rows.get(key);
554
- if (!row) {
555
- const plugin = c.kind === 'plugin' ? parsePluginPrincipalToken(c.name) : null;
556
- row = {
557
- key,
558
- label: plugin ? pluginPrincipalLabel(plugin.plugin, plugin.verb) : c.name,
559
- kind: c.kind,
560
- isYou: false,
561
- principal:
562
- c.kind === 'group'
563
- ? { kind: 'group', group: c.name }
564
- : plugin
565
- ? { kind: 'plugin', plugin: plugin.plugin, verb: plugin.verb }
566
- : { kind: 'role', role: c.name },
567
- verbs: { owner: false, write: false, read: false, download: false },
568
- manage: 'direct',
569
- ancestors: [],
570
- };
571
- rows.set(key, row);
572
- }
573
- return row;
574
- };
575
- const touchUser = (u: { name: string; email: string }): PrincipalRow => {
576
- const key = `u:${u.email.toLowerCase()}`;
577
- let row = rows.get(key);
578
- if (!row) {
579
- const label = u.name || u.email;
580
- row = {
581
- key,
582
- label,
583
- // Only a real display name earns the second line — a nameless user
584
- // would otherwise render the same email twice, burning a row of the
585
- // scarce width on a duplicate.
586
- sub: label.toLowerCase() === u.email.toLowerCase() ? undefined : u.email,
587
- kind: 'user',
588
- isYou: u.email.toLowerCase() === myEmail,
589
- principal: { kind: 'user', email: u.email, displayName: u.name || u.email },
590
- verbs: { owner: false, write: false, read: false, download: false },
591
- manage: 'direct',
592
- ancestors: [],
593
- };
594
- rows.set(key, row);
595
- }
596
- return row;
597
- };
598
-
599
- for (const c of collectivesOf(data.owners)) touchCollective(c).verbs.owner = true;
600
- for (const u of data.owners.users) touchUser(u).verbs.owner = true;
601
- for (const c of collectivesOf(data.eligible)) touchCollective(c).verbs.write = true;
602
- for (const u of data.eligible.users) touchUser(u).verbs.write = true;
603
- // Read grants are rows whether or not the node is public: on a public
604
- // node they are what MAKES it public, and a row is the ONE place any
605
- // grant is removed. The built-in `everyone` is a row like any principal
606
- // — when a file spells it. A derived everyone (public only through a
607
- // plugin principal) has no line of its own; the plugin's row is that grant.
608
- for (const c of collectivesOf(data.readers)) {
609
- if (c.kind === 'role' && isEveryoneRole({ kind: 'role', role: c.name })) {
610
- if (!lookupSources(data.sources, 'r:everyone')?.read?.length) continue;
611
- const row = touchCollective(c);
612
- row.label = 'Everyone';
613
- row.verbs.read = true;
614
- continue;
615
- }
616
- touchCollective(c).verbs.read = true;
617
- }
618
- for (const u of data.readers.users) touchUser(u).verbs.read = true;
619
- for (const c of collectivesOf(data.downloaders)) touchCollective(c).verbs.download = true;
620
- for (const u of data.downloaders.users) touchUser(u).verbs.download = true;
621
-
622
- // Attach each row's per-verb source + manageability (direct / inherited /
623
- // external) from the resolver's `sources` map, keyed by the same row key
624
- // (with the `g:` → `r:` version-skew fallback for group rows).
625
- for (const row of rows.values()) {
626
- row.sources = lookupSources(data.sources, row.key);
627
- const { manage, ancestors } = classifyManage(row.sources);
628
- row.manage = manage;
629
- row.ancestors = ancestors;
630
- }
631
-
632
- return [...rows.values()];
633
- }, [data, myEmail]);
1084
+ const principals = useMemo<PrincipalRow[]>(() => buildRows(data, myEmail), [data, myEmail]);
634
1085
 
635
1086
  // Split direct (granted here, editable) from inherited/external (granted at a
636
1087
  // parent or via a role) so the main list stays clean and the rest collapses
@@ -640,6 +1091,8 @@ export function ManageAccessDialog({
640
1091
  () => principals.filter((p) => p.manage !== 'direct'),
641
1092
  [principals],
642
1093
  );
1094
+ // The read side of a folder-governed file: who can open it, shown read-only.
1095
+ const readerRows = useMemo(() => principals.filter((p) => p.verbs.read), [principals]);
643
1096
 
644
1097
  /**
645
1098
  * The inherited rows, ONE SECTION PER GRANTING FOLDER — the prototype's shape
@@ -692,11 +1145,42 @@ export function ManageAccessDialog({
692
1145
  * `state.accOpen` holds a single value. */
693
1146
  const [openSection, setOpenSection] = useState<string | null>(null);
694
1147
 
1148
+ /**
1149
+ * Keep the row a write just changed on screen. A write can MOVE a row: revoke
1150
+ * someone's local edit and, if a parent still grants them read, they file
1151
+ * under "People invited to <parent>" — which is collapsed, so the person the
1152
+ * reader was just editing vanishes and looks removed. Open the section the
1153
+ * row now lives in (its nearest granting folder, or the roles group); a row
1154
+ * that stays on this folder needs nothing.
1155
+ */
1156
+ const revealRow = useCallback((row: PrincipalRow | undefined) => {
1157
+ if (!row || row.manage === 'direct') return;
1158
+ setOpenSection(row.ancestors.length === 0 ? 'roles' : row.ancestors[0]!);
1159
+ }, []);
1160
+
695
1161
  const governed = repoRelative !== null;
1162
+ // A file that cannot carry frontmatter (a PDF, a deck, an image) has no rules
1163
+ // of its own: its folder's rules govern it, and the grant / revoke routes
1164
+ // refuse it. The server's ruling (`governedByFolder`, from the same shared
1165
+ // predicate over the resolver's registered extensions) decides once the view
1166
+ // has loaded; until then the shared predicate's core set stands in, so the
1167
+ // sheet never flashes a field for a PDF.
1168
+ const folderGoverns =
1169
+ targetKind === 'file' &&
1170
+ repoRelative !== null &&
1171
+ (data ? data.governedByFolder !== undefined : !canCarryFrontmatter(repoRelative));
1172
+ const governingFolder =
1173
+ data?.governedByFolder ??
1174
+ (repoRelative !== null && repoRelative.includes('/')
1175
+ ? repoRelative.slice(0, repoRelative.lastIndexOf('/'))
1176
+ : '');
1177
+ const governingFolderLabel =
1178
+ governingFolder === '' ? WHOLE_WORKSPACE : governingFolder.slice(governingFolder.lastIndexOf('/') + 1);
696
1179
  // The dialog can mutate only if the current user can write this path's access
697
1180
  // config — exactly what the backend gate enforces. `canWrite` on the path is
698
1181
  // the same signal (folder access.md / node frontmatter both gate on write).
699
- const canManage = !!data?.canWrite;
1182
+ // Never on a folder-governed file: there is nothing here to write to.
1183
+ const canManage = !!data?.canWrite && !folderGoverns;
700
1184
 
701
1185
  // Resolve the CURRENT typed query into a principal to append as a chip: an
702
1186
  // exact group/role match or a free-typed email. (Suggestion clicks append
@@ -729,39 +1213,54 @@ export function ManageAccessDialog({
729
1213
  );
730
1214
  setQuery('');
731
1215
  setSuggest(null);
1216
+ // A pick from the list moved focus onto the list's button, which is about
1217
+ // to unmount; the next name is typed into the field, so put the caret
1218
+ // back there rather than making the person click into the white space.
1219
+ queryInputRef.current?.focus();
732
1220
  }, []);
733
1221
 
1222
+ // What the list OFFERS: the server's suggestions minus what is already a
1223
+ // chip. A group picked once has nothing to add a second time, and seeing it
1224
+ // offered again reads as "did that not take?".
1225
+ const offered = useMemo(() => {
1226
+ if (!suggest) return null;
1227
+ const picked = new Set(pickedChips.map(principalKey));
1228
+ return {
1229
+ groups: (suggest.groups ?? []).filter((g) => !picked.has(principalKey({ kind: 'group', group: g }))),
1230
+ roles: (suggest.roles ?? []).filter((r) => !picked.has(principalKey({ kind: 'role', role: r }))),
1231
+ plugins: (suggest.pluginPrincipals ?? [])
1232
+ .flatMap((name) => PLUGIN_PRINCIPAL_VERBS.map((verb) => ({ name, verb })))
1233
+ .filter(({ name, verb }) => !picked.has(principalKey({ kind: 'plugin', plugin: name, verb }))),
1234
+ people: (suggest.people ?? []).filter(
1235
+ (p) => !picked.has(principalKey({ kind: 'user', email: p.email, displayName: p.name })),
1236
+ ),
1237
+ };
1238
+ }, [suggest, pickedChips]);
1239
+ const offersAnything =
1240
+ !!offered &&
1241
+ (offered.groups.length > 0 ||
1242
+ offered.roles.length > 0 ||
1243
+ offered.plugins.length > 0 ||
1244
+ offered.people.length > 0);
1245
+
734
1246
  const removeChip = useCallback((p: Principal) => {
735
1247
  setPickedChips((chips) => chips.filter((c) => principalKey(c) !== principalKey(p)));
736
1248
  }, []);
737
1249
 
738
- // The new-grant checklist stores independent flags, but owner⊇write⊇read folds
739
- // for display (selecting Owner implies edit+read; Edit implies read; owner also
740
- // folds in download). `effectiveNewVerbs` is what the boxes render as checked.
741
- const effectiveNewVerbs = useMemo<VerbSet>(
742
- () => ({
743
- owner: newVerbs.owner,
744
- write: newVerbs.owner || newVerbs.write,
745
- read: newVerbs.owner || newVerbs.write || newVerbs.read,
746
- download: newVerbs.owner || newVerbs.download,
747
- }),
748
- [newVerbs],
749
- );
1250
+ // The new-grant checklist stores independent flags; the grammar's fold turns
1251
+ // them into what the boxes render as checked (Owner implies edit, download
1252
+ // and read; Edit and Download each imply read).
1253
+ const effectiveNewVerbs = useMemo<VerbSet>(() => effectiveVerbs(newVerbs), [newVerbs]);
750
1254
 
751
- // The minimal verb list to send: the single highest tier verb (the lower ones
752
- // fold in server-side) plus download when it's chosen independently of owner.
753
- const grantVerbs = useMemo<GrantVerb[]>(() => {
754
- const verbs: GrantVerb[] = [];
755
- if (effectiveNewVerbs.owner) verbs.push('owner');
756
- else if (effectiveNewVerbs.write) verbs.push('write');
757
- else if (effectiveNewVerbs.read) verbs.push('read');
758
- if (effectiveNewVerbs.download && !effectiveNewVerbs.owner) verbs.push('download');
759
- return verbs;
760
- }, [effectiveNewVerbs]);
761
-
762
- const doGrant = useCallback(async () => {
1255
+ // The fewest lines to send for that set — the grammar's own minimisation, so
1256
+ // `owner` is one line and Download alone (or Read + Download) is `download`
1257
+ // with no redundant `read:` beside it.
1258
+ const grantVerbs = useMemo<GrantVerb[]>(() => minimalGrantVerbs(effectiveNewVerbs), [effectiveNewVerbs]);
1259
+
1260
+ /** Grant every picked principal the chosen verbs. Resolves `true` only when all of them landed. */
1261
+ const doGrant = useCallback(async (): Promise<boolean> => {
763
1262
  if (!workspaceId || repoRelative === null || pickedChips.length === 0 || grantVerbs.length === 0)
764
- return;
1263
+ return false;
765
1264
  setBusy(true);
766
1265
  setMutateError(null);
767
1266
  // No batch grant endpoint exists, so apply each principal/verb pair and
@@ -774,17 +1273,14 @@ export function ManageAccessDialog({
774
1273
  const label = principalLabel(principal);
775
1274
  // `everyone` is public-read only — the backend rejects any other verb for
776
1275
  // it, so clamp here to avoid a guaranteed failure when a higher verb is
777
- // also selected for the other chips.
1276
+ // also selected for the other chips. Every selection that reaches this
1277
+ // point confers read (Share is disabled while `grantVerbs` is empty, and
1278
+ // each of the four boxes now implies read), so the clamp always has a
1279
+ // verb to send: "Can download" on Everyone shares it publicly readable
1280
+ // and drops only the download half the backend would refuse anyway.
778
1281
  const verbsForPrincipal = isEveryoneRole(principal)
779
- ? (effectiveNewVerbs.read ? (['read'] as GrantVerb[]) : [])
1282
+ ? (['read'] as GrantVerb[])
780
1283
  : grantVerbs;
781
- // Don't silently drop the Everyone chip when nothing read-equivalent was
782
- // picked (e.g. only "Can download"): record it as a failure so the chip
783
- // stays visible and the user is told why, rather than a no-op clear.
784
- if (isEveryoneRole(principal) && verbsForPrincipal.length === 0) {
785
- failures.push(`${label}: "Everyone" can only be granted read access. Select "Can read".`);
786
- continue;
787
- }
788
1284
  for (const verb of verbsForPrincipal) {
789
1285
  try {
790
1286
  await grantAccess(workspaceId, {
@@ -807,16 +1303,24 @@ export function ManageAccessDialog({
807
1303
  `${failures.length} grant${failures.length === 1 ? '' : 's'} failed (the rest were applied):\n${failures.join('\n')}`,
808
1304
  );
809
1305
  }
1306
+ return failures.length === 0;
810
1307
  } finally {
811
1308
  reload();
812
1309
  setBusy(false);
813
1310
  }
814
- }, [workspaceId, repoRelative, pickedChips, entry.relativePath, targetKind, grantVerbs, effectiveNewVerbs, reload]);
1311
+ }, [workspaceId, repoRelative, pickedChips, entry.relativePath, targetKind, grantVerbs, reload]);
1312
+
1313
+ // The footer's one primary action. With picks it shares them and closes; a
1314
+ // grant that fails keeps the dialog — and the picks — up with the failure
1315
+ // shown. With nothing picked it only closes.
1316
+ const doShare = useCallback(async () => {
1317
+ if (await doGrant()) onClose();
1318
+ }, [doGrant, onClose]);
815
1319
 
816
- // WHY the node is public, said in the band and acted on in the rows: every
817
- // literal `everyone` line (here, or in a parent) is the Everyone row's
1320
+ // WHY the node is public, said in the reach line and acted on in the rows:
1321
+ // every literal `everyone` line (here, or in a parent) is the Everyone row's
818
1322
  // source; every public plugin principal granted read is that plugin's
819
- // row. The band only describes — one mechanism removes, and it is the
1323
+ // row. The line only describes — one mechanism removes, and it is the
820
1324
  // same one for every principal.
821
1325
  const publicReasons = [
822
1326
  ...(lookupSources(data?.sources, 'r:everyone')?.read ?? []).map((s) =>
@@ -828,76 +1332,128 @@ export function ManageAccessDialog({
828
1332
  }),
829
1333
  ];
830
1334
 
831
- // Toggle a single verb on an existing grantee: check → grant that verb, uncheck
832
- // → revoke just that verb. The server's fresh view is authoritative (we never
833
- // flip optimistically); a refused revoke (e.g. lock contention) surfaces its
834
- // message and we re-sync.
835
- const doToggleVerb = useCallback(
836
- async (principal: Principal, role: Role, currentlyOn: boolean) => {
1335
+ // The item's reach, in one line: the only place the sheet says whether it is
1336
+ // restricted or public. A statement, not a control — each public reason is a
1337
+ // grant with a row below, and the row is where it is removed.
1338
+ const reachLine = data ? (
1339
+ <p className="mt-2 flex items-start gap-1.5 text-detail text-ink-muted">
1340
+ {data.readers.restricted ? (
1341
+ <Lock size={13} aria-hidden className="mt-0.5 shrink-0" />
1342
+ ) : (
1343
+ <Globe size={13} aria-hidden className="mt-0.5 shrink-0 text-ok" />
1344
+ )}
1345
+ <span className="min-w-0">
1346
+ {data.readers.restricted
1347
+ ? 'Restricted: only the people below can open it'
1348
+ : `Public: anyone signed in can read it${
1349
+ publicReasons.length > 0 ? ` — ${publicReasons.join(', ')}` : ''
1350
+ }. Editing needs access.`}
1351
+ </span>
1352
+ </p>
1353
+ ) : null;
1354
+
1355
+ /**
1356
+ * Apply a whole verb set to one existing row — the single action behind every
1357
+ * item of a row's menu, including Deny (`picked: null`).
1358
+ *
1359
+ * The user states the set they want; the dialog writes the DIFFERENCE between
1360
+ * that and what the principal effectively has here, with no prompt in between:
1361
+ *
1362
+ * - a verb the set drops, held only through an entry on this target → revoke
1363
+ * it here (there is nothing left to shadow once it is gone);
1364
+ * - a verb the set drops that a PARENT still grants → a verb-scoped `deny` on
1365
+ * this target, which is what "restrict just this folder" always wrote, now
1366
+ * written straight from the row;
1367
+ * - a verb the set adds that is denied here → lift that denial, which alone
1368
+ * may restore it from the parent;
1369
+ * - a verb the set adds that nothing confers → grant it here.
1370
+ *
1371
+ * Order is broadest-verb-first for both halves; see {@link VERBS_BROADEST_FIRST}
1372
+ * for why neither half is safe in the other order. Each call answers with the
1373
+ * server's fresh view, and the next step re-reads the row from it rather than
1374
+ * from a predicted state — so a partial failure leaves the sheet showing what
1375
+ * actually landed, and the steps already applied stand.
1376
+ */
1377
+ const doApplyVerbSet = useCallback(
1378
+ async (row: PrincipalRow, picked: VerbPick | null) => {
837
1379
  if (!workspaceId || repoRelative === null) return;
1380
+ // The menu stays OPEN across the writes, as the per-verb checklist did:
1381
+ // its items freeze on `busy`, and when the fresh view lands they re-render
1382
+ // showing the set that actually took — including, per verb, "from <parent>"
1383
+ // or "restricted here". Closing it would hide exactly that answer.
838
1384
  setBusy(true);
839
1385
  setMutateError(null);
1386
+ const base = { path: entry.relativePath, kind: targetKind, principal: row.principal };
1387
+ let latest = data;
1388
+ /** The row as the LATEST server response describes it — never a guess. */
1389
+ const current = (): PrincipalRow | undefined =>
1390
+ buildRows(latest, myEmail).find((r) => r.key === row.key);
1391
+ const step = async (send: () => Promise<AccessResponse>) => {
1392
+ latest = await send();
1393
+ setData(latest);
1394
+ };
840
1395
  try {
841
- const grantVerb = ROLE_TO_VERB[role];
842
- const res = currentlyOn
843
- ? await revokeAccess(workspaceId, {
844
- path: entry.relativePath,
845
- kind: targetKind,
846
- principal,
847
- verb: grantVerb,
848
- })
849
- : await grantAccess(workspaceId, {
850
- path: entry.relativePath,
851
- kind: targetKind,
852
- verb: grantVerb,
853
- principal,
854
- });
855
- setData(res);
856
- // When UNCHECKING, the direct entry for this verb was stripped (200) but
857
- // the principal may STILL hold the SAME verb via an ancestor — i.e. the
858
- // verb was `[direct, ancestor]`. The fresh view still lists them with the
859
- // ancestor for this verb; chain into the verb-scoped "Remove from parent?"
860
- // so one uncheck finishes the job instead of a half-removal (the direct
861
- // bit gone, the inherited bit silently remaining and the box re-checking).
862
- if (currentlyOn) {
863
- const key = principalKey(principal);
864
- const stillForVerb = lookupSources(res.sources, key)?.[grantVerb] ?? [];
865
- const ancestors = ancestorsFromSources({ [grantVerb]: stillForVerb });
866
- if (ancestors.length > 0) {
867
- setConfirmRemove({
868
- principal,
869
- label: principalLabel(principal),
870
- ancestors,
871
- verb: grantVerb,
872
- });
1396
+ // Deny is the whole-principal case and the server does it in one write:
1397
+ // `deny-here` with no verb strips every local grant and denies all four,
1398
+ // read included.
1399
+ if (picked === null) {
1400
+ await step(() => revokeAccess(workspaceId, { ...base, mode: 'deny-here' }));
1401
+ return;
1402
+ }
1403
+
1404
+ // ---- lower: what the set drops -------------------------------------
1405
+ // Only a verb the pick states as OFF is dropped; one it leaves out is
1406
+ // left to the file (see `VerbPick`).
1407
+ for (const verb of VERBS_BROADEST_FIRST) {
1408
+ if (picked[verb] !== false) continue;
1409
+ const now = current();
1410
+ if (!now?.verbs[verb]) continue; // already gone
1411
+ const src = now.sources?.[verb] ?? [];
1412
+ // Purely local → a plain revoke is enough and leaves no `deny` line
1413
+ // behind to explain later. Anything else (inherited, or conferred with
1414
+ // no entry of its own) needs the denial: removing what is not written
1415
+ // here cannot take it away.
1416
+ const localOnly = src.length > 0 && src.every((s) => s.kind === 'direct');
1417
+ await step(() =>
1418
+ revokeAccess(
1419
+ workspaceId,
1420
+ localOnly ? { ...base, verb } : { ...base, mode: 'deny-here', verb },
1421
+ ),
1422
+ );
1423
+ // A local grant that turned out to be doubled by a parent: the revoke
1424
+ // landed, the verb survived it. Finish the job with the denial rather
1425
+ // than leave a half-applied set behind.
1426
+ if (localOnly && current()?.verbs[verb]) {
1427
+ await step(() => revokeAccess(workspaceId, { ...base, mode: 'deny-here', verb }));
873
1428
  }
874
1429
  }
875
- } catch (err) {
876
- // Unchecking a verb the principal holds via INHERITANCE (e.g. they're
877
- // direct on `download` but inherit `write`) can't be done in place — the
878
- // target splice no-ops and the route 409s. Convert that into the same
879
- // "Remove from parent?" flow a Remove uses, instead of a raw error toast.
880
- const inherited = asInheritedError(err);
881
- if (inherited) {
882
- const label = principalLabel(principal);
883
- // Scope the confirmation to the single verb the user unchecked, so
884
- // "Restrict just this file" / "Remove from parent" act on THAT verb
885
- // only and leave the principal's other (e.g. direct download) verbs.
886
- setConfirmRemove({
887
- principal,
888
- label,
889
- ancestors: ancestorsFromSources(inherited.sources),
890
- verb: ROLE_TO_VERB[role],
891
- });
892
- } else {
893
- setMutateError(err instanceof Error ? err.message : String(err));
894
- reload(); // re-sync after a refused/rolled-back toggle
1430
+
1431
+ // ---- raise: lift the restrictions the new set no longer needs ------
1432
+ for (const verb of VERBS_BROADEST_FIRST) {
1433
+ if (!picked[verb]) continue;
1434
+ if (!(current()?.denials?.[verb] ?? []).some((s) => s.kind === 'direct')) continue;
1435
+ await step(() => revokeAccess(workspaceId, { ...base, verb }));
1436
+ }
1437
+
1438
+ // ---- raise: grant what still nothing confers -----------------------
1439
+ // `minimalGrantVerbs` already drops the verbs the set's own higher ones
1440
+ // confer, so this writes at most two lines (a tier, plus download) and
1441
+ // never a redundant `read:` under a grant that carries read anyway.
1442
+ for (const verb of minimalGrantVerbs(picked)) {
1443
+ if (current()?.verbs[verb]) continue;
1444
+ await step(() => grantAccess(workspaceId, { ...base, verb }));
895
1445
  }
1446
+ } catch (err) {
1447
+ setMutateError(err instanceof Error ? err.message : String(err));
1448
+ reload(); // re-sync on whatever the server actually holds now
896
1449
  } finally {
897
1450
  setBusy(false);
1451
+ // Wherever the writes left the row, keep it in view — from the latest
1452
+ // response, so a partial failure reveals where it actually is.
1453
+ revealRow(current());
898
1454
  }
899
1455
  },
900
- [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
1456
+ [workspaceId, repoRelative, entry.relativePath, targetKind, data, myEmail, reload, revealRow],
901
1457
  );
902
1458
 
903
1459
  const doRevoke = useCallback(
@@ -909,7 +1465,12 @@ export function ManageAccessDialog({
909
1465
  setConfirmRemove({
910
1466
  principal: row.principal,
911
1467
  label: row.label,
912
- ancestors: row.ancestors,
1468
+ // GRANT ancestors only. The dialog's offer is "remove their access
1469
+ // from <folder>"; an ancestor that denies holds no access to remove,
1470
+ // and acting there would strip that folder's restriction instead. A
1471
+ // row whose only ancestor entry is a denial falls to the no-ancestor
1472
+ // branch, which offers restricting here and nothing else.
1473
+ ancestors: row.grantAncestors,
913
1474
  });
914
1475
  return;
915
1476
  }
@@ -922,13 +1483,22 @@ export function ManageAccessDialog({
922
1483
  principal: row.principal,
923
1484
  });
924
1485
  setData(res);
1486
+ // If a parent still grants them something, the row has just moved into
1487
+ // that folder's collapsed section: keep it on screen (the prompt below
1488
+ // may be declined, and the person must not look removed when it is).
1489
+ revealRow(buildRows(res, myEmail).find((r) => r.key === row.key));
925
1490
  // The direct entry was removed, but the FRESH view may still list this
926
1491
  // principal with only `ancestor` source(s) — i.e. they're still inherited
927
1492
  // from a parent. Open "Remove from parent?" so the one Remove click can
928
1493
  // finish the job instead of leaving a row that reappears as inherited (a
929
1494
  // silent half-removal). We read the just-revoked row's post-revoke sources
930
1495
  // straight from the response, so it reflects the real current tree.
931
- const ancestors = ancestorsFromSources(lookupSources(res.sources, row.key));
1496
+ //
1497
+ // GRANTS, deliberately — `res.denials` is not consulted. A parent that
1498
+ // still DENIES this principal is not unfinished business: the removal
1499
+ // already left them with nothing here, and chaining to that folder would
1500
+ // offer to delete its restriction.
1501
+ const ancestors = ancestorPaths(lookupSources(res.sources, row.key));
932
1502
  if (ancestors.length > 0) {
933
1503
  setConfirmRemove({ principal: row.principal, label: row.label, ancestors });
934
1504
  }
@@ -940,7 +1510,7 @@ export function ManageAccessDialog({
940
1510
  setConfirmRemove({
941
1511
  principal: row.principal,
942
1512
  label: row.label,
943
- ancestors: ancestorsFromSources(inherited.sources),
1513
+ ancestors: ancestorPaths(inherited.sources),
944
1514
  });
945
1515
  } else {
946
1516
  setMutateError(err instanceof Error ? err.message : String(err));
@@ -950,7 +1520,7 @@ export function ManageAccessDialog({
950
1520
  setBusy(false);
951
1521
  }
952
1522
  },
953
- [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
1523
+ [workspaceId, repoRelative, entry.relativePath, targetKind, reload, myEmail, revealRow],
954
1524
  );
955
1525
 
956
1526
  /** Cascade up: remove the principal from the granting ancestor folder (optionally scoped to one verb). */
@@ -1018,9 +1588,33 @@ export function ManageAccessDialog({
1018
1588
  return names.slice(0, 3).join(', ');
1019
1589
  }, [data]);
1020
1590
 
1021
- // One grantee row. Direct rows get the inline verb editor; inherited rows are
1022
- // read-only with a Remove that opens the cascade flow; external rows are
1023
- // read-only with no action.
1591
+ // Every managed row ends in the same two slots: the verb control, then
1592
+ // Remove. A row with nothing removable here (a role or policy grant) keeps
1593
+ // the slot empty, so the verb control still lines up with its neighbours'.
1594
+ //
1595
+ // The accessible names are the ones these actions had before they shared a
1596
+ // slot: on a direct grant this is the old dropdown item "Remove access", on an
1597
+ // inherited grant the old "Remove" button. The name still contains the visible
1598
+ // word, so voice control ("click Remove") reaches both.
1599
+ const removeSlot = (p: PrincipalRow | null) => (
1600
+ <span className="flex w-16 shrink-0 justify-end">
1601
+ {p && (
1602
+ <Button
1603
+ variant="danger"
1604
+ size="tiny"
1605
+ disabled={busy}
1606
+ aria-label={p.manage === 'direct' ? 'Remove access' : undefined}
1607
+ onClick={() => doRevoke(p)}
1608
+ >
1609
+ Remove
1610
+ </Button>
1611
+ )}
1612
+ </span>
1613
+ );
1614
+
1615
+ // One grantee row. Direct rows get the inline verb editor and a Remove that
1616
+ // revokes in place; inherited rows are read-only with a Remove that opens the
1617
+ // cascade flow; external rows are read-only with no action.
1024
1618
  const renderRow = (p: PrincipalRow) => {
1025
1619
  const tone = avatarTone(p.label);
1026
1620
  return (
@@ -1031,7 +1625,7 @@ export function ManageAccessDialog({
1031
1625
  <div key={p.key} className="flex flex-wrap items-center gap-x-3 gap-y-1 py-2">
1032
1626
  {p.kind !== 'user' ? (
1033
1627
  <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-sunken text-detail font-bold text-ink-muted">
1034
- {initials(p.label)}
1628
+ {labelInitials(p.label)}
1035
1629
  </span>
1036
1630
  ) : (
1037
1631
  <span
@@ -1045,105 +1639,146 @@ export function ManageAccessDialog({
1045
1639
  <div className="flex min-w-0 items-center gap-1.5">
1046
1640
  <span className="truncate text-ui font-medium text-ink">{p.label}</span>
1047
1641
  {p.isYou && <span className="shrink-0 text-ui text-ink-faint">(you)</span>}
1642
+ {/* Granted, but nobody has signed in as this address yet. Beside
1643
+ the name, where the chip put it before the grant was saved —
1644
+ and gone by itself once they do sign in. */}
1645
+ {p.kind === 'user' && p.hasAccount === false && <NoAccountNote />}
1048
1646
  {p.kind !== 'user' && (
1049
1647
  // The same chip vocabulary as the suggest menu's trailing tags:
1050
1648
  // a role is a capability, a group is an audience — badge which.
1051
- <Badge tone="outline" size="xs" className="shrink-0 uppercase">
1649
+ <Badge
1650
+ tone="outline"
1651
+ size="xs"
1652
+ className="shrink-0 uppercase"
1653
+ title={PRINCIPAL_KIND_HELP[p.kind]}
1654
+ aria-description={PRINCIPAL_KIND_HELP[p.kind]}
1655
+ >
1052
1656
  {p.kind === 'group' ? 'Group' : p.kind === 'plugin' ? 'Plugin' : 'Role'}
1053
1657
  </Badge>
1054
1658
  )}
1055
1659
  </div>
1056
1660
  {p.sub && <div className="truncate text-detail text-ink-muted">{p.sub}</div>}
1057
1661
  </div>
1058
- {canManage && p.manage === 'inherited' ? (
1059
- // Inherited from a parent folder — read-only here. Leaf folder name only
1060
- // (full path on hover); Remove opens the "Remove from parent?" flow.
1662
+ {canManage ? (
1663
+ // ONE set of controls for every row the caller can manage — direct,
1664
+ // inherited or external alike. An inherited row used to be read-only
1665
+ // text here, which made "give this person less than the parent does" a
1666
+ // thing the sheet could describe but not do; the menu below does it, by
1667
+ // writing the restriction in the background.
1061
1668
  <div className="ml-auto flex max-w-full shrink-0 items-center gap-2">
1062
- <span
1063
- className="min-w-0 max-w-40 truncate text-detail italic text-ink-faint"
1064
- title={p.ancestors.map(folderPath).join(', ')}
1065
- >
1066
- via {p.ancestors.map(folderLabel).join(', ')}
1067
- </span>
1068
- <span className="whitespace-nowrap text-detail text-ink-faint">
1069
- {summarizeVerbs(p.verbs)}
1070
- </span>
1071
- <Button variant="danger" size="tiny" disabled={busy} onClick={() => doRevoke(p)}>
1072
- Remove
1073
- </Button>
1074
- </div>
1075
- ) : canManage && p.manage === 'external' ? (
1076
- // No file-backed grant to remove here — managed elsewhere (a role or
1077
- // group's membership, the everyone policy, or admin rescue).
1078
- <span
1079
- className="ml-auto shrink-0 text-detail text-ink-faint"
1080
- title="Granted via a role or policy. Manage it there"
1081
- >
1082
- {summarizeVerbs(p.verbs)}
1083
- </span>
1084
- ) : canManage ? (
1085
- <div className="ml-auto shrink-0">
1086
- <Button
1087
- variant="quiet"
1088
- size="sm"
1089
- disabled={busy}
1090
- onClick={() => setOpenRowKey((k) => (k === p.key ? null : p.key))}
1091
- trailingIcon={<ChevronDown size={14} />}
1092
- >
1093
- {summarizeVerbs(p.verbs)}
1094
- </Button>
1095
- {openRowKey === p.key && (
1096
- <AnchoredMenu>
1097
- {/* Everyone is public READ only (the grant route refuses the
1098
- rest), so its row offers exactly the verb it can hold. */}
1099
- {(isEveryoneRole(p.principal) ? (['Can read'] as Role[]) : TIER_ROLES).map((role) => {
1100
- const k = ROLE_TO_KEY[role];
1101
- const checked = p.verbs[k];
1102
- const disabled =
1103
- busy ||
1104
- (role === 'Can edit' && p.verbs.owner) ||
1105
- (role === 'Can read' && (p.verbs.owner || p.verbs.write));
1106
- return (
1107
- <MenuItem
1108
- key={role}
1109
- disabled={disabled}
1110
- active={checked}
1111
- onClick={() => doToggleVerb(p.principal, role, checked)}
1112
- trailing={checked ? <Check size={14} className="text-accent" /> : undefined}
1113
- >
1114
- {role}
1115
- </MenuItem>
1116
- );
1117
- })}
1118
- {!isEveryoneRole(p.principal) && <div className="my-1 border-t border-line" />}
1119
- {!isEveryoneRole(p.principal) &&
1120
- (() => {
1121
- const checked = p.verbs.download;
1122
- const disabled = busy || p.verbs.owner;
1123
- return (
1124
- <MenuItem
1125
- disabled={disabled}
1126
- active={checked}
1127
- onClick={() => doToggleVerb(p.principal, 'Can download', checked)}
1128
- trailing={checked ? <Check size={14} className="text-accent" /> : undefined}
1129
- >
1130
- Can download
1131
- </MenuItem>
1132
- );
1133
- })()}
1134
- <div className="my-1 border-t border-line" />
1135
- <MenuItem
1136
- tone="danger"
1137
- disabled={busy}
1138
- onClick={() => {
1139
- setOpenRowKey(null);
1140
- doRevoke(p);
1141
- }}
1142
- >
1143
- Remove access
1144
- </MenuItem>
1145
- </AnchoredMenu>
1669
+ {p.manage === 'inherited' && (
1670
+ // Leaf folder name only (full path on hover) — where the entries
1671
+ // naming this principal live, when none of them is here.
1672
+ <span
1673
+ className="min-w-0 max-w-40 truncate text-detail italic text-ink-faint"
1674
+ title={p.ancestors.map(folderPath).join(', ')}
1675
+ >
1676
+ via {p.ancestors.map(folderLabel).join(', ')}
1677
+ </span>
1146
1678
  )}
1679
+ {/* Its own box: the menu anchors to its DOM parent, which must be
1680
+ the trigger alone, not the trigger and Remove together. */}
1681
+ <div>
1682
+ {/* Not `disabled={busy}`: the menu's items freeze while a grant or
1683
+ revoke is in flight, and this button only opens or closes the
1684
+ menu. Disabled, it could not take focus back on Escape
1685
+ (`.focus()` on a disabled button is a no-op), and focus fell to
1686
+ `document`. */}
1687
+ <Button
1688
+ ref={openRowKey === p.key ? openRowTriggerRef : undefined}
1689
+ variant="quiet"
1690
+ size="sm"
1691
+ onClick={() => setOpenRowKey((k) => (k === p.key ? null : p.key))}
1692
+ trailingIcon={<ChevronDown size={14} />}
1693
+ >
1694
+ {rowSummary(p)}
1695
+ </Button>
1696
+ {openRowKey === p.key && (
1697
+ <AnchoredMenu
1698
+ onDismiss={() => setOpenRowKey(null)}
1699
+ triggerRef={openRowTriggerRef}
1700
+ // Sized to the items, not the trigger: a row that reads
1701
+ // "Can read" opens a narrow panel, and its items carry
1702
+ // notes ("from the whole workspace") that would otherwise
1703
+ // squeeze the label itself down to "C…".
1704
+ width="content"
1705
+ >
1706
+ {/* Everyone is public READ only (the grant route refuses the
1707
+ rest), so its row offers exactly the verb it can hold —
1708
+ plus Deny, which takes even that away. */}
1709
+ {(isEveryoneRole(p.principal) ? (['Can read'] as Role[]) : MENU_ROLES).map(
1710
+ (role, i) => {
1711
+ const checked = p.verbs[ROLE_TO_KEY[role]];
1712
+ const note = verbNote(p, ROLE_TO_VERB[role]);
1713
+ // Where a click on this item takes the row; null means
1714
+ // nowhere from here, and the item says so by being off.
1715
+ const next = nextVerbSet(p.verbs, role);
1716
+ return (
1717
+ // A Fragment, not a wrapper div: the items must stay
1718
+ // DIRECT children of the panel, which is the box the
1719
+ // menu measures and the keyboard walks.
1720
+ <Fragment key={role}>
1721
+ {/* Download is its own axis, not a lower tier — the
1722
+ rule the separator has always drawn. */}
1723
+ {role === 'Can download' && i > 0 && (
1724
+ <div className="my-1 border-t border-line" />
1725
+ )}
1726
+ <MenuItem
1727
+ disabled={busy || next === null}
1728
+ active={checked}
1729
+ aria-pressed={checked}
1730
+ // The note is the row's own explanation, not part of
1731
+ // what the item DOES: keep it out of the name ("Can
1732
+ // read"), and give it to assistive tech as the
1733
+ // description it is.
1734
+ aria-description={note}
1735
+ onClick={() => next && doApplyVerbSet(p, next)}
1736
+ trailing={
1737
+ <span className="flex items-center gap-1.5">
1738
+ {note && (
1739
+ // The note is what gives way when the panel
1740
+ // is at its cap, never the label: bounded and
1741
+ // truncated, with the full text on hover.
1742
+ <span
1743
+ aria-hidden
1744
+ title={note}
1745
+ className="max-w-44 truncate text-meta text-ink-faint"
1746
+ >
1747
+ {note}
1748
+ </span>
1749
+ )}
1750
+ {checked && <Check size={14} className="text-accent" />}
1751
+ </span>
1752
+ }
1753
+ >
1754
+ {role}
1755
+ </MenuItem>
1756
+ </Fragment>
1757
+ );
1758
+ },
1759
+ )}
1760
+ <div className="my-1 border-t border-line" />
1761
+ {/* Last, and the only destructive item: denies every verb here,
1762
+ read included. The row stays — the block is a rule about
1763
+ this person on this target, and this menu is where it is
1764
+ lifted again. */}
1765
+ <MenuItem
1766
+ tone="danger"
1767
+ disabled={busy}
1768
+ active={p.deniedHere}
1769
+ aria-description={`Block ${p.label} on this ${targetKind}, whatever a parent folder grants`}
1770
+ onClick={() => doApplyVerbSet(p, null)}
1771
+ trailing={p.deniedHere ? <Check size={14} className="text-danger" /> : undefined}
1772
+ >
1773
+ Deny
1774
+ </MenuItem>
1775
+ </AnchoredMenu>
1776
+ )}
1777
+ </div>
1778
+ {/* An external row has no entry here to remove — the verb menu can
1779
+ still write one (a denial), but Remove would have nothing to act
1780
+ on, so the slot stays empty and the row still lines up. */}
1781
+ {removeSlot(p.manage === 'external' ? null : p)}
1147
1782
  </div>
1148
1783
  ) : (
1149
1784
  <span className="ml-auto shrink-0 text-detail text-ink-muted">
@@ -1162,21 +1797,41 @@ export function ManageAccessDialog({
1162
1797
  title="Manage access"
1163
1798
  size="lg"
1164
1799
  footer={
1165
- <Button variant="primary" size="sm" onClick={onClose}>
1166
- Done
1167
- </Button>
1800
+ // One primary action, named for what it will do: Share while
1801
+ // anything is picked, Done when there is nothing to grant.
1802
+ pickedChips.length > 0 ? (
1803
+ <Button
1804
+ variant="primary"
1805
+ size="sm"
1806
+ disabled={grantVerbs.length === 0 || busy}
1807
+ onClick={doShare}
1808
+ leadingIcon={busy ? <Loader2 size={14} className="animate-spin" /> : undefined}
1809
+ >
1810
+ Share
1811
+ </Button>
1812
+ ) : (
1813
+ <Button variant="primary" size="sm" onClick={onClose}>
1814
+ Done
1815
+ </Button>
1816
+ )
1168
1817
  }
1169
1818
  >
1170
1819
  <p className="truncate text-detail text-ink-muted" title={entry.relativePath}>
1171
1820
  {entry.name}
1172
1821
  </p>
1173
1822
 
1823
+ {proposal && (
1824
+ <Banner tone="neutral" role="status" className="mt-3">
1825
+ {`You're editing access on change request #${proposal.number}. It takes effect when the request merges.`}
1826
+ </Banner>
1827
+ )}
1828
+
1174
1829
  {governed && canManage && (
1175
1830
  <div className="mt-3">
1176
- {/* `items-start`, not `items-stretch`: the buttons are `rounded-full`,
1177
- so stretching them to match the chip box turned Share into a
1178
- circle the moment a chip wrapped the box onto a second line.
1179
- `flex-wrap` lets them drop below the box rather than crushing it. */}
1831
+ {/* `items-start`, not `items-stretch`: the verb button is `rounded-full`,
1832
+ so stretching it to match the chip box turned it into a pill the
1833
+ height of the box the moment a chip wrapped onto a second line.
1834
+ `flex-wrap` lets it drop below the box rather than crushing it. */}
1180
1835
  <div className="relative flex flex-wrap items-start gap-1.5">
1181
1836
  <div className="relative min-w-48 flex-1">
1182
1837
  {/* A TextField that grew chips: same border, radius and focus
@@ -1184,16 +1839,32 @@ export function ManageAccessDialog({
1184
1839
  <div className="flex w-full flex-wrap items-center gap-1.5 rounded-md border border-line-strong bg-surface px-2 py-1 focus-within:border-transparent focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-accent">
1185
1840
  {pickedChips.map((c) => {
1186
1841
  const label = principalLabel(c);
1842
+ // Nobody has signed in as this address — say so, and grant
1843
+ // it anyway. Only an answer that ruled on this exact
1844
+ // address earns the note (see `lacksAccount`); until one
1845
+ // arrives the chip is simply unlabelled, never guessed at.
1846
+ const noAccount = c.kind === 'user' && lacksAccount(c.email);
1187
1847
  return (
1848
+ // `max-w-full` bounds the chip by the field it sits in, so a
1849
+ // long email can never push its own border past the box;
1850
+ // `min-w-0` lets the label inside it actually shrink (a flex
1851
+ // item's automatic minimum is its content, ellipsis or not).
1188
1852
  <span
1189
1853
  key={principalKey(c)}
1190
- className="inline-flex items-center gap-1 rounded-sm bg-sunken px-2 py-0.5 text-detail text-ink"
1854
+ className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-sm bg-sunken px-2 py-0.5 text-detail text-ink"
1191
1855
  >
1192
- {label}
1856
+ {/* The label is the only part that gives way — it
1857
+ truncates and carries the full name as its tooltip. */}
1858
+ <span className="min-w-0 truncate" title={label}>
1859
+ {label}
1860
+ </span>
1861
+ {noAccount && <NoAccountNote />}
1193
1862
  <button
1194
1863
  type="button"
1195
1864
  onClick={() => removeChip(c)}
1196
- className="rounded-xs text-ink-faint hover:text-danger"
1865
+ // `shrink-0`: the remove control stays whole and visible
1866
+ // at the end of the chip however long the label is.
1867
+ className="shrink-0 rounded-xs text-ink-faint hover:text-danger"
1197
1868
  aria-label={`Remove ${label}`}
1198
1869
  >
1199
1870
  <X size={12} />
@@ -1202,6 +1873,7 @@ export function ManageAccessDialog({
1202
1873
  );
1203
1874
  })}
1204
1875
  <input
1876
+ ref={queryInputRef}
1205
1877
  value={query}
1206
1878
  onChange={(e) => setQuery(e.target.value)}
1207
1879
  onKeyDown={(e) => {
@@ -1210,7 +1882,7 @@ export function ManageAccessDialog({
1210
1882
  addChip(addPending);
1211
1883
  }
1212
1884
  }}
1213
- placeholder={pickedChips.length ? '' : 'Add people, groups, or roles…'}
1885
+ placeholder={pickedChips.length ? '' : 'Add people, groups, roles or plugins…'}
1214
1886
  className="min-w-32 flex-1 bg-transparent px-1 py-1 text-ui text-ink placeholder:text-ink-faint focus:outline-none"
1215
1887
  />
1216
1888
  </div>
@@ -1218,55 +1890,71 @@ export function ManageAccessDialog({
1218
1890
  `roles` or `groups` (version skew) must degrade to an empty
1219
1891
  section, never a crash. Groups lead — they are the audience
1220
1892
  concept grants are meant for; roles remain grantable below. */}
1221
- {query.trim() && suggest && ((suggest.groups?.length ?? 0) > 0 || (suggest.roles?.length ?? 0) > 0 || (suggest.pluginPrincipals?.length ?? 0) > 0 || (suggest.people?.length ?? 0) > 0) && (
1893
+ {query.trim() && offered && offersAnything && (
1222
1894
  <AnchoredMenu width="anchor" align="left" className="max-h-56 overflow-auto">
1223
- {(suggest.groups ?? []).map((g) => (
1895
+ {offered.groups.map((g) => (
1224
1896
  <MenuItem
1225
1897
  key={`grp:${g}`}
1226
1898
  onClick={() => addChip({ kind: 'group', group: g })}
1227
1899
  trailing={
1228
- <span className="text-label uppercase text-ink-faint">group</span>
1900
+ <span
1901
+ className="text-label uppercase text-ink-faint"
1902
+ title={PRINCIPAL_KIND_HELP.group}
1903
+ aria-description={PRINCIPAL_KIND_HELP.group}
1904
+ >
1905
+ group
1906
+ </span>
1229
1907
  }
1230
1908
  >
1231
1909
  <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-sunken text-label font-bold text-ink-muted">
1232
- {initials(g)}
1910
+ {labelInitials(g)}
1233
1911
  </span>
1234
1912
  <span className="min-w-0 flex-1 truncate">{g}</span>
1235
1913
  </MenuItem>
1236
1914
  ))}
1237
- {(suggest.roles ?? []).map((g) => (
1915
+ {offered.roles.map((g) => (
1238
1916
  <MenuItem
1239
1917
  key={`g:${g}`}
1240
1918
  onClick={() => addChip({ kind: 'role', role: g })}
1241
1919
  trailing={
1242
- <span className="text-label uppercase text-ink-faint">role</span>
1920
+ <span
1921
+ className="text-label uppercase text-ink-faint"
1922
+ title={PRINCIPAL_KIND_HELP.role}
1923
+ aria-description={PRINCIPAL_KIND_HELP.role}
1924
+ >
1925
+ role
1926
+ </span>
1243
1927
  }
1244
1928
  >
1245
1929
  <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-sunken text-label font-bold text-ink-muted">
1246
- {initials(g)}
1930
+ {labelInitials(g)}
1247
1931
  </span>
1248
1932
  <span className="min-w-0 flex-1 truncate">{g}</span>
1249
1933
  </MenuItem>
1250
1934
  ))}
1251
1935
  {/* A plugin is three grantees — its readers, its writers, its
1252
1936
  owners — each following the plugin's own roster live. */}
1253
- {(suggest.pluginPrincipals ?? []).flatMap((name) =>
1254
- PLUGIN_PRINCIPAL_VERBS.map((verb) => (
1937
+ {offered.plugins.map(({ name, verb }) => (
1255
1938
  <MenuItem
1256
1939
  key={`pl:${name}/${verb}`}
1257
1940
  onClick={() => addChip({ kind: 'plugin', plugin: name, verb })}
1258
1941
  trailing={
1259
- <span className="text-label uppercase text-ink-faint">plugin</span>
1942
+ <span
1943
+ className="text-label uppercase text-ink-faint"
1944
+ title={PRINCIPAL_KIND_HELP.plugin}
1945
+ aria-description={PRINCIPAL_KIND_HELP.plugin}
1946
+ >
1947
+ plugin
1948
+ </span>
1260
1949
  }
1261
1950
  >
1262
1951
  <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-sunken text-label font-bold text-ink-muted">
1263
- {initials(name)}
1952
+ {labelInitials(name)}
1264
1953
  </span>
1265
1954
  <span className="min-w-0 flex-1 truncate">{pluginPrincipalLabel(name, verb)}</span>
1266
1955
  </MenuItem>
1267
- )),
1268
- )}
1269
- {(suggest.people ?? []).map((p) => {
1956
+ ))}
1957
+ {offered.people.map((p) => {
1270
1958
  const tone = avatarTone(p.name || p.email);
1271
1959
  return (
1272
1960
  <MenuItem
@@ -1292,8 +1980,38 @@ export function ManageAccessDialog({
1292
1980
  )}
1293
1981
  </div>
1294
1982
 
1983
+ {/* People, groups, roles and plugins are the words the field and
1984
+ its suggestions use; this says what each one is. */}
1985
+ <div className="flex h-8 shrink-0 items-center">
1986
+ <IconButton
1987
+ ref={kindHelpTriggerRef}
1988
+ aria-label="What can I share with?"
1989
+ aria-expanded={kindHelpOpen}
1990
+ active={kindHelpOpen}
1991
+ onClick={() => setKindHelpOpen((o) => !o)}
1992
+ >
1993
+ <CircleHelp size={16} />
1994
+ </IconButton>
1995
+ {kindHelpOpen && (
1996
+ <AnchoredMenu
1997
+ onDismiss={() => setKindHelpOpen(false)}
1998
+ triggerRef={kindHelpTriggerRef}
1999
+ width={320}
2000
+ >
2001
+ <ul aria-label="What can I share with?" className="flex flex-col gap-2 px-3 py-2">
2002
+ {(['user', 'group', 'role', 'plugin'] as const).map((k) => (
2003
+ <li key={k} className="text-detail leading-snug text-ink">
2004
+ {PRINCIPAL_KIND_HELP[k]}
2005
+ </li>
2006
+ ))}
2007
+ </ul>
2008
+ </AnchoredMenu>
2009
+ )}
2010
+ </div>
2011
+
1295
2012
  <div className="shrink-0">
1296
2013
  <Button
2014
+ ref={verbTriggerRef}
1297
2015
  variant="outline"
1298
2016
  size="sm"
1299
2017
  className="max-w-44"
@@ -1303,20 +2021,30 @@ export function ManageAccessDialog({
1303
2021
  <span className="truncate">{summarizeVerbs(effectiveNewVerbs)}</span>
1304
2022
  </Button>
1305
2023
  {verbOpen && (
1306
- <AnchoredMenu>
2024
+ <AnchoredMenu onDismiss={() => setVerbOpen(false)} triggerRef={verbTriggerRef}>
1307
2025
  {TIER_ROLES.map((role) => {
1308
2026
  const k = ROLE_TO_KEY[role];
1309
2027
  const checked = effectiveNewVerbs[k];
1310
- const disabled =
1311
- (role === 'Can edit' && effectiveNewVerbs.owner) ||
1312
- (role === 'Can read' && (effectiveNewVerbs.owner || effectiveNewVerbs.write));
2028
+ // Checked because another tick confers it: not a choice here.
2029
+ const disabled = conferredByOthers(newVerbs, k);
1313
2030
  return (
1314
2031
  <MenuItem
1315
2032
  key={role}
1316
2033
  disabled={disabled}
1317
2034
  active={checked}
1318
2035
  aria-pressed={checked}
1319
- onClick={() => setNewVerbs((v) => ({ ...v, [k]: !v[k] }))}
2036
+ onClick={() =>
2037
+ setNewVerbs((v) => {
2038
+ const on = !v[k];
2039
+ // Turning a tier OFF is "less than this", and less
2040
+ // than edit is read, not nothing: the Read the tier
2041
+ // implied stays selected in its own right. Read's
2042
+ // own item is the one that takes read away.
2043
+ return on || k === 'read'
2044
+ ? { ...v, [k]: on }
2045
+ : { ...v, [k]: false, read: true };
2046
+ })
2047
+ }
1320
2048
  trailing={checked ? <Check size={14} className="text-accent" /> : undefined}
1321
2049
  >
1322
2050
  {role}
@@ -1325,10 +2053,16 @@ export function ManageAccessDialog({
1325
2053
  })}
1326
2054
  <div className="my-1 border-t border-line" />
1327
2055
  <MenuItem
1328
- disabled={effectiveNewVerbs.owner}
2056
+ disabled={conferredByOthers(newVerbs, 'download')}
1329
2057
  active={effectiveNewVerbs.download}
1330
2058
  aria-pressed={effectiveNewVerbs.download}
1331
- onClick={() => setNewVerbs((v) => ({ ...v, download: !v.download }))}
2059
+ // Same rule as the tiers: unticking download keeps the
2060
+ // read it implied.
2061
+ onClick={() =>
2062
+ setNewVerbs((v) =>
2063
+ v.download ? { ...v, download: false, read: true } : { ...v, download: true },
2064
+ )
2065
+ }
1332
2066
  trailing={
1333
2067
  effectiveNewVerbs.download ? (
1334
2068
  <Check size={14} className="text-accent" />
@@ -1340,21 +2074,11 @@ export function ManageAccessDialog({
1340
2074
  </AnchoredMenu>
1341
2075
  )}
1342
2076
  </div>
1343
-
1344
- <Button
1345
- variant="primary"
1346
- size="sm"
1347
- className="shrink-0"
1348
- disabled={pickedChips.length === 0 || grantVerbs.length === 0 || busy}
1349
- onClick={doGrant}
1350
- leadingIcon={busy ? <Loader2 size={14} className="animate-spin" /> : undefined}
1351
- >
1352
- Share
1353
- </Button>
1354
2077
  </div>
2078
+ {reachLine}
1355
2079
  {query.trim() && !addPending && !suggest?.peopleWithheld && (
1356
2080
  <p className="mt-1.5 text-detail text-ink-muted">
1357
- Type a full email to add someone, or pick a group or role from the list.
2081
+ Type a full email to add someone, or pick a group, role or plugin from the list.
1358
2082
  </p>
1359
2083
  )}
1360
2084
  {pickedChips.some(isEveryoneRole) && (
@@ -1384,153 +2108,163 @@ export function ManageAccessDialog({
1384
2108
  </Banner>
1385
2109
  ) : (
1386
2110
  <>
1387
- {!canManage && (
1388
- <Banner tone="neutral" role="note" className="mt-3">
1389
- Only people with edit access can share this {targetKind}.
1390
- {ownerNames && <> Ask an owner: {ownerNames}.</>}
1391
- </Banner>
1392
- )}
1393
-
1394
- {/* Names WHICH RULE you are editing, and adapts to the target
1395
- (proto:3625: `On this ` + file|folder). The sheet mixes rules
1396
- set HERE with rules inherited from above, so a heading that
1397
- says only "People with access" leaves the reader to work out
1398
- which of the two lists below is which. The count rides it, as
1399
- on every band in the app. */}
1400
- <h3 className="mb-1 mt-4 flex items-baseline gap-2 text-label uppercase text-ink-faint">
1401
- On this {targetKind}
1402
- {directRows.length > 0 && (
1403
- <span className="text-meta normal-case tabular-nums">{directRows.length}</span>
1404
- )}
1405
- </h3>
1406
-
1407
- {/* A statement, not a control: it says the node is public and
1408
- why. Each reason is a grant with a row below — the Everyone
1409
- row for a literal line, the plugin's row for a public plugin
1410
- principal — and the row is where it is removed. */}
1411
- {data && !data.readers.restricted && (
1412
- <div className="flex items-center gap-3 py-1.5">
1413
- <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-ok-soft text-ok">
1414
- <Globe size={16} />
1415
- </span>
1416
- <div className="min-w-0 flex-1">
1417
- <div className="text-ui text-ink">Anyone can read</div>
1418
- <div className="text-detail text-ink-muted">
1419
- {`Public: every signed-in user can read this ${targetKind}${
1420
- publicReasons.length > 0 ? ` — ${publicReasons.join(', ')}` : ''
1421
- }.`}
1422
- </div>
1423
- </div>
1424
- </div>
1425
- )}
1426
-
1427
- {directRows.length === 0 ? (
1428
- <p className="py-2 text-ui text-ink-muted">
1429
- {inheritedRows.length > 0
1430
- ? 'No one is granted directly here. Everyone below inherits access from a parent folder.'
1431
- : 'No explicit grants at this path.'}
1432
- </p>
2111
+ {/* No field to sit under: the reach line leads the sheet instead. */}
2112
+ {!canManage && reachLine}
2113
+ {folderGoverns ? (
2114
+ <>
2115
+ {/* No field and no rules here: say where the rules are, and
2116
+ go there. Who can open the file is still worth knowing. */}
2117
+ <Banner tone="neutral" role="note" className="mt-3">
2118
+ {folderGovernsAccessMessage(governingFolderLabel)}
2119
+ </Banner>
2120
+ {onManageAncestor && kbDirName && (
2121
+ <Button
2122
+ variant="outline"
2123
+ size="sm"
2124
+ className="mt-2"
2125
+ title={governingFolder || WHOLE_WORKSPACE}
2126
+ onClick={() =>
2127
+ onManageAncestor({
2128
+ name: governingFolderLabel,
2129
+ relativePath: governingFolder ? `${kbDirName}/${governingFolder}` : kbDirName,
2130
+ type: 'directory',
2131
+ })
2132
+ }
2133
+ >
2134
+ {`Manage access on ${governingFolderLabel}`}
2135
+ </Button>
2136
+ )}
2137
+ <h3 className="mb-1 mt-4 flex items-baseline gap-2 text-label uppercase text-ink-faint">
2138
+ Who can open it
2139
+ {readerRows.length > 0 && (
2140
+ <span className="text-meta normal-case tabular-nums">{readerRows.length}</span>
2141
+ )}
2142
+ </h3>
2143
+ {readerRows.length === 0 ? (
2144
+ <p className="py-2 text-ui text-ink-muted">No one is named here.</p>
2145
+ ) : (
2146
+ readerRows.map(renderRow)
2147
+ )}
2148
+ </>
1433
2149
  ) : (
1434
- directRows.map(renderRow)
1435
- )}
2150
+ <>
2151
+ {!canManage && (
2152
+ <Banner tone="neutral" role="note" className="mt-3">
2153
+ Only people with edit access can share this {targetKind}.
2154
+ {ownerNames && <> Ask an owner: {ownerNames}.</>}
2155
+ </Banner>
2156
+ )}
1436
2157
 
1437
- {inheritedRows.length > 0 && (
1438
- <div className="mt-3 border-t border-line pt-2">
1439
- {inheritedByFolder.folders.map(([ancestor, rows]) => {
1440
- const open = openSection === ancestor;
1441
- return (
1442
- <div key={ancestor}>
1443
- <button
1444
- type="button"
1445
- aria-expanded={open}
1446
- title={folderPath(ancestor)}
1447
- onClick={() => setOpenSection(open ? null : ancestor)}
1448
- className="flex w-full items-center gap-1.5 rounded-xs py-1 text-detail text-ink-muted hover:text-ink"
1449
- >
1450
- <ChevronDown
1451
- size={14}
1452
- className={`shrink-0 transition-transform ${open ? 'rotate-180' : '-rotate-90'}`}
1453
- />
1454
- <span className="min-w-0 truncate">
1455
- People invited to <b className="font-semibold">{folderLabel(ancestor)}</b>
1456
- </span>
1457
- <span className="ml-auto shrink-0 tabular-nums text-ink-faint">
1458
- {rows.length}
1459
- </span>
1460
- </button>
1461
- {open && (
1462
- <div className="mb-1">
1463
- {rows.map(renderRow)}
1464
- {/* The folder is both what the heading means and
1465
- where it changes (proto:3647). Without this the
1466
- only act available on an inherited grant is the
1467
- destructive one behind Remove. */}
1468
- {onManageAncestor && kbDirName && (
1469
- <Button
1470
- variant="quiet"
1471
- size="tiny"
1472
- className="mt-0.5"
1473
- onClick={() => {
1474
- const dir = ancestor.replace(/\/?access\.md$/, '');
1475
- onManageAncestor({
1476
- // The same name the button just said. A
1477
- // root-level `access.md` leaves `dir` empty,
1478
- // and `''.split('/').pop()` is `''` — a
1479
- // dialog with no title.
1480
- name: folderLabel(ancestor),
1481
- relativePath: `${kbDirName}/${dir}`,
1482
- type: 'directory',
1483
- });
1484
- }}
1485
- >
1486
- {`Manage ${folderLabel(ancestor)} →`}
1487
- </Button>
2158
+ {/* Names WHICH RULE you are editing, and adapts to the target
2159
+ (proto:3625: `On this ` + file|folder). The sheet mixes rules
2160
+ set HERE with rules inherited from above, so a heading that
2161
+ says only "People with access" leaves the reader to work out
2162
+ which of the two lists below is which. The count rides it, as
2163
+ on every band in the app. */}
2164
+ <h3 className="mb-1 mt-4 flex items-baseline gap-2 text-label uppercase text-ink-faint">
2165
+ On this {targetKind}
2166
+ {directRows.length > 0 && (
2167
+ <span className="text-meta normal-case tabular-nums">{directRows.length}</span>
2168
+ )}
2169
+ </h3>
2170
+
2171
+ {directRows.length === 0 ? (
2172
+ <p className="py-2 text-ui text-ink-muted">
2173
+ {inheritedRows.length > 0
2174
+ ? 'No one is granted directly here. Everyone below inherits access from a parent folder.'
2175
+ : 'No explicit grants at this path.'}
2176
+ </p>
2177
+ ) : (
2178
+ directRows.map(renderRow)
2179
+ )}
2180
+
2181
+ {inheritedRows.length > 0 && (
2182
+ <div className="mt-3 border-t border-line pt-2">
2183
+ {inheritedByFolder.folders.map(([ancestor, rows]) => {
2184
+ const open = openSection === ancestor;
2185
+ return (
2186
+ <div key={ancestor}>
2187
+ <button
2188
+ type="button"
2189
+ aria-expanded={open}
2190
+ title={folderPath(ancestor)}
2191
+ onClick={() => setOpenSection(open ? null : ancestor)}
2192
+ className="flex w-full items-center gap-1.5 rounded-xs py-1 text-detail text-ink-muted hover:text-ink"
2193
+ >
2194
+ <ChevronDown
2195
+ size={14}
2196
+ className={`shrink-0 transition-transform ${open ? 'rotate-180' : '-rotate-90'}`}
2197
+ />
2198
+ <span className="min-w-0 truncate">
2199
+ People invited to <b className="font-semibold">{folderLabel(ancestor)}</b>
2200
+ </span>
2201
+ <span className="ml-auto shrink-0 tabular-nums text-ink-faint">
2202
+ {rows.length}
2203
+ </span>
2204
+ </button>
2205
+ {open && (
2206
+ <div className="mb-1">
2207
+ {rows.map(renderRow)}
2208
+ {/* The folder is both what the heading means and
2209
+ where it changes (proto:3647). Without this the
2210
+ only act available on an inherited grant is the
2211
+ destructive one behind Remove. */}
2212
+ {onManageAncestor && kbDirName && (
2213
+ <Button
2214
+ variant="quiet"
2215
+ size="tiny"
2216
+ className="mt-0.5"
2217
+ onClick={() => {
2218
+ const dir = ancestor.replace(/\/?access\.md$/, '');
2219
+ onManageAncestor({
2220
+ // The same name the button just said. A
2221
+ // root-level `access.md` leaves `dir` empty,
2222
+ // and `''.split('/').pop()` is `''` — a
2223
+ // dialog with no title.
2224
+ name: folderLabel(ancestor),
2225
+ relativePath: `${kbDirName}/${dir}`,
2226
+ type: 'directory',
2227
+ });
2228
+ }}
2229
+ >
2230
+ {`Manage ${folderLabel(ancestor)} →`}
2231
+ </Button>
2232
+ )}
2233
+ </div>
1488
2234
  )}
1489
2235
  </div>
1490
- )}
1491
- </div>
1492
- );
1493
- })}
1494
-
1495
- {/* A role that grants at the workspace level belongs to no
1496
- folder, so it cannot be filed under one. Named for what it
1497
- is rather than swept into the folder sections. */}
1498
- {inheritedByFolder.external.length > 0 && (
1499
- <div>
1500
- <button
1501
- type="button"
1502
- aria-expanded={openSection === 'roles'}
1503
- onClick={() => setOpenSection(openSection === 'roles' ? null : 'roles')}
1504
- className="flex w-full items-center gap-1.5 rounded-xs py-1 text-detail text-ink-muted hover:text-ink"
1505
- >
1506
- <ChevronDown
1507
- size={14}
1508
- className={`shrink-0 transition-transform ${openSection === 'roles' ? 'rotate-180' : '-rotate-90'}`}
1509
- />
1510
- <span className="min-w-0 truncate">People with access through a role</span>
1511
- <span className="ml-auto shrink-0 tabular-nums text-ink-faint">
1512
- {inheritedByFolder.external.length}
1513
- </span>
1514
- </button>
1515
- {openSection === 'roles' && (
1516
- <div className="mb-1">{inheritedByFolder.external.map(renderRow)}</div>
2236
+ );
2237
+ })}
2238
+
2239
+ {/* A role that grants at the workspace level belongs to no
2240
+ folder, so it cannot be filed under one. Named for what it
2241
+ is rather than swept into the folder sections. */}
2242
+ {inheritedByFolder.external.length > 0 && (
2243
+ <div>
2244
+ <button
2245
+ type="button"
2246
+ aria-expanded={openSection === 'roles'}
2247
+ onClick={() => setOpenSection(openSection === 'roles' ? null : 'roles')}
2248
+ className="flex w-full items-center gap-1.5 rounded-xs py-1 text-detail text-ink-muted hover:text-ink"
2249
+ >
2250
+ <ChevronDown
2251
+ size={14}
2252
+ className={`shrink-0 transition-transform ${openSection === 'roles' ? 'rotate-180' : '-rotate-90'}`}
2253
+ />
2254
+ <span className="min-w-0 truncate">People with access through a role</span>
2255
+ <span className="ml-auto shrink-0 tabular-nums text-ink-faint">
2256
+ {inheritedByFolder.external.length}
2257
+ </span>
2258
+ </button>
2259
+ {openSection === 'roles' && (
2260
+ <div className="mb-1">{inheritedByFolder.external.map(renderRow)}</div>
2261
+ )}
2262
+ </div>
1517
2263
  )}
1518
2264
  </div>
1519
2265
  )}
1520
- </div>
2266
+ </>
1521
2267
  )}
1522
-
1523
- <div className="mt-4 flex items-center gap-3 border-t border-line pt-4">
1524
- <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-sunken text-ink-muted">
1525
- <Lock size={16} />
1526
- </span>
1527
- <div className="flex-1">
1528
- <div className="text-ui font-semibold text-ink">Restricted</div>
1529
- <div className="text-detail text-ink-muted">
1530
- Only people granted access can edit this item.
1531
- </div>
1532
- </div>
1533
- </div>
1534
2268
  </>
1535
2269
  )}
1536
2270
  </Dialog>
@@ -1542,7 +2276,11 @@ export function ManageAccessDialog({
1542
2276
  onClose={() => setConfirmRemove(null)}
1543
2277
  size="md"
1544
2278
  title={
1545
- confirmRemove.ancestors.length ? 'Remove from parent folder?' : 'Restrict access here?'
2279
+ confirmRemove.ancestors.length === 1 && isRootAccessMd(confirmRemove.ancestors[0])
2280
+ ? `Remove from ${WHOLE_WORKSPACE}?`
2281
+ : confirmRemove.ancestors.length
2282
+ ? 'Remove from parent folder?'
2283
+ : 'Restrict access here?'
1546
2284
  }
1547
2285
  >
1548
2286
  {(() => {