@bevel-software/platform-core-frontend 0.1.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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/package.json +70 -0
  3. package/src/core/CoreAppShell.tsx +444 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
  5. package/src/core/events.ts +29 -0
  6. package/src/core/registry.ts +336 -0
  7. package/src/css-side-effect-imports.d.ts +7 -0
  8. package/src/html-extensions.ts +12 -0
  9. package/src/index.css +49 -0
  10. package/src/index.ts +23 -0
  11. package/src/lib/api.ts +57 -0
  12. package/src/lib/utils.ts +138 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
  14. package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
  15. package/src/modules/access/api.ts +205 -0
  16. package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
  17. package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
  18. package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
  19. package/src/modules/access/hooks/useFileAccess.ts +151 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
  22. package/src/modules/admin/services/admin.api.ts +92 -0
  23. package/src/modules/admin/services/roles.api.ts +136 -0
  24. package/src/modules/admin/state/admin.context.tsx +223 -0
  25. package/src/modules/auth/components/LoginScreen.tsx +135 -0
  26. package/src/modules/auth/hooks/useAuthState.ts +59 -0
  27. package/src/modules/auth/services/auth.api.ts +24 -0
  28. package/src/modules/auth/services/microsoft-oauth.ts +57 -0
  29. package/src/modules/auth/state/auth.context.ts +18 -0
  30. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
  31. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
  32. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
  33. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
  34. package/src/modules/git/__tests__/git.api.test.ts +113 -0
  35. package/src/modules/git/__tests__/pr.api.test.ts +44 -0
  36. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
  37. package/src/modules/git/components/BranchSwitcher.tsx +527 -0
  38. package/src/modules/git/components/DiffView.tsx +30 -0
  39. package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
  40. package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
  41. package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
  42. package/src/modules/git/components/PullNeededBanner.tsx +204 -0
  43. package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
  44. package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
  45. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
  46. package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
  47. package/src/modules/git/hooks/useGitState.ts +335 -0
  48. package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
  49. package/src/modules/git/services/error-messages.ts +257 -0
  50. package/src/modules/git/services/git.api.ts +163 -0
  51. package/src/modules/git/services/pr-prompts.ts +159 -0
  52. package/src/modules/git/services/pr.api.ts +39 -0
  53. package/src/modules/git/state/auto-update.context.ts +21 -0
  54. package/src/modules/git/state/git.context.ts +82 -0
  55. package/src/modules/layout/components/AppLayout.tsx +40 -0
  56. package/src/modules/layout/components/DemoBanner.tsx +57 -0
  57. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
  58. package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
  59. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
  60. package/src/modules/layout/components/SlideOverlay.tsx +224 -0
  61. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
  62. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
  63. package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
  64. package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
  65. package/src/modules/layout/state/layout.context.ts +46 -0
  66. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
  67. package/src/modules/library/__tests__/diff.test.ts +62 -0
  68. package/src/modules/library/__tests__/loadout.test.tsx +72 -0
  69. package/src/modules/library/__tests__/status.test.ts +117 -0
  70. package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
  71. package/src/modules/library/components/CompareView.tsx +357 -0
  72. package/src/modules/library/components/DetailDialog.tsx +566 -0
  73. package/src/modules/library/components/GearIcon.tsx +12 -0
  74. package/src/modules/library/components/LibraryCard.tsx +132 -0
  75. package/src/modules/library/components/LibraryPage.tsx +254 -0
  76. package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
  77. package/src/modules/library/components/StatusGem.tsx +21 -0
  78. package/src/modules/library/components/SuggestChange.tsx +171 -0
  79. package/src/modules/library/components/particles.ts +50 -0
  80. package/src/modules/library/hooks/useLibraryData.ts +119 -0
  81. package/src/modules/library/hooks/useSkillDetail.ts +74 -0
  82. package/src/modules/library/library.css +320 -0
  83. package/src/modules/library/services/library.api.ts +164 -0
  84. package/src/modules/library/state/loadout.tsx +129 -0
  85. package/src/modules/library/state/toast.tsx +42 -0
  86. package/src/modules/library/utils/diff.ts +102 -0
  87. package/src/modules/library/utils/status.ts +116 -0
  88. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
  89. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
  90. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
  91. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
  92. package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
  93. package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
  94. package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
  96. package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
  97. package/src/modules/pr/components/PrCancelButton.tsx +99 -0
  98. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
  99. package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
  100. package/src/modules/pr/components/PrCommentThread.tsx +168 -0
  101. package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
  102. package/src/modules/pr/components/PrDiffPane.tsx +425 -0
  103. package/src/modules/pr/components/PrFileRow.tsx +164 -0
  104. package/src/modules/pr/components/PrFilesList.tsx +53 -0
  105. package/src/modules/pr/components/PrHeader.tsx +45 -0
  106. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
  107. package/src/modules/pr/components/PrMergeButton.tsx +268 -0
  108. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
  109. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
  110. package/src/modules/pr/components/PrViewer.tsx +364 -0
  111. package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
  112. package/src/modules/pr/services/pr-approvals.api.ts +31 -0
  113. package/src/modules/pr/services/pr-cancel.api.ts +19 -0
  114. package/src/modules/pr/services/pr-comments.api.ts +45 -0
  115. package/src/modules/pr/services/pr-detail.api.ts +17 -0
  116. package/src/modules/pr/services/pr-merge.api.ts +53 -0
  117. package/src/modules/pr/services/pr-open.api.ts +30 -0
  118. package/src/modules/pr/state/pr-viewer.context.ts +34 -0
  119. package/src/modules/pr/utils/bucketize-comments.ts +55 -0
  120. package/src/modules/pr/utils/parsePatch.ts +57 -0
  121. package/src/modules/review/__tests__/review.api.test.ts +121 -0
  122. package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
  123. package/src/modules/review/components/DiffViewer.tsx +78 -0
  124. package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
  125. package/src/modules/review/components/ReviewFileRow.tsx +114 -0
  126. package/src/modules/review/components/ReviewPanel.tsx +260 -0
  127. package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
  128. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
  129. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
  130. package/src/modules/review/hooks/useReviewState.ts +256 -0
  131. package/src/modules/review/services/review.api.ts +72 -0
  132. package/src/modules/review/state/ReviewProvider.tsx +28 -0
  133. package/src/modules/review/state/review.context.ts +29 -0
  134. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
  135. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
  136. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
  137. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
  138. package/src/modules/secrets-vault/services/connect.api.ts +113 -0
  139. package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
  140. package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
  141. package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
  142. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
  144. package/src/modules/toolbar/components/Toolbar.tsx +123 -0
  145. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
  146. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
  147. package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
  148. package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
  149. package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
  150. package/src/modules/workflow/hooks/useFileLock.ts +430 -0
  151. package/src/modules/workflow/services/lock.api.ts +139 -0
  152. package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
  153. package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
  154. package/src/modules/workflow/state/event-bus.context.ts +75 -0
  155. package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
  156. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
  157. package/src/modules/workspace/components/EditorTabs.tsx +384 -0
  158. package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
  159. package/src/modules/workspace/components/FileRoute.tsx +392 -0
  160. package/src/modules/workspace/components/FileViewer.tsx +906 -0
  161. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
  162. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
  163. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
  164. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
  165. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
  166. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
  167. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
  168. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
  169. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
  170. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
  171. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
  172. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
  173. package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
  174. package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
  175. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
  176. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
  177. package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
  178. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
  179. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
  180. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
  181. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
  182. package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
  183. package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
  184. package/src/modules/workspace/components/renderers/index.ts +39 -0
  185. package/src/modules/workspace/components/renderers/types.ts +27 -0
  186. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
  189. package/src/modules/workspace/routing/kb-routes.ts +266 -0
  190. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
  191. package/src/modules/workspace/services/workspace.api.ts +185 -0
  192. package/src/modules/workspace/state/workspace.context.ts +235 -0
  193. package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
  194. package/src/modules/workspace/utils/diff.ts +53 -0
  195. package/src/modules/workspace/utils/fileTree.ts +179 -0
  196. package/src/modules/workspace/utils/frontmatter.ts +80 -0
  197. package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
  198. package/src/modules/workspace/utils/tab-persistence.ts +23 -0
  199. package/src/shared/components/Dialog.tsx +198 -0
  200. package/src/shared/components/PageShell.tsx +51 -0
  201. package/src/shared/components/useModalLayer.ts +35 -0
  202. package/src/shared/markdown/Markdown.tsx +62 -0
  203. package/src/test-setup.ts +59 -0
@@ -0,0 +1,906 @@
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
+ }