@bevel-software/platform-core-frontend 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/package.json +5 -3
  2. package/src/core/CoreAppShell.tsx +195 -56
  3. package/src/core/__tests__/AppChrome.test.tsx +125 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +130 -95
  5. package/src/core/__tests__/bootstrap.test.ts +63 -0
  6. package/src/core/bootstrap.ts +73 -0
  7. package/src/core/events.ts +12 -0
  8. package/src/core/registry.ts +58 -9
  9. package/src/index.css +100 -11
  10. package/src/index.ts +24 -23
  11. package/src/lib/utils.ts +114 -138
  12. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +281 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +166 -1
  14. package/src/modules/access/api.ts +49 -0
  15. package/src/modules/access/components/ManageAccessDialog.tsx +786 -481
  16. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  17. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +86 -0
  18. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +172 -156
  19. package/src/modules/admin/__tests__/admin.unread.test.tsx +61 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +44 -38
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +11 -10
  22. package/src/modules/admin/components/UserAccountsPage.tsx +361 -353
  23. package/src/modules/admin/state/admin.context.tsx +15 -6
  24. package/src/modules/auth/components/AccountPage.tsx +11 -11
  25. package/src/modules/auth/components/LoginScreen.tsx +12 -12
  26. package/src/modules/auth/services/sso.ts +47 -1
  27. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +277 -0
  28. package/src/modules/change-requests/__tests__/author.test.ts +48 -0
  29. package/src/modules/change-requests/__tests__/conflict.test.ts +73 -0
  30. package/src/modules/change-requests/__tests__/diff.test.ts +134 -0
  31. package/src/modules/change-requests/__tests__/propose.test.ts +93 -0
  32. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +72 -0
  33. package/src/modules/change-requests/change-requests.css +22 -0
  34. package/src/modules/change-requests/components/ChangeBox.tsx +277 -0
  35. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +713 -0
  36. package/src/modules/change-requests/components/ConflictHelp.tsx +47 -0
  37. package/src/modules/change-requests/components/CrFileTree.tsx +398 -0
  38. package/src/modules/change-requests/components/FileChangeBoxes.tsx +168 -0
  39. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +236 -0
  40. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +79 -0
  41. package/src/modules/change-requests/hooks/useFileOnBranch.ts +80 -0
  42. package/src/modules/change-requests/services/change-requests.api.ts +45 -0
  43. package/src/modules/change-requests/services/propose.api.ts +162 -0
  44. package/src/modules/change-requests/utils/author.ts +47 -0
  45. package/src/modules/change-requests/utils/conflict.ts +38 -0
  46. package/src/modules/change-requests/utils/diff.ts +80 -0
  47. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +27 -18
  48. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +36 -83
  49. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +5 -5
  50. package/src/modules/git/__tests__/PullRequestsForMe.test.tsx +147 -0
  51. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +2 -8
  52. package/src/modules/git/components/BranchSwitcher.tsx +68 -31
  53. package/src/modules/git/components/DiffView.tsx +4 -4
  54. package/src/modules/git/components/FileComparisonPanel.tsx +20 -20
  55. package/src/modules/git/components/FileHistoryPanel.tsx +71 -107
  56. package/src/modules/git/components/PullNeededBanner.tsx +6 -13
  57. package/src/modules/git/components/PullRequestsForMe.tsx +71 -36
  58. package/src/modules/git/components/UnifiedDiffView.tsx +4 -4
  59. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +2 -2
  60. package/src/modules/git/hooks/useGitState.ts +15 -14
  61. package/src/modules/git/services/__tests__/error-messages.test.ts +4 -4
  62. package/src/modules/git/services/error-messages.ts +7 -7
  63. package/src/modules/git/services/git.api.ts +17 -11
  64. package/src/modules/git/services/pr-prompts.ts +2 -2
  65. package/src/modules/git/state/git.context.ts +10 -1
  66. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +224 -0
  67. package/src/modules/layout/__tests__/SidebarToggle.test.tsx +242 -0
  68. package/src/modules/layout/__tests__/breakpoints.test.ts +56 -0
  69. package/src/modules/layout/breakpoints.ts +6 -0
  70. package/src/modules/layout/components/AppLayout.tsx +17 -5
  71. package/src/modules/layout/components/DemoBanner.tsx +10 -1
  72. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -104
  73. package/src/modules/layout/components/MobileChatLayout.tsx +31 -26
  74. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +59 -24
  75. package/src/modules/layout/components/SidebarFrame.tsx +317 -0
  76. package/src/modules/layout/components/SidebarToggle.tsx +86 -0
  77. package/src/modules/layout/components/SlideOverlay.tsx +1 -1
  78. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +40 -2
  79. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +19 -3
  80. package/src/modules/layout/state/sidebar.ts +200 -0
  81. package/src/modules/library/__tests__/AddToGroupDialog.test.tsx +313 -0
  82. package/src/modules/library/__tests__/ChangeRequestDock.test.tsx +84 -0
  83. package/src/modules/library/__tests__/GroupJoinRequests.test.tsx +178 -0
  84. package/src/modules/library/__tests__/GroupPage.test.tsx +479 -0
  85. package/src/modules/library/__tests__/GroupsIndexPage.test.tsx +283 -0
  86. package/src/modules/library/__tests__/GroupsSidebar.contextmenu.test.tsx +175 -0
  87. package/src/modules/library/__tests__/GroupsSidebar.locked.test.tsx +96 -0
  88. package/src/modules/library/__tests__/GroupsSidebar.test.tsx +142 -0
  89. package/src/modules/library/__tests__/GroupsSidebarMenu.test.tsx +142 -0
  90. package/src/modules/library/__tests__/LibraryCard.test.tsx +149 -0
  91. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +378 -0
  92. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +347 -0
  93. package/src/modules/library/__tests__/LockedGroupView.test.tsx +203 -0
  94. package/src/modules/library/__tests__/NewGroupDialog.test.tsx +114 -0
  95. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +177 -0
  96. package/src/modules/library/__tests__/SkillPage.test.tsx +1063 -0
  97. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +259 -0
  98. package/src/modules/library/__tests__/ToolLogo.test.tsx +63 -0
  99. package/src/modules/library/__tests__/ToolPage.test.tsx +315 -0
  100. package/src/modules/library/__tests__/ToolSharePanel.test.tsx +36 -0
  101. package/src/modules/library/__tests__/ToolVarRow.test.tsx +260 -0
  102. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +197 -0
  103. package/src/modules/library/__tests__/auth-harness.tsx +37 -0
  104. package/src/modules/library/__tests__/oauth-fragment.test.ts +48 -0
  105. package/src/modules/library/__tests__/status.test.ts +210 -117
  106. package/src/modules/library/__tests__/useSkillDetail.test.tsx +102 -0
  107. package/src/modules/library/__tests__/useToolPage.test.tsx +146 -0
  108. package/src/modules/library/components/AccessRequestsBanner.tsx +101 -0
  109. package/src/modules/library/components/AddToGroupDialog.tsx +115 -0
  110. package/src/modules/library/components/ChangeRequestDock.tsx +71 -47
  111. package/src/modules/library/components/DeleteGroupDialog.tsx +87 -0
  112. package/src/modules/library/components/GroupIndexRow.tsx +63 -0
  113. package/src/modules/library/components/GroupJoinRequests.tsx +56 -0
  114. package/src/modules/library/components/GroupPage.tsx +373 -0
  115. package/src/modules/library/components/GroupsIndexPage.tsx +222 -0
  116. package/src/modules/library/components/GroupsSidebar.tsx +338 -0
  117. package/src/modules/library/components/GroupsSidebarMenu.tsx +160 -0
  118. package/src/modules/library/components/LibraryCard.tsx +153 -132
  119. package/src/modules/library/components/LibraryLayout.tsx +344 -0
  120. package/src/modules/library/components/LibraryPage.tsx +138 -254
  121. package/src/modules/library/components/LockGlyph.tsx +31 -0
  122. package/src/modules/library/components/LockedGroupView.tsx +159 -0
  123. package/src/modules/library/components/ManagedGroupRequests.tsx +70 -0
  124. package/src/modules/library/components/NewGroupDialog.tsx +112 -0
  125. package/src/modules/library/components/NewSkillPanel.tsx +151 -0
  126. package/src/modules/library/components/PageActions.tsx +156 -0
  127. package/src/modules/library/components/PendingSkillReview.tsx +63 -0
  128. package/src/modules/library/components/PersonalAddDialog.tsx +88 -0
  129. package/src/modules/library/components/PersonalGroupPage.tsx +125 -0
  130. package/src/modules/library/components/StatusDot.tsx +25 -0
  131. package/src/modules/library/components/ToolLogo.tsx +171 -0
  132. package/src/modules/library/components/group-page-parts.tsx +419 -0
  133. package/src/modules/library/components/skill-page/SkillFileEditor.tsx +134 -0
  134. package/src/modules/library/components/skill-page/SkillFilePane.tsx +117 -0
  135. package/src/modules/library/components/skill-page/SkillFileTabs.tsx +112 -0
  136. package/src/modules/library/components/skill-page/SkillPage.tsx +673 -0
  137. package/src/modules/library/components/skill-page/tab-ids.ts +33 -0
  138. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +175 -0
  139. package/src/modules/library/components/tool-page/ToolPage.tsx +228 -0
  140. package/src/modules/library/components/tool-page/ToolSharePanel.tsx +45 -0
  141. package/src/modules/library/components/tool-page/ToolVarRow.tsx +289 -0
  142. package/src/modules/library/hooks/useJoinRequests.ts +114 -0
  143. package/src/modules/library/hooks/useLibraryData.ts +134 -119
  144. package/src/modules/library/hooks/useSkillDetail.ts +119 -74
  145. package/src/modules/library/hooks/useToolPage.ts +145 -0
  146. package/src/modules/library/library.css +108 -320
  147. package/src/modules/library/routes/LibraryRoutes.tsx +134 -0
  148. package/src/modules/library/routes/WorkspaceItemRoute.tsx +74 -0
  149. package/src/modules/library/routes/library-paths.ts +191 -0
  150. package/src/modules/library/services/groups.api.ts +189 -0
  151. package/src/modules/library/services/library.api.ts +291 -164
  152. package/src/modules/library/services/tools.api.ts +60 -0
  153. package/src/modules/library/state/library-context.ts +22 -0
  154. package/src/modules/library/state/library-data.tsx +223 -0
  155. package/src/modules/library/state/toast.context.ts +32 -0
  156. package/src/modules/library/state/toast.tsx +84 -42
  157. package/src/modules/library/utils/clipboard.ts +33 -0
  158. package/src/modules/library/utils/group-summary.ts +68 -0
  159. package/src/modules/library/utils/names.ts +30 -0
  160. package/src/modules/library/utils/navigate-external.ts +15 -0
  161. package/src/modules/library/utils/oauth-fragment.ts +32 -0
  162. package/src/modules/library/utils/personal-group.ts +36 -0
  163. package/src/modules/library/utils/status.ts +199 -116
  164. package/src/modules/library/utils/toast-duration.ts +16 -0
  165. package/src/modules/onboarding/__tests__/onboarding.test.tsx +533 -0
  166. package/src/modules/onboarding/agent-clients.ts +48 -0
  167. package/src/modules/onboarding/components/ConnectAgentPill.tsx +133 -0
  168. package/src/modules/onboarding/components/RootLanding.tsx +54 -0
  169. package/src/modules/onboarding/components/WelcomePage.tsx +364 -0
  170. package/src/modules/onboarding/paths.ts +9 -0
  171. package/src/modules/onboarding/state/onboarding.ts +191 -0
  172. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +10 -10
  173. package/src/modules/pr/services/pr-approvals.api.ts +19 -0
  174. package/src/modules/pr/services/pr-cancel.api.ts +11 -0
  175. package/src/modules/review/components/BinaryChangePlaceholder.tsx +3 -3
  176. package/src/modules/review/components/DiffViewer.tsx +4 -4
  177. package/src/modules/review/components/MarkdownDiffViewer.tsx +84 -26
  178. package/src/modules/review/components/ReviewFileRow.tsx +10 -10
  179. package/src/modules/review/components/ReviewPanel.tsx +49 -17
  180. package/src/modules/review/components/ReviewPanelSurface.tsx +1 -1
  181. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +122 -0
  182. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +1 -1
  183. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +273 -171
  184. package/src/modules/secrets-vault/components/SecretsPage.tsx +313 -276
  185. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +109 -92
  186. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +82 -51
  187. package/src/modules/secrets-vault/services/connect.api.ts +24 -3
  188. package/src/modules/settings/components/DeploymentPage.tsx +90 -0
  189. package/src/modules/settings/components/SettingsLayout.tsx +135 -0
  190. package/src/modules/settings/components/SettingsNav.tsx +114 -0
  191. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +110 -0
  192. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +249 -0
  193. package/src/modules/settings/settings-nav-items.tsx +166 -0
  194. package/src/modules/setup/__tests__/setup.test.tsx +540 -0
  195. package/src/modules/setup/components/SetupGate.tsx +67 -0
  196. package/src/modules/setup/components/SetupScreen.tsx +573 -0
  197. package/src/modules/setup/services/setup.api.ts +106 -0
  198. package/src/modules/setup/utils/git-host.ts +34 -0
  199. package/src/modules/toolbar/components/AppSwitcher.tsx +131 -108
  200. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -548
  201. package/src/modules/toolbar/components/ProfileMenu.tsx +294 -0
  202. package/src/modules/toolbar/components/Toolbar.tsx +56 -54
  203. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +176 -122
  204. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +252 -77
  205. package/src/modules/tools/ToolsExplorerPage.tsx +45 -40
  206. package/src/modules/workspace/__tests__/design-system-parity.test.ts +133 -0
  207. package/src/modules/workspace/__tests__/testFixtures.ts +2 -0
  208. package/src/modules/workspace/components/EditorTabs.tsx +82 -50
  209. package/src/modules/workspace/components/FileExplorer.tsx +1292 -1068
  210. package/src/modules/workspace/components/FilePaneCard.tsx +53 -0
  211. package/src/modules/workspace/components/FileRoute.tsx +89 -84
  212. package/src/modules/workspace/components/FileViewer.tsx +1312 -906
  213. package/src/modules/workspace/components/KbDocumentShell.tsx +138 -0
  214. package/src/modules/workspace/components/KbFileRail.tsx +128 -0
  215. package/src/modules/workspace/components/KbPageHeader.tsx +390 -0
  216. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +87 -3
  217. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +293 -39
  218. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +1 -16
  219. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +462 -44
  220. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +84 -0
  221. package/src/modules/workspace/components/__tests__/KbFileRail.test.tsx +83 -0
  222. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +192 -0
  223. package/src/modules/workspace/components/renderers/CopyAnchorButton.tsx +64 -0
  224. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +8 -8
  225. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +18 -9
  226. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +14 -14
  227. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +2 -2
  228. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +31 -165
  229. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +18 -5
  230. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +27 -10
  231. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +2 -2
  232. package/src/modules/workspace/components/renderers/TextRenderer.tsx +11 -5
  233. package/src/modules/workspace/components/renderers/ToolForm.tsx +24 -24
  234. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +27 -27
  235. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -11
  236. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +66 -0
  237. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +17 -1
  238. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +1 -1
  239. package/src/modules/workspace/components/renderers/__tests__/MermaidDiagram.test.tsx +58 -0
  240. package/src/modules/workspace/components/renderers/__tests__/lazyRenderer.test.tsx +68 -0
  241. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +64 -0
  242. package/src/modules/workspace/components/renderers/__tests__/sanitizeDocxHtml.test.ts +0 -0
  243. package/src/modules/workspace/components/renderers/chunk-boundary.tsx +71 -0
  244. package/src/modules/workspace/components/renderers/index.ts +78 -2
  245. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +241 -0
  246. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +59 -0
  247. package/src/modules/workspace/components/renderers/sanitizeDocxHtml.ts +91 -0
  248. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +59 -0
  249. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +237 -0
  250. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +185 -0
  251. package/src/modules/workspace/hooks/useAutoGrowTextarea.ts +30 -0
  252. package/src/modules/workspace/hooks/useLastCommit.ts +66 -0
  253. package/src/modules/workspace/hooks/useLinksOut.ts +56 -0
  254. package/src/modules/workspace/hooks/useOpenChangeRequests.ts +20 -0
  255. package/src/modules/workspace/hooks/useWorkspaceState.ts +123 -14
  256. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +1 -1
  257. package/src/modules/workspace/services/workspace.api.ts +9 -2
  258. package/src/modules/workspace/state/open-change-requests.context.ts +35 -0
  259. package/src/modules/workspace/state/open-change-requests.tsx +185 -0
  260. package/src/modules/workspace/state/workspace.context.ts +9 -0
  261. package/src/modules/workspace/utils/__tests__/diff.test.ts +87 -0
  262. package/src/modules/workspace/utils/diff.ts +130 -53
  263. package/src/modules/workspace/utils/fileTree.ts +182 -179
  264. package/src/modules/workspace/workspace.css +28 -0
  265. package/src/shared/components/Badge.tsx +62 -0
  266. package/src/shared/components/Banner.tsx +58 -0
  267. package/src/shared/components/Button.tsx +90 -0
  268. package/src/shared/components/Dialog.tsx +6 -6
  269. package/src/shared/components/Field.tsx +45 -0
  270. package/src/shared/components/IconButton.tsx +74 -0
  271. package/src/shared/components/ListRow.tsx +96 -0
  272. package/src/shared/components/Menu.tsx +88 -0
  273. package/src/shared/components/PageShell.tsx +54 -51
  274. package/src/shared/components/Surface.tsx +86 -0
  275. package/src/shared/components/__tests__/primitives.test.tsx +333 -0
  276. package/src/shared/components/index.ts +48 -0
  277. package/src/shared/components/useDismissableMenu.ts +71 -0
  278. package/src/shared/theme/__tests__/accent-contrast.test.ts +84 -0
  279. package/src/shared/theme/index.css +12 -0
  280. package/src/shared/theme/measure.ts +64 -0
  281. package/src/shared/theme/shadows.css +34 -0
  282. package/src/shared/theme/tokens.css +193 -0
  283. package/src/test-setup.ts +9 -0
  284. package/src/modules/access/components/AccessRestrictedBanner.tsx +0 -31
  285. package/src/modules/access/components/NodeOwnersBanner.tsx +0 -30
  286. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +0 -82
  287. package/src/modules/git/components/ProtectedBranchBanner.tsx +0 -42
  288. package/src/modules/library/__tests__/DetailDialog.test.tsx +0 -200
  289. package/src/modules/library/__tests__/diff.test.ts +0 -62
  290. package/src/modules/library/__tests__/loadout.test.tsx +0 -72
  291. package/src/modules/library/components/CompareView.tsx +0 -357
  292. package/src/modules/library/components/DetailDialog.tsx +0 -566
  293. package/src/modules/library/components/GearIcon.tsx +0 -12
  294. package/src/modules/library/components/LoadoutSidebar.tsx +0 -156
  295. package/src/modules/library/components/StatusGem.tsx +0 -21
  296. package/src/modules/library/components/SuggestChange.tsx +0 -171
  297. package/src/modules/library/components/particles.ts +0 -50
  298. package/src/modules/library/state/loadout.tsx +0 -129
  299. package/src/modules/library/utils/diff.ts +0 -102
  300. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +0 -93
  301. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +0 -158
  302. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +0 -44
  303. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +0 -360
  304. package/src/modules/pr/__tests__/bucketize-comments.test.ts +0 -85
  305. package/src/modules/pr/__tests__/parsePatch.test.ts +0 -104
  306. package/src/modules/pr/__tests__/usePrViewerState.test.ts +0 -72
  307. package/src/modules/pr/components/PrApprovalBadge.tsx +0 -80
  308. package/src/modules/pr/components/PrCancelButton.tsx +0 -99
  309. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +0 -119
  310. package/src/modules/pr/components/PrCommentComposer.tsx +0 -92
  311. package/src/modules/pr/components/PrCommentThread.tsx +0 -168
  312. package/src/modules/pr/components/PrCommentsPanel.tsx +0 -143
  313. package/src/modules/pr/components/PrDiffPane.tsx +0 -425
  314. package/src/modules/pr/components/PrFileRow.tsx +0 -164
  315. package/src/modules/pr/components/PrFilesList.tsx +0 -53
  316. package/src/modules/pr/components/PrHeader.tsx +0 -45
  317. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +0 -58
  318. package/src/modules/pr/components/PrMergeButton.tsx +0 -268
  319. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +0 -112
  320. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +0 -110
  321. package/src/modules/pr/components/PrViewer.tsx +0 -364
  322. package/src/modules/pr/hooks/usePrViewerState.ts +0 -150
  323. package/src/modules/pr/state/pr-viewer.context.ts +0 -34
  324. package/src/modules/pr/utils/bucketize-comments.ts +0 -55
  325. package/src/modules/pr/utils/parsePatch.ts +0 -57
  326. package/src/modules/toolbar/components/AdminMenu.tsx +0 -271
@@ -1,906 +1,1312 @@
1
- import { useMemo, useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
2
- import { Check, XCircle, FileText, History, Clock4, GitCompare, Link2, Lock, Pencil, AlertTriangle } from 'lucide-react';
3
- import { useWorkspace } from '../state/workspace.context';
4
- import { EditorTabs } from './EditorTabs';
5
- import { useGit } from '../../git/state/git.context';
6
- import { useCanonicalFileUrl } from '../routing/kb-routes';
7
- import { useReview } from '../../review/state/review.context';
8
- import { ProtectedBranchBanner } from '../../git/components/ProtectedBranchBanner';
9
- import { PullNeededBanner } from '../../git/components/PullNeededBanner';
10
- import { useFileAccess } from '../../access/hooks/useFileAccess';
11
- import { AccessRestrictedBanner } from '../../access/components/AccessRestrictedBanner';
12
- import { NodeOwnersBanner } from '../../access/components/NodeOwnersBanner';
13
- import { FileHistoryPanel } from '../../git/components/FileHistoryPanel';
14
- import { FileComparisonPanel } from '../../git/components/FileComparisonPanel';
15
- import {
16
- OPEN_COMPARISON_EVENT,
17
- type OpenComparisonDetail,
18
- } from '../../../core/events';
19
- import {
20
- useAppRegistry,
21
- useSuggestedPromptSeed,
22
- } from '../../../core/registry';
23
- import { PrViewer } from '../../pr/components/PrViewer';
24
- import { useFileLock } from '../../workflow/hooks/useFileLock';
25
- import { LockApiError } from '../../workflow/services/lock.api';
26
- import { useAuth } from '../../auth/state/auth.context';
27
- import { getFileRenderer } from './renderers';
28
- import type { RendererSaveState } from './renderers';
29
-
30
- const SUGGESTED_PROMPTS = [
31
- 'Give me an overview of the process landscape.',
32
- 'What are the main process modules?',
33
- 'Show me the Registration & Onboarding processes.',
34
- ];
35
-
36
- export function FileViewer() {
37
- const {
38
- workspaceId,
39
- openFilePath,
40
- openFileContent,
41
- openFileSavedContent,
42
- setHasUnsavedFileChanges,
43
- setActiveTabContent,
44
- pendingFileContent,
45
- saveFile,
46
- fsRevision,
47
- acceptPendingContent,
48
- rejectPendingContent,
49
- addTab,
50
- refreshFileTree,
51
- bumpFsRevision,
52
- reloadTabFromDisk,
53
- } = useWorkspace();
54
- const [linkCopied, setLinkCopied] = useState(false);
55
- // Chat decoupling: the suggested-prompt seed is an optional registry port
56
- // (null when no chat surface is registered → the prompt buttons hide).
57
- const seedSuggestedPrompt = useSuggestedPromptSeed();
58
- const { fileViewerPanels, renderers } = useAppRegistry();
59
- const git = useGit();
60
- const review = useReview();
61
-
62
- // File-lock integration (PLAN §2). One useFileLock per (branch, file)
63
- // the user has open. Acquired on first dirty edit, released when the
64
- // editor unmounts or switches files. The hook handles heartbeat and
65
- // autosave checkpoints internally.
66
- const currentBranch = git.status?.branch ?? null;
67
- // `openFileContentRef` pins the latest in-memory buffer so the lock
68
- // hook's autosave timer can read it without re-subscribing on every
69
- // keystroke.
70
- const openFileContentRef = useRef<string | null>(openFileContent);
71
- useEffect(() => { openFileContentRef.current = openFileContent; }, [openFileContent]);
72
- // Stable read of the active path for async handlers that need to check
73
- // whether the user switched files mid-await.
74
- const openFilePathRef = useRef<string | null>(openFilePath);
75
- useEffect(() => { openFilePathRef.current = openFilePath; }, [openFilePath]);
76
- const persistToDisk = useCallback(async (content: string) => {
77
- if (!openFilePath) return;
78
- await saveFile(openFilePath, content);
79
- }, [openFilePath, saveFile]);
80
- const auth = useAuth();
81
- const fileLock = useFileLock({
82
- workspaceId,
83
- branch: currentBranch,
84
- path: openFilePath,
85
- // Lets the hook filter out "lock held by me" responses during the
86
- // window where a previous tab's release is still in flight, so
87
- // switching away and back doesn't flicker a self-locked banner.
88
- currentUserId: auth.user?.id ?? null,
89
- readPendingContent: () => openFileContentRef.current,
90
- persistToDisk,
91
- });
92
- // Editability is governed by roles.yaml + access.md, but only on
93
- // protected branches — drafts are free-for-all and the hook returns
94
- // canWrite=true for them without a network call. The hook returns
95
- // `canWrite: null` while the lookup is in flight; we treat that as
96
- // "allow editing optimistically" so the editor doesn't flicker between
97
- // disabled / enabled. On a hard `canWrite === false`, the editor goes
98
- // read-only and a banner explains who can change the file.
99
- const access = useFileAccess(openFilePath, currentBranch);
100
- const accessRestricted = access.canWrite === false;
101
- // Keep the existing variable name so the rest of the file (legacy uses for
102
- // dirty-flag bookkeeping etc.) doesn't need to change.
103
- const onProtectedBranch = accessRestricted;
104
- // `hasPendingReview` (the fact that a review session exists) suppresses the
105
- // legacy single-file Accept/Reject banner below so the two review UIs don't
106
- // compete. The review *surface* itself (badge + panel, with its own
107
- // open-intent state) is no longer hard-mounted here — it's a registered
108
- // panel (see `fileViewerPanels` / the enterprise ReviewPanelSurface), so
109
- // the core viewer carries no review-UI dependency.
110
- const hasPendingReview = !!review.session && review.session.changes.length > 0;
111
- // Registered auxiliary surfaces (e.g. the enterprise agent-review badge +
112
- // panel). Rendered on every return path exactly where the hard-mounted
113
- // review surface used to sit, inside this component's relative container so
114
- // absolutely-positioned panels anchor the same way.
115
- const registeredPanels = fileViewerPanels.map(({ id, Component }) => (
116
- <Component key={id} />
117
- ));
118
- // Registry renderer overrides win over the built-in extension map — the
119
- // enterprise registry swaps in its own `.html` renderer (vendored d3/mermaid
120
- // + KB graph client) this way.
121
- const Renderer = useMemo(() => {
122
- if (!openFilePath) return null;
123
- const ext = openFilePath.slice(openFilePath.lastIndexOf('.')).toLowerCase();
124
- const override = renderers.find((r) => r.extensions.includes(ext));
125
- return override?.Component ?? getFileRenderer(openFilePath);
126
- }, [openFilePath, renderers]);
127
-
128
- const [isSubmitting, setIsSubmitting] = useState(false);
129
- const [activeTab, setActiveTab] = useState<'content' | 'history' | 'compare'>('content');
130
- const [isManualDirty, setIsManualDirty] = useState(false);
131
- const [manualSaveState, setManualSaveState] = useState<RendererSaveState>('idle');
132
- // Last save-and-release failure, surfaced inline so a 422-with-validator
133
- // payload doesn't disappear into the console with the user assuming
134
- // their work landed. `kind: 'validation'` carries the structured KB
135
- // issue list; `kind: 'generic'` is the catch-all for everything else.
136
- const [saveError, setSaveError] = useState<
137
- | null
138
- | { kind: 'validation'; message: string; mustFix: Array<{ path?: string; message: string }> }
139
- | { kind: 'generic'; message: string }
140
- >(null);
141
- const [pendingDeferred, setPendingDeferred] = useState(false);
142
- const [hadPending, setHadPending] = useState(false);
143
- // Picker overrides set by the chat tool-card's "View full comparison" link.
144
- // Cleared when the user opens a different file so a deep-link doesn't stick
145
- // around and override their natural defaults on the next open.
146
- const [comparisonOverride, setComparisonOverride] = useState<{
147
- fromBranch: string;
148
- toBranch: string;
149
- } | null>(null);
150
- const historyAvailable = git.availability === 'ready';
151
- const hasUnsavedWork = isManualDirty || manualSaveState === 'saving';
152
-
153
- const hasPending = pendingFileContent !== null;
154
- const pendingJustArrived = hasPending && !hadPending;
155
- const shouldDeferPending = pendingDeferred || (pendingJustArrived && isManualDirty);
156
- const isReviewingPending = hasPending && !shouldDeferPending;
157
- const waitingOnAgentUpdate = hasPending && shouldDeferPending;
158
-
159
- // Reset to the content tab whenever the user opens a different file. Leaving
160
- // the tab sticky means someone who was viewing history on file A lands on the
161
- // history tab of file B, which is surprising — opening a file should default
162
- // to showing what's in it.
163
- useEffect(() => {
164
- setActiveTab('content');
165
- setIsManualDirty(false);
166
- setManualSaveState('idle');
167
- setSaveError(null);
168
- setPendingDeferred(false);
169
- setHadPending(false);
170
- setComparisonOverride(null);
171
- }, [openFilePath]);
172
-
173
- // Listen for the agent's chat tool-card "View full comparison" link. The
174
- // event carries the file path + both refs; we open the file (if needed),
175
- // jump to the Compare tab, and seed the pickers with the requested pair.
176
- useEffect(() => {
177
- const handler = (event: Event) => {
178
- const detail = (event as CustomEvent<OpenComparisonDetail>).detail;
179
- if (!detail || !detail.path || !detail.fromBranch || !detail.toBranch) return;
180
- setComparisonOverride({
181
- fromBranch: detail.fromBranch,
182
- toBranch: detail.toBranch,
183
- });
184
- setActiveTab('compare');
185
- if (detail.path !== openFilePath) {
186
- addTab(detail.path).catch((err) => {
187
- console.error('Failed to open compared file:', detail.path, err);
188
- const filename = detail.path.split('/').pop() ?? detail.path;
189
- const msg = err instanceof Error ? err.message : 'Unknown error';
190
- window.alert(`Failed to open file: ${filename}\n${msg}`);
191
- });
192
- }
193
- };
194
- window.addEventListener(OPEN_COMPARISON_EVENT, handler);
195
- return () => window.removeEventListener(OPEN_COMPARISON_EVENT, handler);
196
- }, [addTab, openFilePath]);
197
-
198
- useEffect(() => {
199
- setHasUnsavedFileChanges?.(hasUnsavedWork);
200
- }, [hasUnsavedWork, setHasUnsavedFileChanges]);
201
-
202
- useEffect(() => {
203
- return () => {
204
- setHasUnsavedFileChanges?.(false);
205
- };
206
- }, [setHasUnsavedFileChanges]);
207
-
208
- useEffect(() => {
209
- if (!hasUnsavedWork) return;
210
- const handler = (event: BeforeUnloadEvent) => {
211
- event.preventDefault();
212
- event.returnValue = '';
213
- };
214
- window.addEventListener('beforeunload', handler);
215
- return () => window.removeEventListener('beforeunload', handler);
216
- }, [hasUnsavedWork]);
217
-
218
- // If the agent writes while the user has unsaved edits, keep the manual buffer
219
- // intact and defer the pending preview until the user explicitly reviews it.
220
- useEffect(() => {
221
- const hasPendingNow = pendingFileContent !== null;
222
-
223
- if (!hasPendingNow) {
224
- setPendingDeferred(false);
225
- setHadPending(false);
226
- } else if (!hadPending) {
227
- setPendingDeferred(isManualDirty);
228
- setHadPending(true);
229
- }
230
- }, [pendingFileContent, isManualDirty, hadPending]);
231
-
232
- // Pending review / protected branches are read-only surfaces — ensure the file-
233
- // level dirty indicator does not stay latched from a prior editable state.
234
- useEffect(() => {
235
- if (onProtectedBranch || isReviewingPending) {
236
- setIsManualDirty(false);
237
- }
238
- }, [onProtectedBranch, isReviewingPending]);
239
-
240
- const handleRevertCompleted = useCallback(async () => {
241
- await refreshFileTree();
242
- // A revert writes to the working tree, so the active tab's cached content
243
- // is stale. Bump fs revision — the hook's invalidation effect refetches
244
- // the active tab, and if the file no longer exists (e.g. revert of its
245
- // creation), drops it from the tab list. The state→URL effect in
246
- // FileRoute then updates the URL to the new active tab.
247
- bumpFsRevision();
248
- await git.refreshStatus();
249
- // A revert writes to the working tree, so pending-review state may no
250
- // longer match what's on disk. Refresh the session before switching tabs
251
- // so the review panel reflects the reconciled paths.
252
- await review.refresh();
253
- setActiveTab('content');
254
- }, [refreshFileTree, bumpFsRevision, git, review]);
255
-
256
- const handleAccept = useCallback(async () => {
257
- if (isSubmitting) return;
258
- setIsSubmitting(true);
259
- try {
260
- await acceptPendingContent();
261
- setPendingDeferred(false);
262
- } finally {
263
- setIsSubmitting(false);
264
- }
265
- }, [isSubmitting, acceptPendingContent]);
266
-
267
- const handleReject = useCallback(async () => {
268
- if (isSubmitting) return;
269
- setIsSubmitting(true);
270
- try {
271
- await rejectPendingContent();
272
- setPendingDeferred(false);
273
- } finally {
274
- setIsSubmitting(false);
275
- }
276
- }, [isSubmitting, rejectPendingContent]);
277
-
278
- // **Edit mode is explicit** (the lock spec, simplified). Viewing a file
279
- // never claims the lock — the user clicks "Edit" to enter edit mode,
280
- // which acquires. Idle for 30s? `useFileLock` auto-releases and
281
- // `holdingLock` flips false; the effect below mirrors that into
282
- // `editMode` so the UI flips back to view. To resume editing, the
283
- // user clicks Edit again (which tries to acquire — may fail if
284
- // someone else grabbed it in the gap, in which case the banner says
285
- // who holds it).
286
- const [editMode, setEditMode] = useState(false);
287
- // True between the Edit click and the moment we've finished
288
- // acquiring + reloading. Renders the button as "Loading…" and
289
- // disables it so a double-click can't fire two acquires.
290
- const [isEnteringEdit, setIsEnteringEdit] = useState(false);
291
-
292
- // Mirror the lock state into edit mode, but only on a transition from
293
- // "we held the lock" to "we don't" — that's the idle-release /
294
- // heartbeat-failure case where we want the UI to flip back to View
295
- // automatically. We can't just check `!holdingLock && editMode` every
296
- // render: when the user first clicks Edit, `editMode` flips true
297
- // before `holdingLock` does (acquire is async), and a naive check
298
- // would immediately revert editMode to false, defeating the whole
299
- // mode transition. The previous-value ref kills that race.
300
- //
301
- // Done-then-Edit race guard: `handleExitEditMode` is optimistic and
302
- // fires `saveAndRelease` in the background. If the user clicks Edit
303
- // before that release completes, we'd see `holdingLock` transition
304
- // true→false (from Done's background release) AFTER `editMode` has
305
- // already been re-set to true by the Edit click — and the naive
306
- // mirror would revert editMode back to false. To avoid that, Done
307
- // stamps `lastDoneAtRef`; the mirror ignores transitions that fall
308
- // within a short window after Done (longer than a typical
309
- // commit+push round-trip on a normal network — Done's release
310
- // running >`DONE_RELEASE_WINDOW_MS` would be exceptional, and the
311
- // worst-case outcome is one extra Edit click to recover).
312
- const wasHoldingLockRef = useRef(false);
313
- const lastDoneAtRef = useRef(0);
314
- const DONE_RELEASE_WINDOW_MS = 5_000;
315
- useEffect(() => {
316
- const lostLock = wasHoldingLockRef.current && !fileLock.holdingLock;
317
- if (lostLock && editMode) {
318
- const withinDoneWindow = Date.now() - lastDoneAtRef.current < DONE_RELEASE_WINDOW_MS;
319
- if (!withinDoneWindow) {
320
- setEditMode(false);
321
- }
322
- }
323
- wasHoldingLockRef.current = fileLock.holdingLock;
324
- }, [fileLock.holdingLock, editMode]);
325
-
326
- // Reset edit mode when switching files — opening a new tab starts in
327
- // View mode regardless of which mode the previous tab was in. The
328
- // `isEnteringEdit` flag is cleared too so a switch-during-load
329
- // doesn't leave the new tab's button stuck in "Loading…".
330
- useEffect(() => {
331
- setEditMode(false);
332
- setIsEnteringEdit(false);
333
- }, [openFilePath, currentBranch, workspaceId]);
334
-
335
- // Monotonic token to scope each enter-edit flow's async completion to
336
- // the request that started it. When the user switches files mid-flow,
337
- // the `useEffect` reset on `openFilePath` clears `isEnteringEdit` and
338
- // bumps the token (via `setIsEnteringEdit(false)` then a new click
339
- // bumps); without comparing the captured token against the current
340
- // one, an old request's `.finally(() => setIsEnteringEdit(false))`
341
- // would clobber the new request's "Loading…" state on the new file.
342
- const enterEditRequestRef = useRef(0);
343
- const handleEnterEditMode = useCallback(() => {
344
- if (editMode || isEnteringEdit || !openFilePath || onProtectedBranch || isReviewingPending) return;
345
- // **Non-optimistic on entry.** We acquire the lock + reload disk
346
- // bytes FIRST, then flip into edit mode. The optimistic path —
347
- // setEditMode(true) sync, acquire + reload in the background —
348
- // is unsafe: any keystrokes typed in the window between the click
349
- // and the reload landing would be silently clobbered when fresh
350
- // disk bytes replace the buffer. The button shows a brief
351
- // "Loading…" state instead. (Exit-edit / Save stays optimistic;
352
- // see `handleExitEditMode` — that path is correctness-safe.)
353
- const targetPath = openFilePath;
354
- const requestId = ++enterEditRequestRef.current;
355
- const isStillCurrent = () =>
356
- requestId === enterEditRequestRef.current && openFilePathRef.current === targetPath;
357
- setIsEnteringEdit(true);
358
- fileLock.acquire()
359
- .then(async ({ acquired, contended, error }) => {
360
- if (!acquired) {
361
- // Two failure shapes:
362
- // - Contention (`contended`): held by someone else → the "Locked
363
- // by X" banner (below) already explains it; don't double-report.
364
- // - Access-denied 403 / network (`error`, not contended): surface
365
- // it. `useFileAccess` default-allows on a transient lookup
366
- // failure, so the editor lets the user click Edit even when the
367
- // authoritative backend gate refuses the lock. Without this the
368
- // click just flickers "Loading…" and nothing happens — the
369
- // write-denial equivalent of the file silently vanishing. We
370
- // read `error` off the resolved outcome, not `fileLock.lockError`
371
- // — the latter is React state and is stale in this closure.
372
- if (!isStillCurrent()) return;
373
- if (!contended && error) {
374
- setSaveError({ kind: 'generic', message: error });
375
- }
376
- return;
377
- }
378
- if (!isStillCurrent()) return;
379
- // Take-ownership reload: now that we hold the lock, refetch the
380
- // canonical bytes so we're editing on top of the latest
381
- // committed state even if a teammate's save echo hasn't
382
- // reached this client yet (slow SSE, dropped event, etc.).
383
- try {
384
- await reloadTabFromDisk(targetPath);
385
- } catch (err) {
386
- console.warn('[FileViewer] reload after acquire failed:', err);
387
- // Don't flip into edit mode if reload failed — editing on
388
- // top of state we couldn't verify risks the same stale-
389
- // overwrite the reload was meant to prevent. Also drop the
390
- // lock so the file isn't perpetually held while the user
391
- // sees no edit mode (best-effort; release failures fall to
392
- // the idle-release timer / unmount cleanup).
393
- fileLock.saveAndRelease().catch((relErr) => {
394
- console.warn('[FileViewer] release after reload failure failed:', relErr);
395
- });
396
- return;
397
- }
398
- // Stale-request check — file may have switched while we were
399
- // reloading. Don't flip editMode for the wrong file.
400
- if (!isStillCurrent()) return;
401
- setEditMode(true);
402
- })
403
- .catch((err) => {
404
- console.warn('[FileViewer] acquire on enter-edit failed:', err);
405
- })
406
- .finally(() => {
407
- // Only clear the loading flag if THIS request is still the
408
- // active one. A newer click already overwrote enterEditRequestRef
409
- // and its own `setIsEnteringEdit(true)` shouldn't get clobbered
410
- // back to false by an older request's finally.
411
- if (requestId === enterEditRequestRef.current) {
412
- setIsEnteringEdit(false);
413
- }
414
- });
415
- }, [editMode, isEnteringEdit, openFilePath, onProtectedBranch, isReviewingPending, fileLock, reloadTabFromDisk]);
416
-
417
- const handleExitEditMode = useCallback(() => {
418
- if (!editMode) return;
419
- // Flip to View mode SYNCHRONOUSLY. The actual save+commit+push that
420
- // `saveAndRelease` runs takes a full git-push round-trip (~1–3 s)
421
- // and we don't want the user staring at a frozen "Done" button
422
- // waiting for the network — they explicitly asked to leave edit
423
- // mode, the UI should respect that immediately.
424
- //
425
- // The save then continues in the background. The renderer is
426
- // already showing the post-edit content (it was the current
427
- // `value` when Done fired), so the user sees their work in View
428
- // mode while the bytes are persisted + committed + pushed behind
429
- // the scenes. The lock-released SSE event eventually clears the
430
- // server-side state for other clients.
431
- //
432
- // `lastDoneAtRef` is the race-guard for the case where the user
433
- // clicks Edit again BEFORE the background release completes — see
434
- // the mirror effect above. The Done timestamp lets that effect
435
- // distinguish "Done's release tail" (don't revert editMode the
436
- // user just re-set to true) from a genuine unexpected lock loss
437
- // (revert as usual).
438
- lastDoneAtRef.current = Date.now();
439
- setEditMode(false);
440
- setSaveError(null);
441
- fileLock.saveAndRelease().catch((err) => {
442
- // Push-needs-agent-resolution is GONE from the user-visible path.
443
- // Under the pending-commits queue, release just drops the lock
444
- // and enqueues a commit; if the eventual background commit /
445
- // push fails, the worker spawns a recovery agent silently.
446
- // Nothing surfaces here.
447
- console.error('[FileViewer] background save+release after Done failed:', err);
448
- // Surface non-resolution failures inline. Three shapes we care about:
449
- // - 422 with a `validation` payload → render the mustFix list
450
- // so the user can see which KB issues are blocking the commit
451
- // (per CLAUDE.md the validator gates EVERY commit, even
452
- // unrelated edits — without this UI the failure looks silent).
453
- // - other LockApiError → render the server message
454
- // - anything else → render the JS message
455
- // Either way we revert to edit mode so the user is back in the
456
- // editor (and can navigate to the failing path / retry).
457
- setEditMode(true);
458
- const validation = (err instanceof LockApiError
459
- ? (err.body as { validation?: { mustFix?: Array<{ path?: string; message: string }> } } | undefined)?.validation
460
- : undefined);
461
- if (validation && Array.isArray(validation.mustFix) && validation.mustFix.length > 0) {
462
- setSaveError({
463
- kind: 'validation',
464
- message: err instanceof Error ? err.message : 'Save was rejected by the validator.',
465
- mustFix: validation.mustFix,
466
- });
467
- } else {
468
- setSaveError({
469
- kind: 'generic',
470
- message: err instanceof Error ? err.message : 'Save failed. Please try again.',
471
- });
472
- }
473
- });
474
- }, [editMode, fileLock]);
475
-
476
- // Save flow (PLAN §2):
477
- // - Lock is already held because we're in edit mode (handleEnterEditMode
478
- // guarantees it). Save = checkpoint commit, lock stays held so
479
- // subsequent keystrokes don't have to re-acquire.
480
- // - Final commit + release happens on exit-edit, unmount, file switch,
481
- // or 30s idle (the hook's idle timer).
482
- const handleSave = useCallback(async (content: string) => {
483
- if (!openFilePath) return;
484
- openFileContentRef.current = content;
485
- if (!fileLock.holdingLock) {
486
- // Defensive: this path runs when a save fires without us being in
487
- // edit mode (rare — renderer is readOnly when !editMode, so
488
- // normally only the explicit Edit-button + saveCheckpoint flow
489
- // reaches here). Acquire the lock, commit-and-release as a
490
- // one-shot, and stay in View mode. We deliberately do NOT call
491
- // `setEditMode(true)` — the user didn't ask to enter Edit mode,
492
- // they just hit save, so the UI shouldn't silently promote them.
493
- // `saveAndRelease` handles the full commit-then-release-then-
494
- // push cycle in one call.
495
- const { acquired, error } = await fileLock.acquire();
496
- if (!acquired) {
497
- // Read the message off the resolved outcome, not `fileLock.lockError`
498
- // — that's React state and is stale in this closure right after the
499
- // await. Covers both the access-denied 403 and lock-contention cases.
500
- throw new Error(error ?? 'File is locked by another user.');
501
- }
502
- try {
503
- await fileLock.saveAndRelease();
504
- } catch (error) {
505
- console.error('Failed transient save:', error);
506
- throw error;
507
- }
508
- return;
509
- }
510
- try {
511
- await fileLock.saveCheckpoint();
512
- } catch (error) {
513
- console.error('Failed to save file:', error);
514
- throw error;
515
- }
516
- }, [openFilePath, fileLock]);
517
-
518
- // Track keystroke + scroll activity so the lock hook's idle timer
519
- // resets while the user is doing anything with the file. Without
520
- // this, a long meeting spent reading the file would auto-release.
521
- const recordActivity = fileLock.recordActivity;
522
- const handleValueChange = useCallback((value: string) => {
523
- recordActivity();
524
- setActiveTabContent(value);
525
- }, [recordActivity, setActiveTabContent]);
526
-
527
- // Scroll handler attached to the editor container. Any scroll within
528
- // the file counts as activity — the user is reading, even if not
529
- // typing. Without this, a long meeting spent reading the file would
530
- // auto-release the lock just because nothing was typed.
531
- const editorContainerRef = useRef<HTMLDivElement>(null);
532
- useEffect(() => {
533
- const el = editorContainerRef.current;
534
- if (!el || !editMode) return;
535
- const onScroll = () => recordActivity();
536
- // Capture-phase so a scroll on a nested element (the editor
537
- // textarea, a code-mirror viewport, etc.) reaches us without the
538
- // child having to bubble. Passive so we don't block the scroll.
539
- el.addEventListener('scroll', onScroll, { capture: true, passive: true });
540
- return () => el.removeEventListener('scroll', onScroll, { capture: true } as EventListenerOptions);
541
- }, [editMode, recordActivity]);
542
-
543
- // No-op save when previewing pending content — don't let edits go through during review
544
- const handlePendingSave = useCallback(async () => {}, []);
545
-
546
- const handleReviewAgentUpdate = useCallback(() => {
547
- if (!waitingOnAgentUpdate || isManualDirty) return;
548
- setPendingDeferred(false);
549
- }, [waitingOnAgentUpdate, isManualDirty]);
550
-
551
- // Canonical link for the open file: the node's id URL when it's a node, else
552
- // its path URL (resolved in the background, falls back to the path meanwhile).
553
- const canonicalFileUrl = useCanonicalFileUrl(openFilePath);
554
- const handleCopyLink = useCallback(async () => {
555
- try {
556
- const base = canonicalFileUrl ?? `${window.location.origin}${window.location.pathname}`;
557
- await navigator.clipboard.writeText(base + window.location.hash);
558
- setLinkCopied(true);
559
- window.setTimeout(() => setLinkCopied(false), 1500);
560
- } catch (err) {
561
- console.error('Failed to copy link:', err);
562
- }
563
- }, [canonicalFileUrl]);
564
-
565
-
566
- if (!openFilePath || openFileContent === null || !Renderer) {
567
- return (
568
- <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
569
- <ProtectedBranchBanner />
570
- <PullNeededBanner />
571
- <EditorTabs />
572
- <div className="flex-1 flex items-center justify-center px-6">
573
- <div className="max-w-md text-center">
574
- <h2 className="text-slate-900 text-base font-medium tracking-tight mb-2">
575
- Open a file, or ask the process assistant a question.
576
- </h2>
577
- <p className="text-slate-600 text-sm mb-6">
578
- Pick anything from the file tree, or start with a suggestion.
579
- </p>
580
- {/* Suggested prompts seed the chat composer — only rendered when a
581
- chat surface registered the seed port. */}
582
- {seedSuggestedPrompt && (
583
- <div className="flex flex-col gap-2">
584
- {SUGGESTED_PROMPTS.map((prompt) => (
585
- <button
586
- key={prompt}
587
- type="button"
588
- onClick={() => seedSuggestedPrompt(prompt)}
589
- className="text-left text-sm text-slate-700 bg-slate-100/80 hover:bg-slate-100 border border-slate-200 hover:border-slate-300 rounded-lg px-3 py-2 transition-colors duration-150"
590
- >
591
- {prompt}
592
- </button>
593
- ))}
594
- </div>
595
- )}
596
- </div>
597
- </div>
598
- {registeredPanels}
599
- <PrViewer />
600
- </div>
601
- );
602
- }
603
-
604
- const lastSlash = openFilePath.lastIndexOf('/');
605
- const fileName = lastSlash >= 0 ? openFilePath.slice(lastSlash + 1) : openFilePath;
606
- const parentDir = lastSlash >= 0 ? openFilePath.slice(0, lastSlash) : '';
607
-
608
- return (
609
- <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
610
- <ProtectedBranchBanner />
611
- <PullNeededBanner />
612
- {accessRestricted && openFilePath && (
613
- <AccessRestrictedBanner path={openFilePath} eligible={access.eligible} />
614
- )}
615
- {openFilePath && <NodeOwnersBanner owners={access.owners} />}
616
- <EditorTabs />
617
- {/* Active-file metadata + sub-tabs (Content / History / Compare) */}
618
- <div className="h-10 border-b border-slate-200 flex items-center px-3 gap-2 shrink-0">
619
- <span className="text-sm font-medium tracking-tight text-slate-900 truncate shrink-0">
620
- {fileName}
621
- </span>
622
- {parentDir && (
623
- <span className="text-xs text-slate-600 truncate min-w-0">
624
- {parentDir}
625
- </span>
626
- )}
627
- {isManualDirty && (
628
- <span className="ml-1 inline-flex items-center gap-1 text-xs text-amber-700 font-medium">
629
- <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />
630
- Unsaved
631
- </span>
632
- )}
633
- {waitingOnAgentUpdate && (
634
- <span className="ml-1 inline-flex items-center gap-1 text-xs text-amber-700 font-medium">
635
- <Clock4 size={12} />
636
- Agent update waiting
637
- </span>
638
- )}
639
- {isReviewingPending && (
640
- <span className="ml-1 inline-flex items-center gap-1 text-xs text-emerald-600 font-medium">
641
- <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
642
- Reviewing agent update
643
- </span>
644
- )}
645
- <div className="ml-auto flex items-center gap-1">
646
- <TabButton
647
- active={activeTab === 'content'}
648
- onClick={() => setActiveTab('content')}
649
- icon={<FileText size={12} />}
650
- label="Content"
651
- />
652
- {historyAvailable && (
653
- <TabButton
654
- active={activeTab === 'history'}
655
- onClick={() => setActiveTab('history')}
656
- icon={<History size={12} />}
657
- label="History"
658
- />
659
- )}
660
- {historyAvailable && (
661
- <TabButton
662
- active={activeTab === 'compare'}
663
- onClick={() => setActiveTab('compare')}
664
- icon={<GitCompare size={12} />}
665
- label="Compare"
666
- />
667
- )}
668
- <button
669
- onClick={handleCopyLink}
670
- className="ml-1 p-1 rounded hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-colors duration-150 relative"
671
- title={linkCopied ? 'Link copied' : 'Copy link to this file'}
672
- aria-label="Copy link to this file"
673
- >
674
- <Link2 size={14} />
675
- {linkCopied && (
676
- <span className="absolute top-full right-0 mt-1 px-1.5 py-0.5 rounded bg-slate-900 text-[10px] text-emerald-300 whitespace-nowrap pointer-events-none">
677
- Link copied
678
- </span>
679
- )}
680
- </button>
681
- {/* Edit / Save toggle. Hidden on protected branches (read-only)
682
- and while reviewing a pending agent update (the Accept/Reject
683
- banner owns the workflow there). Disabled when someone else
684
- holds the lock — the existing lock banner explains who. Both
685
- states use the same emerald palette so the toolbar reads as
686
- "one action button changing its label" rather than two
687
- competing controls. */}
688
- {!onProtectedBranch && !isReviewingPending && activeTab === 'content' && (
689
- editMode ? (
690
- <button
691
- onClick={handleExitEditMode}
692
- className="ml-1 flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-emerald-700 text-white hover:bg-emerald-600 transition-colors"
693
- title="Save changes and return to view mode"
694
- >
695
- <Check size={12} />
696
- Save
697
- </button>
698
- ) : (
699
- <button
700
- onClick={handleEnterEditMode}
701
- disabled={!!fileLock.externalLock || isEnteringEdit}
702
- className="ml-1 flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-emerald-700 text-white hover:bg-emerald-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
703
- title={
704
- fileLock.externalLock
705
- ? `Locked by ${fileLock.externalLock.holderName}`
706
- : isEnteringEdit
707
- ? 'Acquiring lock and fetching latest content…'
708
- : 'Click to edit this file'
709
- }
710
- >
711
- <Pencil size={12} />
712
- {isEnteringEdit ? 'Loading…' : 'Edit'}
713
- </button>
714
- )
715
- )}
716
- </div>
717
- </div>
718
-
719
- {activeTab === 'history' && historyAvailable ? (
720
- <FileHistoryPanel
721
- filePath={openFilePath}
722
- onRevertCompleted={handleRevertCompleted}
723
- />
724
- ) : activeTab === 'compare' && historyAvailable ? (
725
- <FileComparisonPanel
726
- filePath={openFilePath}
727
- initialFrom={comparisonOverride?.fromBranch ?? null}
728
- initialTo={comparisonOverride?.toBranch ?? null}
729
- refreshKey={fsRevision}
730
- />
731
- ) : (
732
- <>
733
- {waitingOnAgentUpdate && (
734
- <div role="status" aria-live="polite" aria-atomic="true" className="flex items-center gap-2 px-3 py-2 bg-amber-50 border-b border-amber-200 shrink-0">
735
- <span className="text-xs text-amber-800 flex-1">
736
- Agent update is waiting. Save or undo your unsaved edits before reviewing it.
737
- </span>
738
- <button
739
- onClick={handleReviewAgentUpdate}
740
- disabled={isManualDirty}
741
- className="px-2.5 py-1 rounded text-xs font-medium bg-amber-700 hover:bg-amber-600 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
742
- title={isManualDirty ? 'Finish local edits first' : 'Open the agent update preview'}
743
- >
744
- Review agent update
745
- </button>
746
- </div>
747
- )}
748
- {/* Accept / Reject banner — hidden whenever a multi-file review
749
- session exists, so the two review UIs never compete (regardless
750
- of whether the multi-file panel is currently open). */}
751
- {isReviewingPending && !hasPendingReview && (
752
- <div role="status" aria-live="polite" aria-atomic="true" className="flex items-center gap-2 px-3 py-2 bg-slate-100 border-b border-slate-300 shrink-0">
753
- <span className="text-xs text-slate-700 flex-1">
754
- Previewing agent's changes — accept to keep, reject to undo
755
- </span>
756
- <button
757
- onClick={handleReject}
758
- disabled={isSubmitting}
759
- className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-200 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
760
- >
761
- <XCircle size={13} />
762
- Reject
763
- </button>
764
- <button
765
- onClick={handleAccept}
766
- disabled={isSubmitting}
767
- className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium bg-emerald-700 hover:bg-emerald-600 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
768
- >
769
- <Check size={13} />
770
- Accept
771
- </button>
772
- </div>
773
- )}
774
-
775
- {/* Lock-by-someone-else banner — read-only state until the holder releases. */}
776
- {fileLock.externalLock && !fileLock.holdingLock && !isReviewingPending && !onProtectedBranch && (
777
- <div role="status" aria-live="polite" aria-atomic="true" className="flex items-center gap-2 px-3 py-2 bg-amber-50 border-b border-amber-200 shrink-0">
778
- <Lock size={14} className="text-amber-700 shrink-0" />
779
- <span className="text-xs text-amber-800 flex-1">
780
- Locked by <span className="font-medium">{fileLock.externalLock.holderName}</span>. The editor is read-only until they finish.
781
- </span>
782
- </div>
783
- )}
784
-
785
- {/* Save-failure banner. Validator failures carry a structured
786
- `mustFix` list which we render so the user can see which KB
787
- issues are blocking the commit (the validator gates ALL
788
- commits, even unrelated edits — without this UI the failure
789
- looks silent and the user keeps clicking Save). */}
790
- {saveError && (
791
- <div role="alert" aria-live="assertive" className="flex flex-col gap-2 px-3 py-2 bg-red-50 border-b border-red-200 shrink-0">
792
- <div className="flex items-center gap-2">
793
- <AlertTriangle size={14} className="text-red-700 shrink-0" />
794
- <span className="text-xs text-red-800 flex-1 font-medium">{saveError.message}</span>
795
- <button
796
- type="button"
797
- onClick={() => setSaveError(null)}
798
- className="text-red-700 hover:text-red-900 text-xs underline"
799
- title="Dismiss"
800
- >
801
- Dismiss
802
- </button>
803
- </div>
804
- {saveError.kind === 'validation' && saveError.mustFix.length > 0 && (
805
- <ul className="text-xs text-red-800 ml-6 list-disc space-y-0.5 max-h-32 overflow-y-auto">
806
- {saveError.mustFix.slice(0, 20).map((issue, i) => (
807
- <li key={i}>
808
- {issue.path && <span className="font-mono">{issue.path}</span>}
809
- {issue.path && ': '}
810
- {issue.message}
811
- </li>
812
- ))}
813
- {saveError.mustFix.length > 20 && (
814
- <li className="italic">…and {saveError.mustFix.length - 20} more</li>
815
- )}
816
- </ul>
817
- )}
818
- </div>
819
- )}
820
-
821
- {/* Review-action failure banner. Rejecting an agent change is
822
- optimistic — the row leaves the panel immediately — so a
823
- background commit/push failure would otherwise be silent. This
824
- surfaces it (and survives the review panel optimistically
825
- unmounting on a failed "Reject all"). */}
826
- {review.lastError && (
827
- <div role="alert" aria-live="assertive" className="flex items-center gap-2 px-3 py-2 bg-red-50 border-b border-red-200 shrink-0">
828
- <AlertTriangle size={14} className="text-red-700 shrink-0" />
829
- <span className="text-xs text-red-800 flex-1 font-medium">{review.lastError}</span>
830
- <button
831
- type="button"
832
- onClick={() => review.clearError()}
833
- className="text-red-700 hover:text-red-900 text-xs underline"
834
- title="Dismiss"
835
- >
836
- Dismiss
837
- </button>
838
- </div>
839
- )}
840
-
841
- {/* File content — show pending (new) content when reviewing, accepted content otherwise.
842
- Lock semantics: the editor is read-only whenever we're not in
843
- explicit Edit mode. Edit mode is gated by the lock, so this
844
- also covers "someone else holds it" without a separate check.
845
- `editorContainerRef` is the scroll-activity source for the
846
- idle-release timer. */}
847
- <div ref={editorContainerRef} className="flex-1 overflow-hidden p-4">
848
- <Renderer
849
- // **Why we key on `openFileSavedContent` (read-only mode only).**
850
- // When a teammate's save lands, the workspace state updates the
851
- // tab's content + savedContent. The renderer's internal
852
- // `useState(content)` + sync-on-prop-change `useEffect` is
853
- // supposed to pull the new value into `value`, but in practice
854
- // (production build, multiple suspended subscribers, etc.) we
855
- // were seeing the preview stay on the stale buffer until the
856
- // user manually closed + reopened the tab. Keying the renderer
857
- // on the bytes themselves forces a fresh mount when those
858
- // bytes change, which initializes `value` from the latest
859
- // content prop directly and bypasses any stuck-state edge
860
- // case. We gate this on `!editMode` so the user's in-flight
861
- // edits (where `value` diverges from `savedContent`) don't
862
- // trigger a remount that would discard their typing —
863
- // savedContent stays stable through an edit until the save
864
- // commits, then advances once.
865
- key={editMode ? `${openFilePath}|edit` : `${openFilePath}|${openFileSavedContent?.length ?? 0}|${openFileSavedContent?.slice(0, 64) ?? ''}|${openFileSavedContent?.slice(-64) ?? ''}`}
866
- content={isReviewingPending ? pendingFileContent! : openFileContent}
867
- savedContent={isReviewingPending ? pendingFileContent! : (openFileSavedContent ?? openFileContent)}
868
- filePath={openFilePath}
869
- onSave={isReviewingPending || onProtectedBranch ? handlePendingSave : handleSave}
870
- onDirtyChange={setIsManualDirty}
871
- onValueChange={isReviewingPending || onProtectedBranch || !editMode ? undefined : handleValueChange}
872
- onSaveStateChange={setManualSaveState}
873
- readOnly={isReviewingPending || onProtectedBranch || !editMode}
874
- />
875
- </div>
876
- </>
877
- )}
878
- {registeredPanels}
879
- <PrViewer />
880
- </div>
881
- );
882
- }
883
-
884
- interface TabButtonProps {
885
- active: boolean;
886
- onClick(): void;
887
- icon: ReactNode;
888
- label: string;
889
- }
890
-
891
- function TabButton({ active, onClick, icon, label }: TabButtonProps) {
892
- return (
893
- <button
894
- type="button"
895
- onClick={onClick}
896
- className={`flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-colors ${
897
- active
898
- ? 'bg-slate-100 text-slate-900'
899
- : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100/80'
900
- }`}
901
- >
902
- {icon}
903
- {label}
904
- </button>
905
- );
906
- }
1
+ import { useMemo, useCallback, useContext, useEffect, useRef, useState } from 'react';
2
+ import { Check, XCircle, Lock, AlertTriangle, ArrowLeft } from 'lucide-react';
3
+ import type { FileTreeEntry, PullRequestSummary } from '@bevel-software/platform-shared';
4
+ import { useWorkspace } from '../state/workspace.context';
5
+ import { EditorTabs } from './EditorTabs';
6
+ import { KbPageHeader } from './KbPageHeader';
7
+ import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
8
+ import { Banner, Button, Surface } from '../../../shared/components';
9
+ import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
10
+ import { useGit } from '../../git/state/git.context';
11
+ import { LayoutContext } from '../../layout/state/layout.context';
12
+ import { useCanonicalFileUrl } from '../routing/kb-routes';
13
+ import { PullNeededBanner } from '../../git/components/PullNeededBanner';
14
+ import { useFileAccess } from '../../access/hooks/useFileAccess';
15
+ import { FileHistoryPanel } from '../../git/components/FileHistoryPanel';
16
+ import { FileComparisonPanel } from '../../git/components/FileComparisonPanel';
17
+ import {
18
+ OPEN_COMPARISON_EVENT,
19
+ type OpenComparisonDetail,
20
+ } from '../../../core/events';
21
+ import {
22
+ useAppRegistry,
23
+ useSuggestedPromptSeed,
24
+ } from '../../../core/registry';
25
+ import { useFileLock } from '../../workflow/hooks/useFileLock';
26
+ import { LockApiError } from '../../workflow/services/lock.api';
27
+ import { useAuth } from '../../auth/state/auth.context';
28
+ import {
29
+ knowledgeSuggestionBranchFor,
30
+ proposeKnowledgeChange,
31
+ } from '../../change-requests/services/propose.api';
32
+ import {
33
+ listMyChangeRequests,
34
+ readFileOnBranch,
35
+ } from '../../change-requests/services/change-requests.api';
36
+ import { FileChangeBoxes } from '../../change-requests/components/FileChangeBoxes';
37
+ import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequestDialog';
38
+ import { formatEligible } from '../../access/hooks/useFileAccess';
39
+ import { PR_STALE_EVENT } from '../../../core/events';
40
+ import { getFileRenderer, getRendererLayout } from './renderers';
41
+ import type { RendererSaveState } from './renderers';
42
+ import { KbDocumentShell } from './KbDocumentShell';
43
+ import { FilePaneCard } from './FilePaneCard';
44
+
45
+ const SUGGESTED_PROMPTS = [
46
+ 'Give me an overview of the process landscape.',
47
+ 'What are the main process modules?',
48
+ 'Show me the Registration & Onboarding processes.',
49
+ ];
50
+
51
+ export function FileViewer() {
52
+ const {
53
+ workspaceId,
54
+ kbDirName,
55
+ openFilePath,
56
+ openFileContent,
57
+ openFileSavedContent,
58
+ setHasUnsavedFileChanges,
59
+ setActiveTabContent,
60
+ pendingFileContent,
61
+ saveFile,
62
+ fsRevision,
63
+ acceptPendingContent,
64
+ rejectPendingContent,
65
+ addTab,
66
+ reloadTabFromDisk,
67
+ } = useWorkspace();
68
+ // Chat decoupling: the suggested-prompt seed is an optional registry port
69
+ // (null when no chat surface is registered → the prompt buttons hide).
70
+ const seedSuggestedPrompt = useSuggestedPromptSeed();
71
+ const { fileViewerPanels, renderers } = useAppRegistry();
72
+ const git = useGit();
73
+ // Hiding the tree buys margin, not line length (proto:709), and the pane
74
+ // controller is the only thing that knows whether it is hidden.
75
+ //
76
+ // Read straight off the context rather than through `useLayout`, which
77
+ // THROWS when there is no provider. A gutter is cosmetic; it must not be
78
+ // able to take the whole viewer down. There are two live cases with no
79
+ // controller — a registry app mounted outside the pane layout, and every
80
+ // unit test that renders FileViewer on its own — and in both the honest
81
+ // answer is "the tree is not hidden".
82
+ const layout = useContext(LayoutContext);
83
+ const explorerHidden = layout?.isExplorerCollapsed ?? false;
84
+
85
+ // File-lock integration (PLAN §2). One useFileLock per (branch, file)
86
+ // the user has open. Acquired on first dirty edit, released when the
87
+ // editor unmounts or switches files. The hook handles heartbeat and
88
+ // autosave checkpoints internally.
89
+ const currentBranch = git.status?.branch ?? null;
90
+ // `openFileContentRef` pins the latest in-memory buffer so the lock
91
+ // hook's autosave timer can read it without re-subscribing on every
92
+ // keystroke.
93
+ const openFileContentRef = useRef<string | null>(openFileContent);
94
+ useEffect(() => { openFileContentRef.current = openFileContent; }, [openFileContent]);
95
+ // Stable read of the active path for async handlers that need to check
96
+ // whether the user switched files mid-await.
97
+ const openFilePathRef = useRef<string | null>(openFilePath);
98
+ useEffect(() => { openFilePathRef.current = openFilePath; }, [openFilePath]);
99
+ const persistToDisk = useCallback(async (content: string) => {
100
+ if (!openFilePath) return;
101
+ await saveFile(openFilePath, content);
102
+ }, [openFilePath, saveFile]);
103
+ const auth = useAuth();
104
+ const fileLock = useFileLock({
105
+ workspaceId,
106
+ branch: currentBranch,
107
+ path: openFilePath,
108
+ // Lets the hook filter out "lock held by me" responses during the
109
+ // window where a previous tab's release is still in flight, so
110
+ // switching away and back doesn't flicker a self-locked banner.
111
+ currentUserId: auth.user?.id ?? null,
112
+ readPendingContent: () => openFileContentRef.current,
113
+ persistToDisk,
114
+ });
115
+ // Editability is governed by roles.yaml + access.md, but only on
116
+ // protected branches — drafts are free-for-all and the hook returns
117
+ // canWrite=true for them without a network call. The hook returns
118
+ // `canWrite: null` while the lookup is in flight; we treat that as
119
+ // "allow editing optimistically" so the editor doesn't flicker between
120
+ // disabled / enabled. On a hard `canWrite === false`, the editor goes
121
+ // read-only and a banner explains who can change the file.
122
+ const access = useFileAccess(openFilePath, currentBranch);
123
+ const accessRestricted = access.canWrite === false;
124
+ // Keep the existing variable name so the rest of the file (legacy uses for
125
+ // dirty-flag bookkeeping etc.) doesn't need to change.
126
+ const onProtectedBranch = accessRestricted;
127
+ // Registered auxiliary surfaces (e.g. the enterprise agent-review badge +
128
+ // panel). Rendered on every return path exactly where the hard-mounted
129
+ // review surface used to sit, inside this component's relative container so
130
+ // absolutely-positioned panels anchor the same way.
131
+ const registeredPanels = fileViewerPanels.map(({ id, Component }) => (
132
+ <Component key={id} />
133
+ ));
134
+ // Registry renderer overrides win over the built-in extension map — the
135
+ // enterprise registry swaps in its own `.html` renderer (vendored d3/mermaid
136
+ // + KB graph client) this way.
137
+ const Renderer = useMemo(() => {
138
+ if (!openFilePath) return null;
139
+ const ext = openFilePath.slice(openFilePath.lastIndexOf('.')).toLowerCase();
140
+ const override = renderers.find((r) => r.extensions.includes(ext));
141
+ return override?.Component ?? getFileRenderer(openFilePath);
142
+ }, [openFilePath, renderers]);
143
+
144
+ const [isSubmitting, setIsSubmitting] = useState(false);
145
+ const [activeTab, setActiveTab] = useState<'content' | 'history' | 'compare'>('content');
146
+ const [isManualDirty, setIsManualDirty] = useState(false);
147
+ const [manualSaveState, setManualSaveState] = useState<RendererSaveState>('idle');
148
+ // Last save-and-release failure, surfaced inline so a 422-with-validator
149
+ // payload doesn't disappear into the console with the user assuming
150
+ // their work landed. `kind: 'validation'` carries the structured KB
151
+ // issue list; `kind: 'generic'` is the catch-all for everything else.
152
+ const [saveError, setSaveError] = useState<
153
+ | null
154
+ | { kind: 'validation'; message: string; mustFix: Array<{ path?: string; message: string }> }
155
+ | { kind: 'generic'; message: string }
156
+ >(null);
157
+ const [pendingDeferred, setPendingDeferred] = useState(false);
158
+ const [hadPending, setHadPending] = useState(false);
159
+
160
+ // **Propose mode** — the write path for a reader WITHOUT write permission.
161
+ // Where Edit acquires the file lock and commits to this branch, Propose
162
+ // takes no lock and never touches this branch: the text goes to the
163
+ // caller's personal suggestions branch and surfaces as a change request
164
+ // for the file's owners to approve. No lock because the lock protects the
165
+ // file's canonical bytes, and a proposal does not change them.
166
+ const [proposeMode, setProposeMode] = useState(false);
167
+ const [proposalBusy, setProposalBusy] = useState(false);
168
+ // The one confirmation the author gets that the proposal is now someone
169
+ // else's to act on. Knowledge has no toast provider (see KbPageHeader),
170
+ // so this is a banner, dismissed on the next file/mode change.
171
+ const [proposalSent, setProposalSent] = useState(false);
172
+ // "Loading…" between the Propose click and the editor opening: entering
173
+ // checks for an existing open proposal and, if there is one, reads the
174
+ // file's PROPOSED version off the suggestions branch first.
175
+ const [isEnteringPropose, setIsEnteringPropose] = useState(false);
176
+ /**
177
+ * The editor's base when the caller already has an open proposal: the file
178
+ * as it reads on THEIR suggestions branch. Seeding from it is what makes a
179
+ * second proposal INCREMENTAL — it stacks on the pending change instead of
180
+ * silently starting over from this branch's text and overwriting it. Null
181
+ * = no open proposal (or the read failed): seed from the tab as before.
182
+ */
183
+ const [proposeSeed, setProposeSeed] = useState<string | null>(null);
184
+ /**
185
+ * What Send actually sends. The tab's content ref lags the editor by one
186
+ * state propagation and — when a seed is in play — starts out pointing at
187
+ * THIS branch's text, not the proposed text on screen. This ref is set to
188
+ * the seed on entry and to every keystroke after, so the zero-edits case
189
+ * sends what the editor showed, never what it replaced.
190
+ */
191
+ const proposeBufferRef = useRef<string | null>(null);
192
+ // Picker overrides set by the chat tool-card's "View full comparison" link.
193
+ // Cleared when the user opens a different file so a deep-link doesn't stick
194
+ // around and override their natural defaults on the next open.
195
+ const [comparisonOverride, setComparisonOverride] = useState<{
196
+ fromBranch: string;
197
+ toBranch: string;
198
+ } | null>(null);
199
+ const historyAvailable = git.availability === 'ready';
200
+ const hasUnsavedWork = isManualDirty || manualSaveState === 'saving';
201
+
202
+ const hasPending = pendingFileContent !== null;
203
+ const pendingJustArrived = hasPending && !hadPending;
204
+ const shouldDeferPending = pendingDeferred || (pendingJustArrived && isManualDirty);
205
+ const isReviewingPending = hasPending && !shouldDeferPending;
206
+ const waitingOnAgentUpdate = hasPending && shouldDeferPending;
207
+
208
+ // Reset to the content tab whenever the user opens a different file. Leaving
209
+ // the tab sticky means someone who was viewing history on file A lands on the
210
+ // history tab of file B, which is surprising — opening a file should default
211
+ // to showing what's in it.
212
+ useEffect(() => {
213
+ // Intentional reset-on-key-change (same pattern as useWorkspaceState):
214
+ // opening a different file must start from the content tab.
215
+ // eslint-disable-next-line react-hooks/set-state-in-effect
216
+ setActiveTab('content');
217
+ setIsManualDirty(false);
218
+ setManualSaveState('idle');
219
+ setSaveError(null);
220
+ setPendingDeferred(false);
221
+ setHadPending(false);
222
+ setComparisonOverride(null);
223
+ }, [openFilePath]);
224
+
225
+ // Listen for the agent's chat tool-card "View full comparison" link. The
226
+ // event carries the file path + both refs; we open the file (if needed),
227
+ // jump to the Compare tab, and seed the pickers with the requested pair.
228
+ useEffect(() => {
229
+ const handler = (event: Event) => {
230
+ const detail = (event as CustomEvent<OpenComparisonDetail>).detail;
231
+ if (!detail || !detail.path || !detail.fromBranch || !detail.toBranch) return;
232
+ setComparisonOverride({
233
+ fromBranch: detail.fromBranch,
234
+ toBranch: detail.toBranch,
235
+ });
236
+ setActiveTab('compare');
237
+ if (detail.path !== openFilePath) {
238
+ addTab(detail.path).catch((err) => {
239
+ console.error('Failed to open compared file:', detail.path, err);
240
+ const filename = detail.path.split('/').pop() ?? detail.path;
241
+ const msg = err instanceof Error ? err.message : 'Unknown error';
242
+ window.alert(`Failed to open file: ${filename}\n${msg}`);
243
+ });
244
+ }
245
+ };
246
+ window.addEventListener(OPEN_COMPARISON_EVENT, handler);
247
+ return () => window.removeEventListener(OPEN_COMPARISON_EVENT, handler);
248
+ }, [addTab, openFilePath]);
249
+
250
+ useEffect(() => {
251
+ setHasUnsavedFileChanges?.(hasUnsavedWork);
252
+ }, [hasUnsavedWork, setHasUnsavedFileChanges]);
253
+
254
+ useEffect(() => {
255
+ return () => {
256
+ setHasUnsavedFileChanges?.(false);
257
+ };
258
+ }, [setHasUnsavedFileChanges]);
259
+
260
+ useEffect(() => {
261
+ if (!hasUnsavedWork) return;
262
+ const handler = (event: BeforeUnloadEvent) => {
263
+ event.preventDefault();
264
+ event.returnValue = '';
265
+ };
266
+ window.addEventListener('beforeunload', handler);
267
+ return () => window.removeEventListener('beforeunload', handler);
268
+ }, [hasUnsavedWork]);
269
+
270
+ // If the agent writes while the user has unsaved edits, keep the manual buffer
271
+ // intact and defer the pending preview until the user explicitly reviews it.
272
+ useEffect(() => {
273
+ const hasPendingNow = pendingFileContent !== null;
274
+
275
+ if (!hasPendingNow) {
276
+ // eslint-disable-next-line react-hooks/set-state-in-effect
277
+ setPendingDeferred(false);
278
+ setHadPending(false);
279
+ } else if (!hadPending) {
280
+ setPendingDeferred(isManualDirty);
281
+ setHadPending(true);
282
+ }
283
+ }, [pendingFileContent, isManualDirty, hadPending]);
284
+
285
+ // Pending review / protected branches are read-only surfaces — ensure the file-
286
+ // level dirty indicator does not stay latched from a prior editable state.
287
+ // Propose mode is the exception: it IS the editable surface for a reader
288
+ // without write access, and its dirty flag is real.
289
+ useEffect(() => {
290
+ if ((onProtectedBranch && !proposeMode) || isReviewingPending) {
291
+ // eslint-disable-next-line react-hooks/set-state-in-effect
292
+ setIsManualDirty(false);
293
+ }
294
+ }, [onProtectedBranch, isReviewingPending, proposeMode]);
295
+
296
+ const handleAccept = useCallback(async () => {
297
+ if (isSubmitting) return;
298
+ setIsSubmitting(true);
299
+ try {
300
+ await acceptPendingContent();
301
+ setPendingDeferred(false);
302
+ } finally {
303
+ setIsSubmitting(false);
304
+ }
305
+ }, [isSubmitting, acceptPendingContent]);
306
+
307
+ const handleReject = useCallback(async () => {
308
+ if (isSubmitting) return;
309
+ setIsSubmitting(true);
310
+ try {
311
+ await rejectPendingContent();
312
+ setPendingDeferred(false);
313
+ } catch (err) {
314
+ // Reject WRITES — the baseline back over the agent's bytes — and a
315
+ // failed write must not read as "rejected". Same banner the save path
316
+ // uses. (Accept performs no write, so it has no failure to surface.)
317
+ setSaveError({
318
+ kind: 'generic',
319
+ message: `Couldn't reject the update: ${err instanceof Error ? err.message : String(err)}`,
320
+ });
321
+ } finally {
322
+ setIsSubmitting(false);
323
+ }
324
+ }, [isSubmitting, rejectPendingContent]);
325
+
326
+ // **Edit mode is explicit** (the lock spec, simplified). Viewing a file
327
+ // never claims the lock — the user clicks "Edit" to enter edit mode,
328
+ // which acquires. Idle for `IDLE_RELEASE_MS` (two minutes)?
329
+ // `useFileLock` auto-releases and
330
+ // `holdingLock` flips false; the effect below mirrors that into
331
+ // `editMode` so the UI flips back to view. To resume editing, the
332
+ // user clicks Edit again (which tries to acquire — may fail if
333
+ // someone else grabbed it in the gap, in which case the banner says
334
+ // who holds it).
335
+ const [editMode, setEditMode] = useState(false);
336
+ // True between the Edit click and the moment we've finished
337
+ // acquiring + reloading. Renders the button as "Loading…" and
338
+ // disables it so a double-click can't fire two acquires.
339
+ const [isEnteringEdit, setIsEnteringEdit] = useState(false);
340
+
341
+ // Mirror the lock state into edit mode, but only on a transition from
342
+ // "we held the lock" to "we don't" — that's the idle-release /
343
+ // heartbeat-failure case where we want the UI to flip back to View
344
+ // automatically. We can't just check `!holdingLock && editMode` every
345
+ // render: when the user first clicks Edit, `editMode` flips true
346
+ // before `holdingLock` does (acquire is async), and a naive check
347
+ // would immediately revert editMode to false, defeating the whole
348
+ // mode transition. The previous-value ref kills that race.
349
+ //
350
+ // Done-then-Edit race guard: `handleExitEditMode` is optimistic and
351
+ // fires `saveAndRelease` in the background. If the user clicks Edit
352
+ // before that release completes, we'd see `holdingLock` transition
353
+ // true→false (from Done's background release) AFTER `editMode` has
354
+ // already been re-set to true by the Edit click — and the naive
355
+ // mirror would revert editMode back to false. To avoid that, Done
356
+ // stamps `lastDoneAtRef`; the mirror ignores transitions that fall
357
+ // within a short window after Done (longer than a typical
358
+ // commit+push round-trip on a normal network — Done's release
359
+ // running >`DONE_RELEASE_WINDOW_MS` would be exceptional, and the
360
+ // worst-case outcome is one extra Edit click to recover).
361
+ const wasHoldingLockRef = useRef(false);
362
+ const lastDoneAtRef = useRef(0);
363
+ const DONE_RELEASE_WINDOW_MS = 5_000;
364
+ useEffect(() => {
365
+ const lostLock = wasHoldingLockRef.current && !fileLock.holdingLock;
366
+ if (lostLock && editMode) {
367
+ const withinDoneWindow = Date.now() - lastDoneAtRef.current < DONE_RELEASE_WINDOW_MS;
368
+ if (!withinDoneWindow) {
369
+ setEditMode(false);
370
+ }
371
+ }
372
+ wasHoldingLockRef.current = fileLock.holdingLock;
373
+ }, [fileLock.holdingLock, editMode]);
374
+
375
+ // Reset edit mode when switching files — opening a new tab starts in
376
+ // View mode regardless of which mode the previous tab was in. The
377
+ // `isEnteringEdit` flag is cleared too so a switch-during-load
378
+ // doesn't leave the new tab's button stuck in "Loading…".
379
+ useEffect(() => {
380
+ // Intentional reset-on-key-change: a new file starts in View mode.
381
+ // eslint-disable-next-line react-hooks/set-state-in-effect
382
+ setEditMode(false);
383
+ setIsEnteringEdit(false);
384
+ setProposeMode(false);
385
+ setProposalSent(false);
386
+ setIsEnteringPropose(false);
387
+ setProposeSeed(null);
388
+ proposeBufferRef.current = null;
389
+ }, [openFilePath, currentBranch, workspaceId]);
390
+
391
+ // Monotonic token to scope each enter-edit flow's async completion to
392
+ // the request that started it. When the user switches files mid-flow,
393
+ // the `useEffect` reset on `openFilePath` clears `isEnteringEdit` and
394
+ // bumps the token (via `setIsEnteringEdit(false)` then a new click
395
+ // bumps); without comparing the captured token against the current
396
+ // one, an old request's `.finally(() => setIsEnteringEdit(false))`
397
+ // would clobber the new request's "Loading…" state on the new file.
398
+ const enterEditRequestRef = useRef(0);
399
+ const handleEnterEditMode = useCallback(() => {
400
+ if (editMode || isEnteringEdit || !openFilePath || onProtectedBranch || isReviewingPending) return;
401
+ // **Non-optimistic on entry.** We acquire the lock + reload disk
402
+ // bytes FIRST, then flip into edit mode. The optimistic path —
403
+ // setEditMode(true) sync, acquire + reload in the background —
404
+ // is unsafe: any keystrokes typed in the window between the click
405
+ // and the reload landing would be silently clobbered when fresh
406
+ // disk bytes replace the buffer. The button shows a brief
407
+ // "Loading…" state instead. (Exit-edit / Save stays optimistic;
408
+ // see `handleExitEditMode` — that path is correctness-safe.)
409
+ const targetPath = openFilePath;
410
+ const requestId = ++enterEditRequestRef.current;
411
+ const isStillCurrent = () =>
412
+ requestId === enterEditRequestRef.current && openFilePathRef.current === targetPath;
413
+ setIsEnteringEdit(true);
414
+ fileLock.acquire()
415
+ .then(async ({ acquired, contended, error }) => {
416
+ if (!acquired) {
417
+ // Two failure shapes:
418
+ // - Contention (`contended`): held by someone else → the "Locked
419
+ // by X" banner (below) already explains it; don't double-report.
420
+ // - Access-denied 403 / network (`error`, not contended): surface
421
+ // it. `useFileAccess` default-allows on a transient lookup
422
+ // failure, so the editor lets the user click Edit even when the
423
+ // authoritative backend gate refuses the lock. Without this the
424
+ // click just flickers "Loading…" and nothing happens — the
425
+ // write-denial equivalent of the file silently vanishing. We
426
+ // read `error` off the resolved outcome, not `fileLock.lockError`
427
+ // — the latter is React state and is stale in this closure.
428
+ if (!isStillCurrent()) return;
429
+ if (!contended && error) {
430
+ setSaveError({ kind: 'generic', message: error });
431
+ }
432
+ return;
433
+ }
434
+ if (!isStillCurrent()) return;
435
+ // Take-ownership reload: now that we hold the lock, refetch the
436
+ // canonical bytes so we're editing on top of the latest
437
+ // committed state even if a teammate's save echo hasn't
438
+ // reached this client yet (slow SSE, dropped event, etc.).
439
+ try {
440
+ await reloadTabFromDisk(targetPath);
441
+ } catch (err) {
442
+ console.warn('[FileViewer] reload after acquire failed:', err);
443
+ // Don't flip into edit mode if reload failed — editing on
444
+ // top of state we couldn't verify risks the same stale-
445
+ // overwrite the reload was meant to prevent. Also drop the
446
+ // lock so the file isn't perpetually held while the user
447
+ // sees no edit mode (best-effort; release failures fall to
448
+ // the idle-release timer / unmount cleanup).
449
+ fileLock.saveAndRelease().catch((relErr) => {
450
+ console.warn('[FileViewer] release after reload failure failed:', relErr);
451
+ });
452
+ return;
453
+ }
454
+ // Stale-request check — file may have switched while we were
455
+ // reloading. Don't flip editMode for the wrong file.
456
+ if (!isStillCurrent()) return;
457
+ setEditMode(true);
458
+ })
459
+ .catch((err) => {
460
+ console.warn('[FileViewer] acquire on enter-edit failed:', err);
461
+ })
462
+ .finally(() => {
463
+ // Only clear the loading flag if THIS request is still the
464
+ // active one. A newer click already overwrote enterEditRequestRef
465
+ // and its own `setIsEnteringEdit(true)` shouldn't get clobbered
466
+ // back to false by an older request's finally.
467
+ if (requestId === enterEditRequestRef.current) {
468
+ setIsEnteringEdit(false);
469
+ }
470
+ });
471
+ }, [editMode, isEnteringEdit, openFilePath, onProtectedBranch, isReviewingPending, fileLock, reloadTabFromDisk]);
472
+
473
+ const handleExitEditMode = useCallback(() => {
474
+ if (!editMode) return;
475
+ // Flip to View mode SYNCHRONOUSLY. The actual save+commit+push that
476
+ // `saveAndRelease` runs takes a full git-push round-trip (~1–3 s)
477
+ // and we don't want the user staring at a frozen "Done" button
478
+ // waiting for the network — they explicitly asked to leave edit
479
+ // mode, the UI should respect that immediately.
480
+ //
481
+ // The save then continues in the background. The renderer is
482
+ // already showing the post-edit content (it was the current
483
+ // `value` when Done fired), so the user sees their work in View
484
+ // mode while the bytes are persisted + committed + pushed behind
485
+ // the scenes. The lock-released SSE event eventually clears the
486
+ // server-side state for other clients.
487
+ //
488
+ // `lastDoneAtRef` is the race-guard for the case where the user
489
+ // clicks Edit again BEFORE the background release completes — see
490
+ // the mirror effect above. The Done timestamp lets that effect
491
+ // distinguish "Done's release tail" (don't revert editMode the
492
+ // user just re-set to true) from a genuine unexpected lock loss
493
+ // (revert as usual).
494
+ lastDoneAtRef.current = Date.now();
495
+ setEditMode(false);
496
+ setSaveError(null);
497
+ fileLock.saveAndRelease().catch((err) => {
498
+ // Push-needs-agent-resolution is GONE from the user-visible path.
499
+ // Under the pending-commits queue, release just drops the lock
500
+ // and enqueues a commit; if the eventual background commit /
501
+ // push fails, the worker spawns a recovery agent silently.
502
+ // Nothing surfaces here.
503
+ console.error('[FileViewer] background save+release after Done failed:', err);
504
+ // Surface non-resolution failures inline. Three shapes we care about:
505
+ // - 422 with a `validation` payload → render the mustFix list
506
+ // so the user can see which KB issues are blocking the commit
507
+ // (per CLAUDE.md the validator gates EVERY commit, even
508
+ // unrelated edits — without this UI the failure looks silent).
509
+ // - other LockApiError → render the server message
510
+ // - anything else → render the JS message
511
+ // Either way we revert to edit mode so the user is back in the
512
+ // editor (and can navigate to the failing path / retry).
513
+ setEditMode(true);
514
+ const validation = (err instanceof LockApiError
515
+ ? (err.body as { validation?: { mustFix?: Array<{ path?: string; message: string }> } } | undefined)?.validation
516
+ : undefined);
517
+ if (validation && Array.isArray(validation.mustFix) && validation.mustFix.length > 0) {
518
+ setSaveError({
519
+ kind: 'validation',
520
+ message: err instanceof Error ? err.message : 'Save was rejected by the validator.',
521
+ mustFix: validation.mustFix,
522
+ });
523
+ } else {
524
+ setSaveError({
525
+ kind: 'generic',
526
+ message: err instanceof Error ? err.message : 'Save failed. Please try again.',
527
+ });
528
+ }
529
+ });
530
+ }, [editMode, fileLock]);
531
+
532
+ /**
533
+ * Enter propose mode. If the caller already has an OPEN proposal, the
534
+ * editor seeds from the file as it reads on their suggestions branch —
535
+ * proposing again is a continuation, and starting from this branch's text
536
+ * would silently overwrite their own pending change. No lock either way:
537
+ * the lock protects the file's canonical bytes, and a proposal never
538
+ * touches them. Any staleness against this branch shows up in the change
539
+ * request's diff, where it is visible.
540
+ */
541
+ const handleEnterPropose = useCallback(() => {
542
+ if (proposeMode || isEnteringPropose || !openFilePath) return;
543
+ setProposalSent(false);
544
+ setSaveError(null);
545
+ const targetPath = openFilePath;
546
+ setIsEnteringPropose(true);
547
+ (async () => {
548
+ let seed: string | null = null;
549
+ const user = auth.user;
550
+ const prefix = kbDirName ? `${kbDirName}/` : null;
551
+ if (user && prefix && targetPath.startsWith(prefix)) {
552
+ let existing = null;
553
+ try {
554
+ const branch = knowledgeSuggestionBranchFor(user);
555
+ const mine = await listMyChangeRequests();
556
+ existing = mine.find((c) => c.state === 'open' && c.branch === branch) ?? null;
557
+ if (existing) {
558
+ seed = await readFileOnBranch(branch, targetPath.slice(prefix.length));
559
+ }
560
+ } catch (err) {
561
+ // TWO failure causes, and only one may degrade. "Is there an open
562
+ // proposal?" failing means we KNOW nothing — seed from this branch,
563
+ // which is better than a propose button that does nothing. But a
564
+ // proposal we KNOW exists and could not read must refuse: opening
565
+ // the editor on this branch's text and sending would silently
566
+ // replace the caller's pending proposal — the exact overwrite the
567
+ // seed exists to prevent.
568
+ if (existing) {
569
+ console.warn('[FileViewer] could not read the open proposal:', err);
570
+ if (openFilePathRef.current === targetPath) {
571
+ setSaveError({
572
+ kind: 'generic',
573
+ message:
574
+ "Couldn't load your open proposal, so the editor stayed closed. Try again in a moment.",
575
+ });
576
+ }
577
+ return;
578
+ }
579
+ console.warn('[FileViewer] could not check for an open proposal:', err);
580
+ seed = null;
581
+ }
582
+ }
583
+ // Switched files while the seed loaded — this propose is moot.
584
+ if (openFilePathRef.current !== targetPath) return;
585
+ setProposeSeed(seed);
586
+ proposeBufferRef.current = seed ?? openFileContentRef.current;
587
+ setProposeMode(true);
588
+ })().finally(() => setIsEnteringPropose(false));
589
+ }, [proposeMode, isEnteringPropose, openFilePath, auth.user, kbDirName]);
590
+
591
+ /** Leave propose mode, throwing the typed text away and re-reading disk. */
592
+ const handleDiscardProposal = useCallback(() => {
593
+ setProposeMode(false);
594
+ setProposeSeed(null);
595
+ proposeBufferRef.current = null;
596
+ if (openFilePath) {
597
+ reloadTabFromDisk(openFilePath).catch((err) => {
598
+ console.warn('[FileViewer] reload after discarding a proposal failed:', err);
599
+ });
600
+ }
601
+ }, [openFilePath, reloadTabFromDisk]);
602
+
603
+ /**
604
+ * Send the proposal: the buffer goes to the caller's personal suggestions
605
+ * branch and an open change request against the default branch is created
606
+ * (or reused — one bundle per person). The file on THIS branch is untouched,
607
+ * so on success the tab re-reads disk: leaving the proposed text on screen
608
+ * would claim the file now says something it does not.
609
+ */
610
+ const handleSendProposal = useCallback(async (contentOverride?: string) => {
611
+ const path = openFilePathRef.current;
612
+ // Ctrl+S hands the renderer's buffer straight in; the Send button has no
613
+ // buffer of its own and falls back to the propose buffer (seed +
614
+ // keystrokes), then to the tab's mirror.
615
+ const content = contentOverride ?? proposeBufferRef.current ?? openFileContentRef.current;
616
+ if (!path || !kbDirName || !auth.user || content === null || proposalBusy) return;
617
+ const prefix = `${kbDirName}/`;
618
+ if (!path.startsWith(prefix)) return;
619
+ // Nothing typed over an existing proposal: the branch already says
620
+ // exactly this. Close the editor rather than pushing an empty commit at
621
+ // the change request.
622
+ if (proposeSeed !== null && content === proposeSeed) {
623
+ setProposeMode(false);
624
+ setProposeSeed(null);
625
+ proposeBufferRef.current = null;
626
+ if (openFilePathRef.current === path) {
627
+ reloadTabFromDisk(path).catch(() => {});
628
+ }
629
+ return;
630
+ }
631
+ setProposalBusy(true);
632
+ setSaveError(null);
633
+ try {
634
+ await proposeKnowledgeChange({
635
+ repoRelativePath: path.slice(prefix.length),
636
+ content,
637
+ userEmail: auth.user.email,
638
+ userId: auth.user.id,
639
+ userName: auth.user.name,
640
+ });
641
+ setProposeMode(false);
642
+ setProposeSeed(null);
643
+ proposeBufferRef.current = null;
644
+ setProposalSent(true);
645
+ // The same signal a share dialog or an agent turn sends: the open
646
+ // change-request list just changed, so the tree dots and the page
647
+ // banner refetch.
648
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
649
+ if (openFilePathRef.current === path) {
650
+ await reloadTabFromDisk(path);
651
+ }
652
+ } catch (err) {
653
+ console.error('[FileViewer] sending a proposal failed:', err);
654
+ setSaveError({
655
+ kind: 'generic',
656
+ message: err instanceof Error ? err.message : "Couldn't send your proposed change.",
657
+ });
658
+ } finally {
659
+ setProposalBusy(false);
660
+ }
661
+ }, [kbDirName, auth.user, proposalBusy, proposeSeed, reloadTabFromDisk]);
662
+
663
+ // Save flow (PLAN §2):
664
+ // - Lock is already held because we're in edit mode (handleEnterEditMode
665
+ // guarantees it). Save = checkpoint commit, lock stays held so
666
+ // subsequent keystrokes don't have to re-acquire.
667
+ // - Final commit + release happens on exit-edit, unmount, file switch,
668
+ // or `IDLE_RELEASE_MS` of inactivity (the hook's idle timer).
669
+ const handleSave = useCallback(async (content: string) => {
670
+ if (!openFilePath) return;
671
+ openFileContentRef.current = content;
672
+ if (!fileLock.holdingLock) {
673
+ // Defensive: this path runs when a save fires without us being in
674
+ // edit mode (rare — renderer is readOnly when !editMode, so
675
+ // normally only the explicit Edit-button + saveCheckpoint flow
676
+ // reaches here). Acquire the lock, commit-and-release as a
677
+ // one-shot, and stay in View mode. We deliberately do NOT call
678
+ // `setEditMode(true)` — the user didn't ask to enter Edit mode,
679
+ // they just hit save, so the UI shouldn't silently promote them.
680
+ // `saveAndRelease` handles the full commit-then-release-then-
681
+ // push cycle in one call.
682
+ const { acquired, error } = await fileLock.acquire();
683
+ if (!acquired) {
684
+ // Read the message off the resolved outcome, not `fileLock.lockError`
685
+ // — that's React state and is stale in this closure right after the
686
+ // await. Covers both the access-denied 403 and lock-contention cases.
687
+ throw new Error(error ?? 'File is locked by another user.');
688
+ }
689
+ try {
690
+ await fileLock.saveAndRelease();
691
+ } catch (error) {
692
+ console.error('Failed transient save:', error);
693
+ throw error;
694
+ }
695
+ return;
696
+ }
697
+ try {
698
+ await fileLock.saveCheckpoint();
699
+ } catch (error) {
700
+ console.error('Failed to save file:', error);
701
+ throw error;
702
+ }
703
+ }, [openFilePath, fileLock]);
704
+
705
+ // Track keystroke + scroll activity so the lock hook's idle timer
706
+ // resets while the user is doing anything with the file. Without
707
+ // this, a long meeting spent reading the file would auto-release.
708
+ const recordActivity = fileLock.recordActivity;
709
+ const handleValueChange = useCallback((value: string) => {
710
+ recordActivity();
711
+ // Keep the propose buffer current too — harmless in edit mode, and in
712
+ // propose mode it is what Send reads (see `proposeBufferRef`).
713
+ proposeBufferRef.current = value;
714
+ setActiveTabContent(value);
715
+ }, [recordActivity, setActiveTabContent]);
716
+
717
+ // Scroll handler attached to the editor container. Any scroll within
718
+ // the file counts as activity — the user is reading, even if not
719
+ // typing. Without this, a long meeting spent reading the file would
720
+ // auto-release the lock just because nothing was typed.
721
+ const editorContainerRef = useRef<HTMLDivElement>(null);
722
+ useEffect(() => {
723
+ const el = editorContainerRef.current;
724
+ if (!el || !editMode) return;
725
+ const onScroll = () => recordActivity();
726
+ // Capture-phase so a scroll on a nested element (the editor
727
+ // textarea, a code-mirror viewport, etc.) reaches us without the
728
+ // child having to bubble. Passive so we don't block the scroll.
729
+ el.addEventListener('scroll', onScroll, { capture: true, passive: true });
730
+ return () => el.removeEventListener('scroll', onScroll, { capture: true } as EventListenerOptions);
731
+ }, [editMode, recordActivity]);
732
+
733
+ // No-op save when previewing pending content — don't let edits go through during review
734
+ const handlePendingSave = useCallback(async () => {}, []);
735
+
736
+ const handleReviewAgentUpdate = useCallback(() => {
737
+ if (!waitingOnAgentUpdate || isManualDirty) return;
738
+ setPendingDeferred(false);
739
+ }, [waitingOnAgentUpdate, isManualDirty]);
740
+
741
+ // Canonical link for the open file: the node's id URL when it's a node, else
742
+ // its path URL (resolved in the background, falls back to the path meanwhile).
743
+ const canonicalFileUrl = useCanonicalFileUrl(openFilePath);
744
+ // Each copy resolves to whether it actually landed. `navigator.clipboard`
745
+ // rejects outright on a non-secure origin, and the header says so on the
746
+ // control that was clicked rather than swallowing it.
747
+ const handleCopyLink = useCallback(async () => {
748
+ try {
749
+ const base = canonicalFileUrl ?? `${window.location.origin}${window.location.pathname}`;
750
+ await navigator.clipboard.writeText(base + window.location.hash);
751
+ return true;
752
+ } catch (err) {
753
+ console.error('Failed to copy link:', err);
754
+ return false;
755
+ }
756
+ }, [canonicalFileUrl]);
757
+
758
+ // "Copy page as Markdown" is the document's own source. It is offered only
759
+ // when there IS markdown to copy — a PDF or an image has none, and copying
760
+ // a blob's bytes as text is nonsense rather than a feature.
761
+ const canCopyPage = !!openFilePath && /\.(md|markdown)$/i.test(openFilePath);
762
+ const handleCopyPage = useCallback(async () => {
763
+ if (openFileContent === null) return false;
764
+ try {
765
+ await navigator.clipboard.writeText(openFileContent);
766
+ return true;
767
+ } catch (err) {
768
+ console.error('Failed to copy page:', err);
769
+ return false;
770
+ }
771
+ }, [openFileContent]);
772
+
773
+ // Manage access on the open file, reached from the page's Share button.
774
+ //
775
+ // This page shares ONE thing: the file you are reading. It used to also
776
+ // offer "Share the whole folder", and that went — from a file's page it was
777
+ // a single click away from handing over everything in the folder, with
778
+ // nothing on screen showing what "everything" was. Sharing a folder now
779
+ // starts where the folder is: its row in the tree, right-click → Manage
780
+ // access, next to the children it governs.
781
+ const [shareTarget, setShareTarget] = useState<FileTreeEntry | null>(null);
782
+ const handleShare = useCallback(() => {
783
+ if (!openFilePath) return;
784
+ setShareTarget({
785
+ name: openFilePath.slice(openFilePath.lastIndexOf('/') + 1),
786
+ relativePath: openFilePath,
787
+ type: 'file',
788
+ });
789
+ }, [openFilePath]);
790
+
791
+ // ALL open requests, not just the ones scoped to you — a colleague's request
792
+ // on a file you can read but not write still belongs on this page.
793
+ const openChangeRequests = useOpenChangeRequests();
794
+ const requestsOnThisFile = openFilePath ? openChangeRequests.forPath(openFilePath) : [];
795
+ // The full-bleed banner's "Review the change" opens the SHARED
796
+ // change-request dialog — the old PR viewer surface is gone.
797
+ const [bannerCr, setBannerCr] = useState<PullRequestSummary | null>(null);
798
+
799
+ if (!openFilePath || openFileContent === null || !Renderer) {
800
+ return (
801
+ <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
802
+ <PullNeededBanner />
803
+ <EditorTabs />
804
+ <div className="flex-1 flex items-center justify-center px-6">
805
+ <div className="max-w-md text-center">
806
+ <h2 className="mb-2 text-head text-ink">
807
+ Open a file, or ask the process assistant a question.
808
+ </h2>
809
+ <p className="mb-6 text-ui text-ink-muted">
810
+ Pick anything from the file tree, or start with a suggestion.
811
+ </p>
812
+ {/* Suggested prompts seed the chat composer — only rendered when a
813
+ chat surface registered the seed port. */}
814
+ {seedSuggestedPrompt && (
815
+ <div className="flex flex-col gap-2">
816
+ {SUGGESTED_PROMPTS.map((prompt) => (
817
+ <Surface
818
+ key={prompt}
819
+ as="button"
820
+ tone="sunken"
821
+ radius="lg"
822
+ elevation="none"
823
+ interactive
824
+ type="button"
825
+ onClick={() => seedSuggestedPrompt(prompt)}
826
+ className="px-3 py-2 text-left text-ui text-ink"
827
+ >
828
+ {prompt}
829
+ </Surface>
830
+ ))}
831
+ </div>
832
+ )}
833
+ </div>
834
+ </div>
835
+ {registeredPanels}
836
+ </div>
837
+ );
838
+ }
839
+
840
+ // Which shape the document column takes. A history / comparison panel is a
841
+ // fixed-height viewport with its own scroller (both roots are
842
+ // `flex-1 flex flex-col min-h-0`), so it gets the full-bleed contract for
843
+ // the same reason a PDF does — an auto-height column would collapse it.
844
+ const shellVariant =
845
+ activeTab === 'content' ? getRendererLayout(openFilePath) : 'full-bleed';
846
+
847
+ // What the pane card's bar names — extension kept, unlike the `<h1>` above,
848
+ // because the bar is the technical label (`SKILL.md`, `How to get
849
+ // started.md`) exactly as the skill page's file bar renders it.
850
+ const fileBaseName = openFilePath.slice(openFilePath.lastIndexOf('/') + 1);
851
+
852
+ // The repo-relative path (kbDirName stripped) — what the change-request
853
+ // machinery speaks. Null for files outside the KB clone, which cannot have
854
+ // change requests.
855
+ const repoRelativePath =
856
+ kbDirName && openFilePath.startsWith(`${kbDirName}/`)
857
+ ? openFilePath.slice(kbDirName.length + 1)
858
+ : null;
859
+ const ownersLabel =
860
+ access.owners.roles.length > 0 || access.owners.users.length > 0
861
+ ? formatEligible(access.owners)
862
+ : 'the owners';
863
+
864
+ const rendererElement = (
865
+ // The renderer is a dynamic per-extension lookup resolved in a useMemo
866
+ // above — not a component created during render.
867
+ // eslint-disable-next-line react-hooks/static-components
868
+ <Renderer
869
+ // **Why we key on `openFileSavedContent` (read-only mode only).**
870
+ // When a teammate's save lands, the workspace state updates the
871
+ // tab's content + savedContent. The renderer's internal
872
+ // `useState(content)` + sync-on-prop-change `useEffect` is
873
+ // supposed to pull the new value into `value`, but in practice
874
+ // (production build, multiple suspended subscribers, etc.) we
875
+ // were seeing the preview stay on the stale buffer until the
876
+ // user manually closed + reopened the tab. Keying the renderer
877
+ // on the bytes themselves forces a fresh mount when those
878
+ // bytes change, which initializes `value` from the latest
879
+ // content prop directly and bypasses any stuck-state edge
880
+ // case. We gate this on `!editMode` so the user's in-flight
881
+ // edits (where `value` diverges from `savedContent`) don't
882
+ // trigger a remount that would discard their typing —
883
+ // savedContent stays stable through an edit until the save
884
+ // commits, then advances once.
885
+ key={editMode || proposeMode ? `${openFilePath}|edit` : `${openFilePath}|${openFileSavedContent?.length ?? 0}|${openFileSavedContent?.slice(0, 64) ?? ''}|${openFileSavedContent?.slice(-64) ?? ''}`}
886
+ // In propose mode with an open proposal, the buffer AND the dirty
887
+ // baseline are the PROPOSED text (the seed) — the editor continues the
888
+ // pending change, and "dirty" means "differs from what I already
889
+ // proposed", not "differs from this branch".
890
+ content={
891
+ isReviewingPending
892
+ ? pendingFileContent!
893
+ : proposeMode && proposeSeed !== null
894
+ ? proposeSeed
895
+ : openFileContent
896
+ }
897
+ savedContent={
898
+ isReviewingPending
899
+ ? pendingFileContent!
900
+ : proposeMode && proposeSeed !== null
901
+ ? proposeSeed
902
+ : (openFileSavedContent ?? openFileContent)
903
+ }
904
+ filePath={openFilePath}
905
+ // In propose mode a save (Ctrl+S) IS sending the proposal — the
906
+ // one thing it must never be is a write to this branch.
907
+ onSave={
908
+ isReviewingPending
909
+ ? handlePendingSave
910
+ : proposeMode
911
+ ? handleSendProposal
912
+ : onProtectedBranch
913
+ ? handlePendingSave
914
+ : handleSave
915
+ }
916
+ onDirtyChange={setIsManualDirty}
917
+ onValueChange={
918
+ isReviewingPending || !(editMode || proposeMode) ? undefined : handleValueChange
919
+ }
920
+ onSaveStateChange={setManualSaveState}
921
+ readOnly={isReviewingPending || !(editMode || proposeMode)}
922
+ />
923
+ );
924
+
925
+ // The pane bar's write action — the labelled button at the frame's top
926
+ // left, same slot the skill page uses. What it says is the access answer:
927
+ // `Edit` when you may write the file, `Propose changes` when you may not
928
+ // (null = lookup in flight = optimistic Edit, exactly the header's old
929
+ // rule). While a mode is OPEN it shows the way out instead. The header's
930
+ // own cluster is suppressed for prose files (`writeActionInPane`).
931
+ const lockedBy = fileLock.externalLock?.holderName ?? null;
932
+ const paneActions = isReviewingPending ? null : proposeMode ? (
933
+ <>
934
+ <Button variant="quiet" size="tiny" onClick={handleDiscardProposal} disabled={proposalBusy}>
935
+ Discard
936
+ </Button>
937
+ <Button
938
+ variant="primary"
939
+ size="tiny"
940
+ onClick={() => void handleSendProposal()}
941
+ disabled={proposalBusy}
942
+ title="Send your proposed change for approval"
943
+ >
944
+ {proposalBusy ? 'Sending…' : 'Send proposal'}
945
+ </Button>
946
+ </>
947
+ ) : editMode ? (
948
+ <Button
949
+ variant="outline"
950
+ size="tiny"
951
+ onClick={handleExitEditMode}
952
+ title="Save changes and return to view mode"
953
+ >
954
+ Done
955
+ </Button>
956
+ ) : accessRestricted ? (
957
+ <Button
958
+ variant="outline"
959
+ size="tiny"
960
+ disabled={isEnteringPropose}
961
+ onClick={handleEnterPropose}
962
+ title={
963
+ isEnteringPropose
964
+ ? 'Checking for an open proposal…'
965
+ : "You can't edit this file directly. Propose a change for its owners to approve"
966
+ }
967
+ >
968
+ {isEnteringPropose ? 'Loading…' : 'Propose changes'}
969
+ </Button>
970
+ ) : (
971
+ <Button
972
+ variant="outline"
973
+ size="tiny"
974
+ disabled={!!lockedBy || isEnteringEdit}
975
+ onClick={handleEnterEditMode}
976
+ title={
977
+ lockedBy
978
+ ? `Locked by ${lockedBy}`
979
+ : isEnteringEdit
980
+ ? 'Acquiring lock and fetching latest content…'
981
+ : 'Click to edit this file'
982
+ }
983
+ >
984
+ {isEnteringEdit ? 'Loading…' : 'Edit'}
985
+ </Button>
986
+ );
987
+
988
+ return (
989
+ <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
990
+ <PullNeededBanner />
991
+ {/* No "you don't have permission to edit" banner, deliberately: for a
992
+ reader the restriction is not news worth a stripe across every page —
993
+ the Propose changes affordance already says what they CAN do, and the
994
+ detailed who-may-edit copy still appears where it answers a question
995
+ (the disabled-save tooltip). */}
996
+ {/* ONE column holds the tabs, the title and the text at the same width,
997
+ so they share an edge and the page reads as a single centred block
998
+ (proto:700-705). `editorContainerRef` goes to `scrollRef` because the
999
+ shell is now the element that scrolls — the capture-phase listener
1000
+ bound to it is the file lock's only activity signal for a reader. */}
1001
+ <KbDocumentShell
1002
+ roomy={explorerHidden}
1003
+ variant={shellVariant}
1004
+ scrollRef={editorContainerRef}
1005
+ >
1006
+ <EditorTabs />
1007
+ {/* The document names itself, and its actions sit beside its name.
1008
+ Everything the deleted 40px strip carried is here — the three chips
1009
+ as Badges, Edit with the same handlers and the same lock semantics,
1010
+ the copy-link that used to be an icon in the corner — plus Share and
1011
+ the overflow the prototype puts on the page. */}
1012
+ <KbPageHeader
1013
+ path={openFilePath}
1014
+ canWrite={access.canWrite}
1015
+ editMode={editMode}
1016
+ entering={isEnteringEdit}
1017
+ proposeMode={proposeMode}
1018
+ proposalBusy={proposalBusy}
1019
+ onPropose={handleEnterPropose}
1020
+ onSendProposal={() => void handleSendProposal()}
1021
+ onDiscardProposal={handleDiscardProposal}
1022
+ writeActionInPane={shellVariant === 'prose'}
1023
+ lockedBy={fileLock.externalLock?.holderName ?? null}
1024
+ historyAvailable={historyAvailable}
1025
+ isDirty={isManualDirty}
1026
+ waitingOnAgentUpdate={waitingOnAgentUpdate}
1027
+ isReviewingPending={isReviewingPending}
1028
+ activeTab={activeTab}
1029
+ onEdit={handleEnterEditMode}
1030
+ onDone={handleExitEditMode}
1031
+ onOpenHistory={() => setActiveTab('history')}
1032
+ onShare={handleShare}
1033
+ onCopyPage={canCopyPage ? handleCopyPage : undefined}
1034
+ onCopyLink={handleCopyLink}
1035
+ />
1036
+
1037
+ {/* Content stopped being a tab: the document IS the page, and history
1038
+ and comparison are two things you can go and look at. Each renders in
1039
+ place of the body with an explicit way back — without it the only
1040
+ route home would be reopening the file. */}
1041
+ {activeTab === 'history' && historyAvailable ? (
1042
+ <>
1043
+ <BackToDocument onBack={() => setActiveTab('content')} label="Version history" />
1044
+ <FileHistoryPanel filePath={openFilePath} />
1045
+ </>
1046
+ ) : activeTab === 'compare' && historyAvailable ? (
1047
+ <>
1048
+ <BackToDocument onBack={() => setActiveTab('content')} label="Compare versions" />
1049
+ <FileComparisonPanel
1050
+ filePath={openFilePath}
1051
+ initialFrom={comparisonOverride?.fromBranch ?? null}
1052
+ initialTo={comparisonOverride?.toBranch ?? null}
1053
+ refreshKey={fsRevision}
1054
+ />
1055
+ </>
1056
+ ) : (
1057
+ <>
1058
+ {/* Somebody has proposed a change to this file. For a DOCUMENT the
1059
+ proposals render as change boxes UNDER the file (below) — the
1060
+ skill page's presentation, because the question they ask is
1061
+ unanswerable without the text. This banner remains only for
1062
+ full-bleed files, which have no below to put a box in. The
1063
+ signal comes from the broad endpoint, not from the dock's
1064
+ you-scoped queue, so a colleague's request on a file you can
1065
+ read but not write still shows. */}
1066
+ {requestsOnThisFile.length > 0 && shellVariant !== 'prose' && (
1067
+ <Banner role="note" tone="wait" className="mb-4 flex-none">
1068
+ <div className="font-semibold">
1069
+ {requestsOnThisFile.length === 1
1070
+ ? 'Open change request'
1071
+ : `${requestsOnThisFile.length} open change requests`}
1072
+ </div>
1073
+ <div className="mt-0.5 text-detail text-ink-muted">
1074
+ {requestsOnThisFile[0].appAuthor?.name ?? requestsOnThisFile[0].author.login}{' '}
1075
+ proposed “{requestsOnThisFile[0].title}”. Nothing here changes until someone
1076
+ with write access applies it.
1077
+ </div>
1078
+ <div className="mt-3">
1079
+ <Button
1080
+ variant="primary"
1081
+ size="sm"
1082
+ onClick={() => setBannerCr(requestsOnThisFile[0])}
1083
+ >
1084
+ Review the change
1085
+ </Button>
1086
+ </div>
1087
+ </Banner>
1088
+ )}
1089
+ {/* Propose mode's one-line contract: where the text goes, and that
1090
+ nothing on this page changes until someone with write access
1091
+ says yes. Shown INSTEAD of the access-restricted banner. */}
1092
+ {proposeMode && (
1093
+ <Banner role="status" tone="wait" aria-live="polite" className="mb-4 flex-none">
1094
+ You're proposing a change. Nothing here changes until someone with write
1095
+ access approves it.
1096
+ </Banner>
1097
+ )}
1098
+ {proposalSent && (
1099
+ <Banner
1100
+ role="status"
1101
+ tone="ok"
1102
+ icon={<Check size={14} />}
1103
+ aria-live="polite"
1104
+ className="mb-4 flex-none"
1105
+ >
1106
+ <div className="flex items-center gap-2">
1107
+ <span className="flex-1">
1108
+ Your proposed change was sent as a change request.
1109
+ </span>
1110
+ <Button variant="quiet" size="sm" title="Dismiss" onClick={() => setProposalSent(false)}>
1111
+ Dismiss
1112
+ </Button>
1113
+ </div>
1114
+ </Banner>
1115
+ )}
1116
+ {waitingOnAgentUpdate && (
1117
+ <Banner
1118
+ role="status"
1119
+ tone="wait"
1120
+ aria-live="polite"
1121
+ aria-atomic="true"
1122
+ className="mb-4 flex-none items-center"
1123
+ >
1124
+ <div className="flex items-center gap-2">
1125
+ <span className="flex-1">
1126
+ Agent update is waiting. Save or undo your unsaved edits before reviewing it.
1127
+ </span>
1128
+ <Button
1129
+ variant="outline"
1130
+ size="sm"
1131
+ onClick={handleReviewAgentUpdate}
1132
+ disabled={isManualDirty}
1133
+ title={isManualDirty ? 'Finish local edits first' : 'Open the agent update preview'}
1134
+ >
1135
+ Review agent update
1136
+ </Button>
1137
+ </div>
1138
+ </Banner>
1139
+ )}
1140
+ {/* Accept / Reject banner for a single previewed agent update. */}
1141
+ {isReviewingPending && (
1142
+ <Banner
1143
+ role="status"
1144
+ tone="neutral"
1145
+ aria-live="polite"
1146
+ aria-atomic="true"
1147
+ className="mb-4 flex-none"
1148
+ >
1149
+ <div className="flex items-center gap-2">
1150
+ <span className="flex-1">
1151
+ Previewing agent's changes: accept to keep, reject to undo
1152
+ </span>
1153
+ <Button
1154
+ variant="quiet"
1155
+ size="sm"
1156
+ leadingIcon={<XCircle size={13} />}
1157
+ onClick={handleReject}
1158
+ disabled={isSubmitting}
1159
+ >
1160
+ Reject
1161
+ </Button>
1162
+ <Button
1163
+ variant="primary"
1164
+ size="sm"
1165
+ leadingIcon={<Check size={13} />}
1166
+ onClick={handleAccept}
1167
+ disabled={isSubmitting}
1168
+ >
1169
+ Accept
1170
+ </Button>
1171
+ </div>
1172
+ </Banner>
1173
+ )}
1174
+
1175
+ {/* Lock-by-someone-else banner — read-only state until the holder releases. */}
1176
+ {fileLock.externalLock && !fileLock.holdingLock && !isReviewingPending && !onProtectedBranch && (
1177
+ <Banner
1178
+ role="status"
1179
+ tone="wait"
1180
+ icon={<Lock size={14} />}
1181
+ aria-live="polite"
1182
+ aria-atomic="true"
1183
+ className="mb-4 flex-none"
1184
+ >
1185
+ Locked by <span className="font-medium">{fileLock.externalLock.holderName}</span>. The editor is read-only until they finish.
1186
+ </Banner>
1187
+ )}
1188
+
1189
+ {/* Save-failure banner. Validator failures carry a structured
1190
+ `mustFix` list which we render so the user can see which KB
1191
+ issues are blocking the commit (the validator gates ALL
1192
+ commits, even unrelated edits — without this UI the failure
1193
+ looks silent and the user keeps clicking Save). */}
1194
+ {saveError && (
1195
+ <Banner
1196
+ role="alert"
1197
+ tone="danger"
1198
+ icon={<AlertTriangle size={14} />}
1199
+ aria-live="assertive"
1200
+ className="mb-4 flex-none"
1201
+ >
1202
+ <div className="flex items-center gap-2">
1203
+ <span className="flex-1 font-medium">{saveError.message}</span>
1204
+ <Button variant="quiet" size="sm" title="Dismiss" onClick={() => setSaveError(null)}>
1205
+ Dismiss
1206
+ </Button>
1207
+ </div>
1208
+ {/* The validator gates EVERY commit, even an unrelated edit, so
1209
+ the structured issue list is the only way the user learns
1210
+ which KB problem is blocking their save. The 20-item cap and
1211
+ its "…and N more" tail stay. */}
1212
+ {saveError.kind === 'validation' && saveError.mustFix.length > 0 && (
1213
+ <ul className="mt-1.5 max-h-32 list-disc space-y-0.5 overflow-y-auto pl-4 text-detail">
1214
+ {saveError.mustFix.slice(0, 20).map((issue, i) => (
1215
+ <li key={i}>
1216
+ {issue.path && <span className="font-mono">{issue.path}</span>}
1217
+ {issue.path && ': '}
1218
+ {issue.message}
1219
+ </li>
1220
+ ))}
1221
+ {saveError.mustFix.length > 20 && (
1222
+ <li className="italic">…and {saveError.mustFix.length - 20} more</li>
1223
+ )}
1224
+ </ul>
1225
+ )}
1226
+ </Banner>
1227
+ )}
1228
+
1229
+ {/* File content — show pending (new) content when reviewing, accepted content otherwise.
1230
+ Lock semantics: the editor is read-only whenever we're not in
1231
+ explicit Edit mode. Edit mode is gated by the lock, so this
1232
+ also covers "someone else holds it" without a separate check.
1233
+ The scroll-activity source for the idle-release timer is the
1234
+ shell above, not this wrapper — see `KbDocumentShell.scrollRef`.
1235
+
1236
+ A PROSE document sits inside `FilePaneCard` — the same edged
1237
+ frame, with the same mono filename bar, that the skill page puts
1238
+ around its files. One file-in-a-box drawing for the whole app;
1239
+ full-bleed renderers (pdf, csv, images…) are viewports, not
1240
+ documents, and keep their unframed definite-height contract. */}
1241
+ <div className={shellVariant === 'full-bleed' ? 'flex min-h-0 flex-1 flex-col' : 'min-w-0'}>
1242
+ {shellVariant === 'prose' ? (
1243
+ <>
1244
+ <FilePaneCard file={fileBaseName} actions={paneActions}>
1245
+ {rendererElement}
1246
+ </FilePaneCard>
1247
+ {/* Every open proposal on this file, under the file it is
1248
+ about — the same boxes, the same dialog, as the skill
1249
+ page. Hidden while the reader IS editing or proposing:
1250
+ the diffs are against text that is changing under them. */}
1251
+ {!editMode && !proposeMode && repoRelativePath && requestsOnThisFile.length > 0 && (
1252
+ <FileChangeBoxes
1253
+ repoRelativePath={repoRelativePath}
1254
+ requests={requestsOnThisFile}
1255
+ canDecide={access.canWrite === true}
1256
+ ownersLabel={ownersLabel}
1257
+ onApplied={() => {
1258
+ reloadTabFromDisk(openFilePath).catch(() => {});
1259
+ }}
1260
+ />
1261
+ )}
1262
+ </>
1263
+ ) : (
1264
+ rendererElement
1265
+ )}
1266
+ </div>
1267
+ </>
1268
+ )}
1269
+ </KbDocumentShell>
1270
+ {registeredPanels}
1271
+ {bannerCr && (
1272
+ <ChangeRequestDialog
1273
+ cr={bannerCr}
1274
+ onClose={() => setBannerCr(null)}
1275
+ // Applying is the only verdict the dialog reaches now.
1276
+ onResolved={() => {
1277
+ setBannerCr(null);
1278
+ window.dispatchEvent(new Event(PR_STALE_EVENT));
1279
+ reloadTabFromDisk(openFilePath).catch(() => {});
1280
+ }}
1281
+ />
1282
+ )}
1283
+ {shareTarget && (
1284
+ <ManageAccessDialog
1285
+ key={shareTarget.relativePath}
1286
+ entry={shareTarget}
1287
+ // Keyed on the path, so retargeting at a parent remounts the sheet
1288
+ // against that folder — the whole thing is this one setter.
1289
+ onManageAncestor={setShareTarget}
1290
+ onClose={() => setShareTarget(null)}
1291
+ />
1292
+ )}
1293
+ </div>
1294
+ );
1295
+ }
1296
+
1297
+ /**
1298
+ * The way back from a panel that took the document's place.
1299
+ *
1300
+ * `Content` is no longer a tab, so there is no tab to click to return. Without
1301
+ * this row the only route home from Version history is reopening the file.
1302
+ */
1303
+ function BackToDocument({ onBack, label }: { onBack(): void; label: string }) {
1304
+ return (
1305
+ <div className="mb-3 flex shrink-0 items-center gap-2">
1306
+ <Button variant="quiet" size="sm" leadingIcon={<ArrowLeft size={13} />} onClick={onBack}>
1307
+ Back to the document
1308
+ </Button>
1309
+ <span className="text-detail text-ink-faint">{label}</span>
1310
+ </div>
1311
+ );
1312
+ }