@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,1315 @@
1
+ import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
2
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
3
+ import { useEventBus, canonicalizeWorkspaceId } from '../../workflow/state/event-bus.context';
4
+ import type {
5
+ OpenTab,
6
+ PendingEntry,
7
+ UploadError,
8
+ UploadInput,
9
+ WorkspaceContextValue,
10
+ } from '../state/workspace.context';
11
+ import {
12
+ getOrCreateWorkspace,
13
+ listFiles,
14
+ readFile,
15
+ writeFile,
16
+ createDirectory as createDirectoryApi,
17
+ uploadFile,
18
+ flushBatch,
19
+ deleteFile as deleteFileApi,
20
+ moveEntry as moveEntryApi,
21
+ deleteWorkspace as deleteWorkspaceApi,
22
+ unzipFile as unzipFileApi,
23
+ WorkspaceApiError,
24
+ } from '../services/workspace.api';
25
+ import { contentChanged } from '../utils/diff';
26
+ import { isUploadNoise, walkEntries, type DroppedItem } from '../utils/readDroppedEntries';
27
+ import { tabsKey, type PersistedTabState } from '../utils/tab-persistence';
28
+
29
+ const PERSIST_DEBOUNCE_MS = 200;
30
+ // Bounded concurrency cap for upload requests. The server serializes git
31
+ // commits per workspace anyway, but network bytes can pipeline — 4 strikes a
32
+ // balance: responsive without monopolizing the browser's HTTP/1.1 connection
33
+ // budget or stressing the lock service.
34
+ const UPLOAD_CONCURRENCY = 4;
35
+ const UNSAVED_TAB_WARNING = (filename: string) =>
36
+ `You have unsaved changes in ${filename}. Close anyway?`;
37
+ const UNSAVED_TABS_BULK_WARNING = (filenames: string[]) =>
38
+ `You have unsaved changes in:\n - ${filenames.join('\n - ')}\nClose anyway?`;
39
+
40
+ function basename(path: string): string {
41
+ const i = path.lastIndexOf('/');
42
+ return i >= 0 ? path.slice(i + 1) : path;
43
+ }
44
+
45
+ /**
46
+ * Return a copy of the tree with the entry at `targetPath` (and any
47
+ * descendants beneath it) removed. Used by `deleteEntry`'s optimistic
48
+ * removal: the folder vanishes from the explorer immediately while the
49
+ * server churns through N per-file commits + push.
50
+ *
51
+ * Tree paths are globally unique, so the recursion finds at most one
52
+ * match — but always-recurse keeps the helper trivially correct and
53
+ * the trees here are small (hundreds of entries, not millions).
54
+ */
55
+ function pruneTreeAt(
56
+ tree: FileTreeEntry | null,
57
+ targetPath: string,
58
+ ): FileTreeEntry | null {
59
+ if (!tree) return null;
60
+ if (!tree.children) return tree;
61
+ return {
62
+ ...tree,
63
+ children: tree.children
64
+ .filter((c) => c.relativePath !== targetPath)
65
+ .map((c) => pruneTreeAt(c, targetPath) as FileTreeEntry),
66
+ };
67
+ }
68
+
69
+ // Flatten a FileTreeEntry into the set of paths it covers. Used to reconcile
70
+ // the optimistic pending-upload overlay against the freshly-fetched server
71
+ // tree after a folder drop — entries whose paths now exist on the server are
72
+ // dropped from the overlay (the real entry takes over rendering).
73
+ function collectPaths(root: FileTreeEntry): Set<string> {
74
+ const out = new Set<string>();
75
+ const visit = (node: FileTreeEntry) => {
76
+ if (node.relativePath && node.relativePath !== '.') {
77
+ out.add(node.relativePath);
78
+ }
79
+ if (node.children) {
80
+ for (const child of node.children) visit(child);
81
+ }
82
+ };
83
+ visit(root);
84
+ return out;
85
+ }
86
+
87
+ interface UseWorkspaceStateReturn extends WorkspaceContextValue {
88
+ setPersistenceBranch: (branch: string | null) => void;
89
+ deleteWorkspace: () => Promise<void>;
90
+ }
91
+
92
+ export function useWorkspaceState(): UseWorkspaceStateReturn {
93
+ const [workspaceId, setWorkspaceId] = useState<string | null>(null);
94
+ const [kbDirName, setKbDirName] = useState<string | null>(null);
95
+ const [fileTree, setFileTree] = useState<FileTreeEntry | null>(null);
96
+ const [openTabs, setOpenTabs] = useState<OpenTab[]>([]);
97
+ const [activeTabPath, setActiveTabPath] = useState<string | null>(null);
98
+ const [uploadError, setUploadError] = useState<UploadError | null>(null);
99
+ const [isUploading, setIsUploading] = useState(false);
100
+ const [fsRevision, setFsRevision] = useState(0);
101
+ const [persistenceBranch, setPersistenceBranchState] = useState<string | null>(null);
102
+
103
+ const bumpFs = useCallback(() => setFsRevision((n) => n + 1), []);
104
+
105
+ // Monotonic token so a slow `addTab` whose response arrives after a newer add
106
+ // doesn't clobber the newer state.
107
+ const addRequestIdRef = useRef(0);
108
+ // Tracks the (workspaceId, persistenceBranch) key we've successfully hydrated
109
+ // for. Auto-persist effect won't write until hydrate has run for the current
110
+ // key — avoids overwriting localStorage with `[]` before the restore lands.
111
+ const hydratedKeyRef = useRef<string | null>(null);
112
+ // Refs for stale-closure-safe reads inside callbacks.
113
+ const openTabsRef = useRef<OpenTab[]>(openTabs);
114
+ const activeTabPathRef = useRef<string | null>(activeTabPath);
115
+ const fileTreeRef = useRef<FileTreeEntry | null>(fileTree);
116
+ /**
117
+ * Paths the user has optimistically removed but the server is still
118
+ * processing. Mid-delete `file-changed` events (one per per-file commit)
119
+ * trigger `refreshFileTree`, which fetches the partial server state —
120
+ * the folder is still mostly there until the last file lands. Without
121
+ * this reconciliation, the explorer would show the folder vanish, then
122
+ * reappear with N-k files, then drain slowly, then vanish again. We
123
+ * prune any in-flight paths out of every refresh response so the
124
+ * optimistic state stays stable until the delete finishes.
125
+ */
126
+ const pendingDeletePathsRef = useRef<Set<string>>(new Set());
127
+ // persistenceBranch as a ref too, so hydrateTabs reads the latest value
128
+ // even when setPersistenceBranch was called in the same render.
129
+ const persistenceBranchRef = useRef<string | null>(persistenceBranch);
130
+ useEffect(() => { openTabsRef.current = openTabs; }, [openTabs]);
131
+ useEffect(() => { activeTabPathRef.current = activeTabPath; }, [activeTabPath]);
132
+ useEffect(() => { fileTreeRef.current = fileTree; }, [fileTree]);
133
+ useEffect(() => { persistenceBranchRef.current = persistenceBranch; }, [persistenceBranch]);
134
+
135
+ const setPersistenceBranch = useCallback((branch: string | null) => {
136
+ persistenceBranchRef.current = branch;
137
+ setPersistenceBranchState(branch);
138
+ }, []);
139
+
140
+ // Bootstrap workspace, branch-aware (PLAN §3). One effect that depends
141
+ // on `persistenceBranch` handles both the initial mount and every
142
+ // subsequent branch switch — using two effects (default-branch mount +
143
+ // branch-rebootstrap) races on first load when the URL carries a
144
+ // non-default branch: both effects fire in parallel, and whichever
145
+ // resolves last clobbers the other's workspaceId/fileTree, sometimes
146
+ // landing the user on `target-company-state` for a beat before
147
+ // snapping to the URL's branch.
148
+ //
149
+ // The `cancelled` flag drops the previous bootstrap's result when
150
+ // `persistenceBranch` changes mid-flight, so a fast switch never
151
+ // overwrites the newer branch's state with an older response.
152
+ useEffect(() => {
153
+ const branch = persistenceBranch ?? undefined;
154
+ let cancelled = false;
155
+ (async () => {
156
+ try {
157
+ const { workspace, fileTree: tree } = await getOrCreateWorkspace(branch);
158
+ if (cancelled) return;
159
+ setWorkspaceId(workspace.id);
160
+ setKbDirName(workspace.kbDirName);
161
+ setFileTree(tree);
162
+ } catch (err) {
163
+ if (!cancelled) console.error('Failed to bootstrap workspace:', err);
164
+ }
165
+ })();
166
+ return () => { cancelled = true; };
167
+ }, [persistenceBranch]);
168
+
169
+ const refreshFileTree = useCallback(async () => {
170
+ if (!workspaceId) return null;
171
+ try {
172
+ let tree = await listFiles(workspaceId);
173
+ // Reconcile with in-flight optimistic deletes — see the ref's
174
+ // JSDoc for the disappear/reappear/disappear bug this avoids.
175
+ for (const pending of pendingDeletePathsRef.current) {
176
+ const pruned = pruneTreeAt(tree, pending);
177
+ if (pruned) tree = pruned;
178
+ }
179
+ setFileTree(tree);
180
+ return tree;
181
+ } catch (err) {
182
+ console.error('Failed to refresh file tree:', err);
183
+ return null;
184
+ }
185
+ }, [workspaceId]);
186
+
187
+ // ── Tab CRUD ──────────────────────────────────────────────────────────────
188
+
189
+ /**
190
+ * Remove a tab because its file is gone or unreadable — a 404 (file vanished)
191
+ * or a 403 (read access denied/revoked). A tab the user isn't allowed to read
192
+ * AUTO-CLOSES rather than lingering in a no-access state, mirroring the tree,
193
+ * which hides unreadable files entirely.
194
+ */
195
+ const dropTabByPath = useCallback((path: string) => {
196
+ setOpenTabs((prev) => prev.filter((t) => t.path !== path));
197
+ if (activeTabPathRef.current === path) {
198
+ const surviving = openTabsRef.current.filter((t) => t.path !== path);
199
+ setActiveTabPath(surviving[0]?.path ?? null);
200
+ }
201
+ }, []);
202
+
203
+ const activateTab = useCallback((tab: OpenTab) => {
204
+ setActiveTabPath(tab.path);
205
+ // If the tab's content was invalidated (fsRevision bump), refetch in the
206
+ // background so the renderer shows fresh bytes. The renderer's existing
207
+ // null-content guard renders an empty/loading state until content arrives.
208
+ if (tab.content === null && workspaceId) {
209
+ const path = tab.path;
210
+ readFile(workspaceId, path).then((content) => {
211
+ setOpenTabs((prev) => prev.map((t) => (
212
+ t.path === path ? { ...t, content, savedContent: content } : t
213
+ )));
214
+ }).catch((err) => {
215
+ if (
216
+ err instanceof WorkspaceApiError &&
217
+ (err.status === 404 || err.status === 403)
218
+ ) {
219
+ // File vanished (404) or read access was revoked (403) — auto-close.
220
+ dropTabByPath(path);
221
+ } else {
222
+ console.error('Failed to refetch tab content:', err);
223
+ }
224
+ });
225
+ }
226
+ }, [workspaceId, dropTabByPath]);
227
+
228
+ const addTab = useCallback(async (relativePath: string): Promise<boolean> => {
229
+ if (!workspaceId) return false;
230
+ // If a tab for this path already exists, just activate it. NEVER prompts
231
+ // on dirty state — opening more tabs never discards work.
232
+ const existing = openTabsRef.current.find((t) => t.path === relativePath);
233
+ if (existing) {
234
+ activateTab(existing);
235
+ return true;
236
+ }
237
+ const requestId = ++addRequestIdRef.current;
238
+ try {
239
+ const content = await readFile(workspaceId, relativePath);
240
+ const isLatest = requestId === addRequestIdRef.current;
241
+ // Re-check dedup in case of races during the await.
242
+ const stillExisting = openTabsRef.current.find((t) => t.path === relativePath);
243
+ if (stillExisting) {
244
+ // Only steal focus when THIS call is the latest open — preserves the
245
+ // newer open's focus when an older read resolves second.
246
+ if (isLatest) activateTab(stillExisting);
247
+ return true;
248
+ }
249
+ const newTab: OpenTab = {
250
+ path: relativePath,
251
+ content,
252
+ savedContent: content,
253
+ isDirty: false,
254
+ pendingFileContent: null,
255
+ };
256
+ // Race-safe append: a parallel addTab for the same path may have inserted
257
+ // the tab between the dedup check above and this setter.
258
+ setOpenTabs((prev) => (
259
+ prev.some((t) => t.path === relativePath) ? prev : [...prev, newTab]
260
+ ));
261
+ if (isLatest) setActiveTabPath(relativePath);
262
+ return true;
263
+ } catch (err) {
264
+ // Drop stale errors silently — the user already navigated to a newer
265
+ // tab, surfacing the older error would be confusing.
266
+ if (requestId !== addRequestIdRef.current) return false;
267
+ // A 403 (read-restricted deep-link / id-link) throws like any other
268
+ // failure: NO tab is created for a file the user can't read — the route
269
+ // surfaces an access-denied state instead. Mirrors the tree, which hides
270
+ // unreadable files entirely.
271
+ console.error('Failed to read file:', err);
272
+ throw err;
273
+ }
274
+ }, [workspaceId, activateTab]);
275
+
276
+ const closeTab = useCallback(async (
277
+ tab: OpenTab,
278
+ options?: { skipConfirm?: boolean },
279
+ ): Promise<{ closed: boolean; newActivePath: string | null }> => {
280
+ if (tab.isDirty && !options?.skipConfirm) {
281
+ const confirmed = window.confirm(UNSAVED_TAB_WARNING(basename(tab.path)));
282
+ if (!confirmed) return { closed: false, newActivePath: activeTabPathRef.current };
283
+ }
284
+ const tabs = openTabsRef.current;
285
+ const idx = tabs.findIndex((t) => t.path === tab.path);
286
+ if (idx < 0) return { closed: true, newActivePath: activeTabPathRef.current };
287
+ const next = tabs.filter((_, i) => i !== idx);
288
+ setOpenTabs(next);
289
+ let newActivePath = activeTabPathRef.current;
290
+ if (activeTabPathRef.current === tab.path) {
291
+ // Activate left neighbor, or right if none, or null if list is now empty.
292
+ const newActive = next[idx - 1] ?? next[idx] ?? null;
293
+ newActivePath = newActive?.path ?? null;
294
+ setActiveTabPath(newActivePath);
295
+ }
296
+ return { closed: true, newActivePath };
297
+ }, []);
298
+
299
+ const closeAllTabs = useCallback(() => {
300
+ setOpenTabs([]);
301
+ setActiveTabPath(null);
302
+ }, []);
303
+
304
+ const reorderTab = useCallback((tab: OpenTab, toIndex: number) => {
305
+ setOpenTabs((prev) => {
306
+ const fromIdx = prev.findIndex((t) => t.path === tab.path);
307
+ if (fromIdx < 0) return prev;
308
+ const clamped = Math.max(0, Math.min(toIndex, prev.length - 1));
309
+ if (clamped === fromIdx) return prev;
310
+ const next = prev.slice();
311
+ const [moved] = next.splice(fromIdx, 1);
312
+ next.splice(clamped, 0, moved);
313
+ return next;
314
+ });
315
+ }, []);
316
+
317
+ const hydrateTabs = useCallback(async (
318
+ paths: string[],
319
+ activePath: string | null,
320
+ ): Promise<{ surviving: string[]; dropped: string[]; denied: string[] }> => {
321
+ if (!workspaceId) return { surviving: [], dropped: paths.slice(), denied: [] };
322
+ // Deduplicate while preserving order.
323
+ const uniqPaths = paths.filter((p, i) => paths.indexOf(p) === i);
324
+
325
+ if (uniqPaths.length === 0) {
326
+ setOpenTabs([]);
327
+ setActiveTabPath(null);
328
+ hydratedKeyRef.current = persistenceBranchRef.current
329
+ ? `${workspaceId}.${persistenceBranchRef.current}`
330
+ : null;
331
+ return { surviving: [], dropped: [], denied: [] };
332
+ }
333
+
334
+ // Fetch every path in parallel. 404s are silently dropped (file no longer
335
+ // on this branch); 403s are dropped too — a persisted tab the user can no
336
+ // longer read auto-closes rather than erroring the whole hydrate into a
337
+ // retry loop — but reported separately so a denied DEEPLINK can surface an
338
+ // access message instead of "file not found". Other errors throw so the
339
+ // caller can show "file-load-failed".
340
+ const results = await Promise.allSettled(uniqPaths.map((p) => readFile(workspaceId, p)));
341
+ const survivors: OpenTab[] = [];
342
+ const surviving: string[] = [];
343
+ const dropped: string[] = [];
344
+ const denied: string[] = [];
345
+ for (let i = 0; i < uniqPaths.length; i++) {
346
+ const path = uniqPaths[i];
347
+ const res = results[i];
348
+ if (res.status === 'fulfilled') {
349
+ survivors.push({
350
+ path,
351
+ content: res.value,
352
+ savedContent: res.value,
353
+ isDirty: false,
354
+ pendingFileContent: null,
355
+ });
356
+ surviving.push(path);
357
+ } else {
358
+ const err = res.reason;
359
+ if (err instanceof WorkspaceApiError && err.status === 404) {
360
+ dropped.push(path);
361
+ } else if (err instanceof WorkspaceApiError && err.status === 403) {
362
+ denied.push(path);
363
+ } else {
364
+ // Surface the first unexpected failure so the route can show
365
+ // "file-load-failed" rather than misleading "file-missing".
366
+ throw err;
367
+ }
368
+ }
369
+ }
370
+
371
+ setOpenTabs(survivors);
372
+ // Activate `activePath` if it survived; else last surviving path; else null.
373
+ const requested = activePath && survivors.some((t) => t.path === activePath)
374
+ ? activePath
375
+ : (survivors[survivors.length - 1]?.path ?? null);
376
+ setActiveTabPath(requested);
377
+ hydratedKeyRef.current = persistenceBranchRef.current
378
+ ? `${workspaceId}.${persistenceBranchRef.current}`
379
+ : null;
380
+ return { surviving, dropped, denied };
381
+ }, [workspaceId]);
382
+
383
+ // ── Renderer value bridge → active tab.content ────────────────────────────
384
+
385
+ // Renderer fires this on every keystroke. Caching the typed value on the
386
+ // tab is what lets the user switch to another tab and come back without
387
+ // losing in-flight bytes.
388
+ const setActiveTabContent = useCallback((value: string) => {
389
+ const path = activeTabPathRef.current;
390
+ if (!path) return;
391
+ setOpenTabs((prev) => {
392
+ const idx = prev.findIndex((t) => t.path === path);
393
+ if (idx < 0) return prev;
394
+ if (prev[idx].content === value) return prev;
395
+ const next = prev.slice();
396
+ next[idx] = { ...next[idx], content: value };
397
+ return next;
398
+ });
399
+ }, []);
400
+
401
+ // ── Renderer dirty bridge → active tab.isDirty ────────────────────────────
402
+
403
+ const setHasUnsavedFileChanges = useCallback((dirty: boolean) => {
404
+ const path = activeTabPathRef.current;
405
+ if (!path) return;
406
+ setOpenTabs((prev) => {
407
+ const idx = prev.findIndex((t) => t.path === path);
408
+ if (idx < 0) return prev;
409
+ if (prev[idx].isDirty === dirty) return prev;
410
+ const next = prev.slice();
411
+ next[idx] = { ...next[idx], isDirty: dirty };
412
+ return next;
413
+ });
414
+ }, []);
415
+
416
+ // ── Working-tree mutations ────────────────────────────────────────────────
417
+
418
+ const createFile = useCallback(async (relativePath: string, content?: string) => {
419
+ if (!workspaceId) return;
420
+ await writeFile(workspaceId, relativePath, content ?? '');
421
+ await refreshFileTree();
422
+ bumpFs();
423
+ }, [workspaceId, refreshFileTree, bumpFs]);
424
+
425
+ const createDirectory = useCallback(async (relativePath: string) => {
426
+ if (!workspaceId) return;
427
+ await createDirectoryApi(workspaceId, relativePath);
428
+ await refreshFileTree();
429
+ bumpFs();
430
+ }, [workspaceId, refreshFileTree, bumpFs]);
431
+
432
+ const unzipHere = useCallback(async (zipRelativePath: string) => {
433
+ if (!workspaceId) {
434
+ return { extracted: 0, skipped: [], destination: '' };
435
+ }
436
+ const result = await unzipFileApi(workspaceId, zipRelativePath);
437
+ await refreshFileTree();
438
+ bumpFs();
439
+ return {
440
+ extracted: result.extracted.length,
441
+ skipped: result.skipped,
442
+ destination: result.destination,
443
+ };
444
+ }, [workspaceId, refreshFileTree, bumpFs]);
445
+
446
+ const uploadFiles = useCallback(async (files: File[], targetDirectory: string) => {
447
+ if (!workspaceId) return;
448
+ for (const file of files) {
449
+ const relativePath = targetDirectory ? `${targetDirectory}/${file.name}` : file.name;
450
+ try {
451
+ await uploadFile(workspaceId, relativePath, file);
452
+ } catch (err) {
453
+ const message = err instanceof Error ? err.message : 'Upload failed';
454
+ throw Object.assign(new Error(message), { filename: file.name });
455
+ }
456
+ }
457
+ await refreshFileTree();
458
+ bumpFs();
459
+ }, [workspaceId, refreshFileTree, bumpFs]);
460
+
461
+ const clearUploadError = useCallback(() => setUploadError(null), []);
462
+
463
+ // Pending overlay: files/dirs the user dropped but whose server commits
464
+ // haven't echoed back yet. The ref holds the mutable working set the
465
+ // upload pipeline tweaks; the state snapshot is what React renders.
466
+ // `flushPending` copies the ref into a fresh state Map whenever the
467
+ // pipeline wants the renderer to catch up.
468
+ const pendingUploadsRef = useRef<Map<string, PendingEntry>>(new Map());
469
+ const [pendingUploads, setPendingUploads] = useState<Map<string, PendingEntry>>(
470
+ () => new Map(),
471
+ );
472
+ const [uploadProgress, setUploadProgress] = useState<
473
+ { uploaded: number; total: number | null } | null
474
+ >(null);
475
+
476
+ const flushPending = useCallback(() => {
477
+ // Snapshot via a new Map so React sees a stable reference change.
478
+ setPendingUploads(new Map(pendingUploadsRef.current));
479
+ }, []);
480
+
481
+ const addPending = useCallback((entry: PendingEntry) => {
482
+ pendingUploadsRef.current.set(entry.fullPath, entry);
483
+ flushPending();
484
+ }, [flushPending]);
485
+
486
+ const removePending = useCallback((fullPath: string) => {
487
+ if (pendingUploadsRef.current.delete(fullPath)) flushPending();
488
+ }, [flushPending]);
489
+
490
+ const clearPendingMatching = useCallback((predicate: (entry: PendingEntry) => boolean) => {
491
+ let changed = false;
492
+ for (const [key, entry] of pendingUploadsRef.current) {
493
+ if (predicate(entry)) {
494
+ pendingUploadsRef.current.delete(key);
495
+ changed = true;
496
+ }
497
+ }
498
+ if (changed) flushPending();
499
+ }, [flushPending]);
500
+
501
+ const activeUploadsRef = useRef(0);
502
+ const dispatchUpload = useCallback(async (input: UploadInput, targetDirectory: string) => {
503
+ if (!workspaceId) return;
504
+ // Pin the workspace at dispatch time. A folder upload can take seconds;
505
+ // if the user switches branches mid-flight, the trailing state
506
+ // mutations (setUploadError / setIsUploading / setFileTree via
507
+ // refreshFileTree / clearPendingMatching) would clobber the new
508
+ // branch's UI with old-branch results. `isCurrent()` gates every
509
+ // post-await mutation; the workspaceId reset effect above already
510
+ // clears the optimistic refs the moment the switch happens.
511
+ const dispatchWorkspaceId = workspaceId;
512
+ const isCurrent = () => workspaceIdRef.current === dispatchWorkspaceId;
513
+
514
+ setUploadError(null);
515
+ activeUploadsRef.current += 1;
516
+ setIsUploading(true);
517
+
518
+ // Batch mode collapses N per-file pushes into one end-of-burst push
519
+ // via `POST /flush` — mirrors the recursive folder-delete batch.
520
+ // Folder drops / folder-picker / multi-file pickers go through batch;
521
+ // a single-file pick stays on the legacy 1-commit-1-push path so the
522
+ // 1-file UX is exactly as fast as before (no extra `/flush` RTT).
523
+ const isBatch =
524
+ input.kind === 'items'
525
+ || input.kind === 'paths'
526
+ || (input.kind === 'files' && input.files.length > 1);
527
+
528
+ // Track tree shape we discover as we walk so we can preserve empty
529
+ // subdirectories. `discoveredDirs` = every directory the walker yielded;
530
+ // `fileAncestors` = every prefix of every uploaded file's relative path.
531
+ // `emptyDirs = discoveredDirs − fileAncestors` after the walk completes.
532
+ const discoveredDirs = new Set<string>();
533
+ const fileAncestors = new Set<string>();
534
+ const fullPath = (rel: string) =>
535
+ targetDirectory ? `${targetDirectory}/${rel}` : rel;
536
+ const recordFileAncestors = (rel: string) => {
537
+ const parts = rel.split('/');
538
+ for (let i = 1; i < parts.length; i++) {
539
+ fileAncestors.add(parts.slice(0, i).join('/'));
540
+ }
541
+ };
542
+
543
+ let uploaded = 0;
544
+ let total: number | null = null;
545
+ let abort = false;
546
+ let firstError: { filename: string; reason: string } | null = null;
547
+ // Tracks whether any deferred `createDirectory` (empty-dir preservation)
548
+ // commits landed. Without this, a folder drop containing only empty
549
+ // subdirectories would skip `flushBatch` (`uploaded === 0`) and leave
550
+ // the dir-create commits stranded unpushed locally.
551
+ let deferredDirsQueued = false;
552
+
553
+ const setProgress = () => {
554
+ setUploadProgress({ uploaded, total });
555
+ };
556
+
557
+ const recordError = (filename: string, err: unknown) => {
558
+ if (firstError) return;
559
+ const reason = err instanceof Error ? err.message : 'Upload failed';
560
+ firstError = { filename, reason };
561
+ abort = true;
562
+ };
563
+
564
+ // Concurrency-bounded upload pump. Producer pushes UploadItems; workers
565
+ // pull and upload. We don't use a queue + N worker promises because we
566
+ // also want the producer to suspend when the queue is saturated, so we
567
+ // model the cap as a semaphore.
568
+ const inFlight: Promise<void>[] = [];
569
+
570
+ const uploadOne = async (file: File, relativePath: string): Promise<void> => {
571
+ const path = fullPath(relativePath);
572
+ addPending({ fullPath: path, type: 'file' });
573
+ // Pre-register the file's directory ancestors so the dropped
574
+ // structure flashes in immediately, before any commits land.
575
+ for (const ancestor of fileAncestors) {
576
+ const ancestorFull = fullPath(ancestor);
577
+ if (!pendingUploadsRef.current.has(ancestorFull)) {
578
+ addPending({ fullPath: ancestorFull, type: 'directory' });
579
+ }
580
+ }
581
+ try {
582
+ await uploadFile(workspaceId, path, file, { defer: isBatch });
583
+ uploaded += 1;
584
+ setProgress();
585
+ // Don't remove the pending entry here — the server commit has
586
+ // landed but the file tree hasn't been refreshed yet, so removing
587
+ // would briefly hide the file in the explorer. Reconciliation
588
+ // happens after the final refresh in the `finally` block below.
589
+ } catch (err) {
590
+ recordError(path, err);
591
+ // On failure, remove the pending entry so the failed file
592
+ // disappears from the explorer rather than lingering as a ghost.
593
+ removePending(path);
594
+ }
595
+ };
596
+
597
+ const runWithCap = async (file: File, relativePath: string) => {
598
+ while (inFlight.length >= UPLOAD_CONCURRENCY) {
599
+ await Promise.race(inFlight);
600
+ }
601
+ const p = uploadOne(file, relativePath).finally(() => {
602
+ const idx = inFlight.indexOf(p);
603
+ if (idx >= 0) inFlight.splice(idx, 1);
604
+ });
605
+ inFlight.push(p);
606
+ };
607
+
608
+ const consume = async (item: DroppedItem) => {
609
+ // OS-generated noise (`.DS_Store`, `__MACOSX/…`, `._*`) shouldn't be
610
+ // committed to the KB — silently skip, mirroring the unzip route's
611
+ // existing filter. Applied here so all three input modes share the
612
+ // same rule.
613
+ if (isUploadNoise(item.relativePath)) return;
614
+ if (item.kind === 'dir') {
615
+ discoveredDirs.add(item.relativePath);
616
+ const dirFull = fullPath(item.relativePath);
617
+ if (!pendingUploadsRef.current.has(dirFull)) {
618
+ addPending({ fullPath: dirFull, type: 'directory' });
619
+ }
620
+ return;
621
+ }
622
+ if (total === null) total = 1; else total += 1;
623
+ setProgress();
624
+ recordFileAncestors(item.relativePath);
625
+ await runWithCap(item.file, item.relativePath);
626
+ };
627
+
628
+ try {
629
+ if (input.kind === 'files') {
630
+ const files = input.files.filter((f) => !isUploadNoise(f.name));
631
+ total = files.length;
632
+ setProgress();
633
+ for (const file of files) {
634
+ if (abort) break;
635
+ await runWithCap(file, file.name);
636
+ }
637
+ } else if (input.kind === 'paths') {
638
+ const items = input.items.filter((it) => !isUploadNoise(it.relativePath));
639
+ total = items.length;
640
+ setProgress();
641
+ for (const it of items) {
642
+ if (abort) break;
643
+ recordFileAncestors(it.relativePath);
644
+ await runWithCap(it.file, it.relativePath);
645
+ }
646
+ } else {
647
+ // kind === 'items': lazy walk a snapshot of FileSystemEntry. Uploads
648
+ // start on the first yielded file so the UI doesn't wait for full
649
+ // enumeration.
650
+ for await (const item of walkEntries(input.entries)) {
651
+ if (abort) break;
652
+ await consume(item);
653
+ }
654
+ }
655
+ // Drain remaining in-flight uploads.
656
+ while (inFlight.length > 0) {
657
+ await Promise.race(inFlight);
658
+ }
659
+
660
+ // Empty-dir preservation: every directory the walker discovered that
661
+ // didn't end up with a file under it needs an explicit createDirectory
662
+ // call so its `.gitkeep` is committed. Skipped on error so we don't
663
+ // half-commit a broken drop.
664
+ if (!firstError && input.kind === 'items') {
665
+ const emptyDirs: string[] = [];
666
+ for (const dir of discoveredDirs) {
667
+ if (!fileAncestors.has(dir)) emptyDirs.push(dir);
668
+ }
669
+ for (const rel of emptyDirs) {
670
+ const path = fullPath(rel);
671
+ try {
672
+ await createDirectoryApi(workspaceId, path, { defer: isBatch });
673
+ if (isBatch) deferredDirsQueued = true;
674
+ } catch (err) {
675
+ recordError(path, err);
676
+ break;
677
+ }
678
+ }
679
+ }
680
+
681
+ // End-of-batch checkpoint: push every commit accumulated above in
682
+ // a single round-trip to origin and trigger one `fs-tree-changed`
683
+ // server-side. Skipped on error so we don't try to push a half-
684
+ // committed batch — the local commits sit unpushed until the next
685
+ // save on this branch catches up, exactly like the folder-delete
686
+ // batch's failure mode. The `deferredDirsQueued` arm covers the
687
+ // empty-folders-only drop where `uploaded === 0` but we still
688
+ // queued one or more deferred dir-create commits that need pushing.
689
+ if (isBatch && !firstError && (uploaded > 0 || deferredDirsQueued)) {
690
+ try {
691
+ await flushBatch(workspaceId, targetDirectory || '.');
692
+ } catch (err) {
693
+ recordError(targetDirectory || '.', err);
694
+ }
695
+ }
696
+ } catch (err) {
697
+ // Walker-level failure (rare — broken entries are skipped inside the
698
+ // walker). Surface as a generic error.
699
+ recordError('upload', err);
700
+ } finally {
701
+ // Workspace-agnostic bookkeeping always runs so the next dispatch
702
+ // sees a clean count. Everything below it is *workspace-shared* UI
703
+ // state — if the user switched branches mid-flight, applying it
704
+ // would clobber the new branch's view with results from the branch
705
+ // they already left. The workspace-change effect already reset the
706
+ // optimistic overlays.
707
+ activeUploadsRef.current = Math.max(0, activeUploadsRef.current - 1);
708
+ if (isCurrent()) {
709
+ if (firstError) {
710
+ setUploadError(firstError);
711
+ // Drop any pending overlay entries that didn't make it — files
712
+ // we already uploaded successfully are removed inside uploadOne.
713
+ clearPendingMatching(() => true);
714
+ }
715
+
716
+ const stillRunning = activeUploadsRef.current > 0;
717
+ setIsUploading(stillRunning);
718
+ if (!stillRunning) setUploadProgress(null);
719
+
720
+ // One final refresh to reconcile the server tree with whatever
721
+ // committed, then clear pending overlay entries whose real
722
+ // counterparts have arrived. Entries that didn't make it
723
+ // (e.g. refresh raced ahead of a slow commit echo) stay in the
724
+ // overlay until the next SSE-triggered refresh removes them.
725
+ refreshFileTree()
726
+ .then((tree) => {
727
+ if (!isCurrent()) return;
728
+ if (tree) {
729
+ const realPaths = collectPaths(tree);
730
+ clearPendingMatching((entry) => realPaths.has(entry.fullPath));
731
+ }
732
+ bumpFs();
733
+ })
734
+ .catch((err) => {
735
+ console.warn('[workspace] post-upload tree refresh failed:', err);
736
+ });
737
+ }
738
+ }
739
+ }, [
740
+ workspaceId, refreshFileTree, bumpFs,
741
+ addPending, removePending, clearPendingMatching,
742
+ ]);
743
+
744
+ const deleteEntry = useCallback(async (relativePath: string) => {
745
+ if (!workspaceId) return;
746
+ // Pin the workspace at delete time. A recursive folder delete is N
747
+ // per-file commits + one push — multiple seconds. If the user
748
+ // switches branches mid-flight, the post-await mutations below
749
+ // would clobber the new branch's tree / tabs with state from the
750
+ // old branch's delete. `isCurrent()` gates every state mutation
751
+ // after the await; the workspace-change reset effect already
752
+ // clears `pendingDeletePathsRef` on its own.
753
+ const deleteWorkspaceId = workspaceId;
754
+ const isCurrent = () => workspaceIdRef.current === deleteWorkspaceId;
755
+
756
+ // Tab sweep: close every tab whose path matches the deleted path or starts
757
+ // with `deletedPath + '/'` (directory delete). If any swept tab is dirty,
758
+ // confirm once with all affected filenames before proceeding.
759
+ const prefix = relativePath + '/';
760
+ const toClose = openTabsRef.current.filter(
761
+ (t) => t.path === relativePath || t.path.startsWith(prefix),
762
+ );
763
+ const dirty = toClose.filter((t) => t.isDirty);
764
+ if (dirty.length > 0) {
765
+ const confirmed = window.confirm(UNSAVED_TABS_BULK_WARNING(dirty.map((t) => basename(t.path))));
766
+ if (!confirmed) return;
767
+ }
768
+ // Optimistic tree removal. A folder delete on the server takes 2-3s
769
+ // (N per-file commits batched into one push) — without optimism the
770
+ // explorer freezes for that whole time and the user assumes nothing
771
+ // happened. Snapshot first so we can roll back on failure. Mark the
772
+ // path as pending so any mid-delete `refreshFileTree` (triggered by
773
+ // per-file `file-changed` SSE events) also prunes it — otherwise the
774
+ // folder would reappear with a partial child list each refresh.
775
+ const treeSnapshot = fileTreeRef.current;
776
+ pendingDeletePathsRef.current.add(relativePath);
777
+ setFileTree((prev) => pruneTreeAt(prev, relativePath));
778
+ bumpFs();
779
+ try {
780
+ await deleteFileApi(workspaceId, relativePath);
781
+ } catch (err) {
782
+ if (!isCurrent()) throw err;
783
+ pendingDeletePathsRef.current.delete(relativePath);
784
+ // Roll back the optimistic prune, then reconcile with whatever
785
+ // partial state actually landed (a mid-batch failure leaves the
786
+ // early files deleted and the rest intact).
787
+ setFileTree(treeSnapshot);
788
+ bumpFs();
789
+ await refreshFileTree();
790
+ throw err;
791
+ }
792
+ if (!isCurrent()) return;
793
+ pendingDeletePathsRef.current.delete(relativePath);
794
+ // Close tabs only after the server confirmed — keeps tab content +
795
+ // cursor position intact on the rollback path.
796
+ if (toClose.length > 0) {
797
+ const survivingTabs = openTabsRef.current.filter(
798
+ (t) => !(t.path === relativePath || t.path.startsWith(prefix)),
799
+ );
800
+ setOpenTabs(survivingTabs);
801
+ if (activeTabPathRef.current && toClose.some((t) => t.path === activeTabPathRef.current)) {
802
+ setActiveTabPath(survivingTabs[survivingTabs.length - 1]?.path ?? null);
803
+ }
804
+ }
805
+ // No final refreshFileTree() — the optimistic prune already matches
806
+ // server state. The backend's end-of-batch `fs-tree-changed` SSE
807
+ // event triggers a refresh anyway as belt-and-suspenders. No second
808
+ // `bumpFs()` either — the optimistic bump above already counted.
809
+ }, [workspaceId, refreshFileTree, bumpFs]);
810
+
811
+ const reloadTabFromDisk = useCallback(async (relativePath: string) => {
812
+ if (!workspaceId) return;
813
+ const exists = openTabsRef.current.some((t) => t.path === relativePath);
814
+ if (!exists) return;
815
+ // Capture the workspace this reload was issued for. The `await readFile`
816
+ // below yields to the event loop, during which the user may switch
817
+ // branches (workspaceIdRef.current changes). Applying old-branch bytes
818
+ // to a new-branch tab would silently corrupt the buffer.
819
+ const expectedWorkspaceId = workspaceId;
820
+ try {
821
+ const fresh = await readFile(expectedWorkspaceId, relativePath);
822
+ if (workspaceIdRef.current !== expectedWorkspaceId) return;
823
+ setOpenTabs((prev) => prev.map((t) => {
824
+ if (t.path !== relativePath) return t;
825
+ // Don't clobber in-flight local edits or a pending agent preview
826
+ // that landed during the readFile. The caller (e.g. Edit-click)
827
+ // assumes the tab was clean when it asked us to reload — if it
828
+ // isn't anymore, the user's newer state wins.
829
+ if (t.isDirty || t.pendingFileContent !== null) return t;
830
+ // Skip if bytes are already in sync — avoids a useless re-render that
831
+ // would briefly unmount the renderer.
832
+ if (fresh === t.content && fresh === t.savedContent) return t;
833
+ return {
834
+ ...t,
835
+ content: fresh,
836
+ savedContent: fresh,
837
+ isDirty: false,
838
+ pendingFileContent: null,
839
+ };
840
+ }));
841
+ } catch (err) {
842
+ if (workspaceIdRef.current !== expectedWorkspaceId) return;
843
+ if (err instanceof WorkspaceApiError && err.status === 404) {
844
+ // File vanished between Edit click and reload — drop the tab.
845
+ setOpenTabs((prev) => prev.filter((t) => t.path !== relativePath));
846
+ if (activeTabPathRef.current === relativePath) {
847
+ const surviving = openTabsRef.current.filter((t) => t.path !== relativePath);
848
+ setActiveTabPath(surviving[surviving.length - 1]?.path ?? null);
849
+ }
850
+ return;
851
+ }
852
+ console.warn(`[workspace] reloadTabFromDisk failed for "${relativePath}":`, err);
853
+ throw err;
854
+ }
855
+ }, [workspaceId]);
856
+
857
+ const saveFile = useCallback(async (relativePath: string, content: string) => {
858
+ if (!workspaceId) return;
859
+ await writeFile(workspaceId, relativePath, content);
860
+ // Update the matching tab — both the cached current value and the on-disk
861
+ // baseline now equal `content`; clear dirty.
862
+ setOpenTabs((prev) => {
863
+ const idx = prev.findIndex((t) => t.path === relativePath);
864
+ if (idx < 0) return prev;
865
+ const next = prev.slice();
866
+ next[idx] = { ...next[idx], content, savedContent: content, isDirty: false };
867
+ return next;
868
+ });
869
+ bumpFs();
870
+ }, [workspaceId, bumpFs]);
871
+
872
+ const moveEntry = useCallback(async (oldPath: string, newPath: string) => {
873
+ if (!workspaceId) return;
874
+ await moveEntryApi(workspaceId, oldPath, newPath);
875
+ // Rewrite all matching tab paths in place — exact match OR directory prefix.
876
+ const oldPrefix = oldPath + '/';
877
+ setOpenTabs((prev) => prev.map((t) => {
878
+ if (t.path === oldPath) return { ...t, path: newPath };
879
+ if (t.path.startsWith(oldPrefix)) return { ...t, path: newPath + t.path.slice(oldPath.length) };
880
+ return t;
881
+ }));
882
+ if (activeTabPathRef.current === oldPath) {
883
+ setActiveTabPath(newPath);
884
+ } else if (activeTabPathRef.current && activeTabPathRef.current.startsWith(oldPrefix)) {
885
+ setActiveTabPath(newPath + activeTabPathRef.current.slice(oldPath.length));
886
+ }
887
+ await refreshFileTree();
888
+ bumpFs();
889
+ }, [workspaceId, refreshFileTree, bumpFs]);
890
+
891
+ // ── Pending-content (agent edits) — routed to active tab ──────────────────
892
+
893
+ const setPendingContent = useCallback((content: string) => {
894
+ const path = activeTabPathRef.current;
895
+ if (!path) return;
896
+ const active = openTabsRef.current.find((t) => t.path === path);
897
+ if (!active || active.content === null) return;
898
+ if (!contentChanged(active.content, content)) {
899
+ // No diff — clear any stale pending and bail.
900
+ setOpenTabs((prev) => prev.map((t) => (t.path === path ? { ...t, pendingFileContent: null } : t)));
901
+ return;
902
+ }
903
+ setOpenTabs((prev) => prev.map((t) => (t.path === path ? { ...t, pendingFileContent: content } : t)));
904
+ }, []);
905
+
906
+ const acceptPendingContent = useCallback(async () => {
907
+ const path = activeTabPathRef.current;
908
+ if (!path) return;
909
+ const active = openTabsRef.current.find((t) => t.path === path);
910
+ if (!active || active.pendingFileContent === null) return;
911
+ const content = active.pendingFileContent;
912
+ // The agent's bytes were already flushed to disk by its tool call, so
913
+ // accepting means: align both `content` and `savedContent` with that.
914
+ setOpenTabs((prev) => prev.map((t) => (
915
+ t.path === path
916
+ ? { ...t, content, savedContent: content, pendingFileContent: null, isDirty: false }
917
+ : t
918
+ )));
919
+ }, []);
920
+
921
+ const rejectPendingContent = useCallback(async () => {
922
+ if (!workspaceId) return;
923
+ const path = activeTabPathRef.current;
924
+ if (!path) return;
925
+ const active = openTabsRef.current.find((t) => t.path === path);
926
+ // Reject means: roll back to the on-disk baseline before the agent wrote.
927
+ // savedContent holds that baseline; if it's null, fall back to content.
928
+ const baseline = active?.savedContent ?? active?.content ?? null;
929
+ if (!active || baseline === null) return;
930
+ await writeFile(workspaceId, path, baseline);
931
+ setOpenTabs((prev) => prev.map((t) => (
932
+ t.path === path
933
+ ? { ...t, content: baseline, savedContent: baseline, pendingFileContent: null, isDirty: false }
934
+ : t
935
+ )));
936
+ bumpFs();
937
+ }, [workspaceId, bumpFs]);
938
+
939
+ // ── fsRevision invalidation ───────────────────────────────────────────────
940
+
941
+ // When the working tree mutates, refetch the active tab's bytes in the
942
+ // background and swap only if they actually changed. Inactive non-dirty
943
+ // tabs are nulled so re-activating them triggers a refetch. Dirty tabs are
944
+ // never touched — that's the user's in-flight work.
945
+ //
946
+ // **Why we don't null the active tab too** — nulling it would unmount the
947
+ // renderer until the eager refetch resolves (FileViewer early-returns when
948
+ // `openFileContent === null`). On a save-induced bump that's a visible
949
+ // flicker: the file briefly disappears, then the renderer remounts. By
950
+ // keeping the active tab's current bytes in place and only swapping on a
951
+ // genuine diff, the user sees a stable view when bytes haven't changed,
952
+ // and a clean swap when they have.
953
+ const prevFsRevisionRef = useRef(0);
954
+ useEffect(() => {
955
+ if (fsRevision === prevFsRevisionRef.current) return;
956
+ prevFsRevisionRef.current = fsRevision;
957
+ if (fsRevision === 0) return;
958
+
959
+ const activePath = activeTabPathRef.current;
960
+ const activeBeforeInvalidation = openTabsRef.current.find((t) => t.path === activePath);
961
+ const activeIsDirty = activeBeforeInvalidation?.isDirty ?? false;
962
+
963
+ // Null inactive non-dirty tabs so re-activating them triggers a refetch.
964
+ // The active tab keeps its current content — the eager refetch below
965
+ // swaps it only if the bytes actually changed.
966
+ // eslint-disable-next-line react-hooks/set-state-in-effect
967
+ setOpenTabs((prev) => prev.map((t) => {
968
+ if (t.isDirty || t.path === activePath) return t;
969
+ return { ...t, content: null, savedContent: null };
970
+ }));
971
+
972
+ if (activePath && workspaceId && !activeIsDirty) {
973
+ // Snapshot the workspace and the tab's content fingerprint at issue
974
+ // time. `readFile` yields to the event loop — while it's in flight
975
+ // the user can switch branches, switch active tabs, or start typing,
976
+ // any of which means applying the fetched bytes would clobber
977
+ // newer state. Re-check inside the updater before mutating.
978
+ const expectedWorkspaceId = workspaceId;
979
+ const baselineContent = activeBeforeInvalidation?.content ?? null;
980
+ const baselineSavedContent = activeBeforeInvalidation?.savedContent ?? null;
981
+ readFile(expectedWorkspaceId, activePath).then((content) => {
982
+ if (workspaceIdRef.current !== expectedWorkspaceId) return;
983
+ if (activeTabPathRef.current !== activePath) return;
984
+ setOpenTabs((prev) => prev.map((t) => {
985
+ if (t.path !== activePath) return t;
986
+ // Tab now dirty / has pending agent content / its baseline
987
+ // moved out from under us (e.g. saveFile already updated it
988
+ // synchronously). Anything other than "still the buffer we
989
+ // issued the read against" means newer state wins.
990
+ if (t.isDirty || t.pendingFileContent !== null) return t;
991
+ if (t.content !== baselineContent || t.savedContent !== baselineSavedContent) return t;
992
+ // Same-bytes short-circuit: a save-triggered bump where the tab
993
+ // was already updated synchronously by saveFile() will land here
994
+ // with identical content, so we avoid a needless re-render.
995
+ if (content === t.content && content === t.savedContent) return t;
996
+ return { ...t, content, savedContent: content };
997
+ }));
998
+ }).catch((err) => {
999
+ if (workspaceIdRef.current !== expectedWorkspaceId) return;
1000
+ if (err instanceof WorkspaceApiError && err.status === 404) {
1001
+ setOpenTabs((prev) => prev.filter((t) => t.path !== activePath));
1002
+ setActiveTabPath((cur) => {
1003
+ if (cur !== activePath) return cur;
1004
+ const surviving = openTabsRef.current.filter((t) => t.path !== activePath);
1005
+ return surviving[surviving.length - 1]?.path ?? null;
1006
+ });
1007
+ } else {
1008
+ console.error('Failed to refetch active tab content:', err);
1009
+ }
1010
+ });
1011
+ }
1012
+ }, [fsRevision, workspaceId]);
1013
+
1014
+ // ── Reset hydratedKey when persistenceBranch changes ──────────────────────
1015
+
1016
+ // When the user switches branches, the previously-hydrated key no longer
1017
+ // applies. Clear the marker so the auto-persist effect waits for a fresh
1018
+ // `hydrateTabs` call before writing localStorage for the new branch.
1019
+ useEffect(() => {
1020
+ if (!workspaceId || !persistenceBranch) {
1021
+ hydratedKeyRef.current = null;
1022
+ return;
1023
+ }
1024
+ const key = `${workspaceId}.${persistenceBranch}`;
1025
+ if (hydratedKeyRef.current !== key) {
1026
+ hydratedKeyRef.current = null;
1027
+ }
1028
+ }, [workspaceId, persistenceBranch]);
1029
+
1030
+ // ── Auto-persist tabs to localStorage (debounced) ─────────────────────────
1031
+
1032
+ useEffect(() => {
1033
+ if (!workspaceId || !persistenceBranch) return;
1034
+ const key = `${workspaceId}.${persistenceBranch}`;
1035
+ if (hydratedKeyRef.current !== key) return;
1036
+
1037
+ const handle = window.setTimeout(() => {
1038
+ try {
1039
+ const payload: PersistedTabState = {
1040
+ paths: openTabs.map((t) => t.path),
1041
+ activePath: activeTabPath,
1042
+ };
1043
+ localStorage.setItem(tabsKey(workspaceId, persistenceBranch), JSON.stringify(payload));
1044
+ } catch (err) {
1045
+ console.warn('Failed to persist tabs:', err);
1046
+ }
1047
+ }, PERSIST_DEBOUNCE_MS);
1048
+ return () => window.clearTimeout(handle);
1049
+ }, [openTabs, activeTabPath, workspaceId, persistenceBranch]);
1050
+
1051
+ const deleteWorkspace = useCallback(async () => {
1052
+ if (!workspaceId) return;
1053
+ try {
1054
+ await deleteWorkspaceApi(workspaceId);
1055
+ closeAllTabs();
1056
+ // Re-bootstrap on the SAME branch the user was viewing. Without
1057
+ // passing `persistenceBranch`, getOrCreateWorkspace falls back to
1058
+ // the default branch (`target-company-state`), which silently
1059
+ // swaps the user onto a different branch after a delete.
1060
+ const branch = persistenceBranchRef.current ?? undefined;
1061
+ const { workspace, fileTree: tree } = await getOrCreateWorkspace(branch);
1062
+ setWorkspaceId(workspace.id);
1063
+ setKbDirName(workspace.kbDirName);
1064
+ setFileTree(tree);
1065
+ } catch (err) {
1066
+ console.error('Failed to delete workspace:', err);
1067
+ }
1068
+ }, [workspaceId, closeAllTabs]);
1069
+
1070
+ // ── Live updates: react to other users' / agent's edits ───────────────────
1071
+ //
1072
+ // When the backend's lock-release commits + pushes a file, the workflow
1073
+ // event bus pushes a `file-changed` event to every session focused on
1074
+ // this workspace+branch. We:
1075
+ //
1076
+ // 1. Refresh the file tree (the path may be new or deleted).
1077
+ // 2. For an open tab matching the changed path, refetch the content
1078
+ // and replace the buffer unconditionally. The dirty bit is cleared
1079
+ // because the local buffer is now superseded by what's on disk.
1080
+ //
1081
+ // **Why we don't filter by "is it our own save"** — when the user's own
1082
+ // lock-release fires, the SSE event echoes back to this tab. We refetch,
1083
+ // the new content equals `savedContent` (we just wrote it), and the
1084
+ // comparison short-circuits the state update entirely (no re-render).
1085
+ // Same code path handles "another user changed the file" and "I just
1086
+ // saved" without needing to know the current user's id.
1087
+ //
1088
+ // **Why we don't preserve a dirty buffer** — the alternative is a silent
1089
+ // last-write-wins overwrite when this user next acquires the lock and
1090
+ // saves: the cached pre-update content + their typing would clobber the
1091
+ // teammate's commit. Auto-reloading is louder than silent overwrite and
1092
+ // is the right default given how the lock pipeline serialises writes.
1093
+ //
1094
+ // The bus only delivers workspace-scoped events for the currently
1095
+ // focused workspace (set by `EventBusFocusBinder`), so the workspace
1096
+ // filter on the handler is belt-and-braces.
1097
+ // Track the current workspaceId in a ref so the async readFile handler
1098
+ // below can detect a workspace switch that happened after it was
1099
+ // subscribed but before its fetch resolved — otherwise a stale resolve
1100
+ // would call `setOpenTabs` on the new workspace's tabs, replacing the
1101
+ // wrong file's content with bytes from the old branch.
1102
+ const workspaceIdRef = useRef<string | null>(workspaceId);
1103
+ useEffect(() => { workspaceIdRef.current = workspaceId; }, [workspaceId]);
1104
+
1105
+ // Reset the optimistic-overlay state on workspace switch. Without this,
1106
+ // pending entries from a partly-uploaded folder on branch A linger in
1107
+ // the explorer after the user switches to branch B, and the async
1108
+ // dispatchUpload tail can keep mutating these refs for the old
1109
+ // workspace. Clearing both refs + the rendered Map together keeps the
1110
+ // overlay tied to the workspace it was generated for. The setState in
1111
+ // here is the intentional "reset on key change" pattern — the other
1112
+ // useEffect in this file uses the same exemption.
1113
+ useEffect(() => {
1114
+ pendingUploadsRef.current = new Map();
1115
+ pendingDeletePathsRef.current = new Set();
1116
+ // eslint-disable-next-line react-hooks/set-state-in-effect
1117
+ setPendingUploads(new Map());
1118
+ }, [workspaceId]);
1119
+
1120
+ const bus = useEventBus();
1121
+ useEffect(() => {
1122
+ if (!bus || !workspaceId) return;
1123
+ // Pin the workspaceId at subscription time. The handler closure
1124
+ // already captures `workspaceId`, but the in-flight readFile that
1125
+ // each invocation kicks off may resolve AFTER the workspace has
1126
+ // switched. The check against `workspaceIdRef.current` below
1127
+ // discards stale resolves so we never apply old-branch bytes to a
1128
+ // new-branch tab.
1129
+ const subscribedWorkspaceId = workspaceId;
1130
+ // Canonicalise once for every subsequent comparison — see the
1131
+ // helper's doc for why the two sides arrive in different
1132
+ // encodings. Without this, every feature branch with `/` in the
1133
+ // name silently drops every event.
1134
+ const subscribedCanon = canonicalizeWorkspaceId(subscribedWorkspaceId);
1135
+ const offFileChanged = bus.subscribe('file-changed', (event) => {
1136
+ if (canonicalizeWorkspaceId(event.workspaceId) !== subscribedCanon) return;
1137
+ void refreshFileTree();
1138
+ // (No access-denied tab recovery here: a tab whose read 403s auto-closes
1139
+ // immediately, so there is never a denied tab to revive. A re-granted
1140
+ // file reappears in the refreshed tree instead.)
1141
+ const matchingTab = openTabsRef.current.find((t) => t.path === event.path);
1142
+ if (!matchingTab) return;
1143
+ // Don't clobber a pending agent preview the user is reviewing.
1144
+ // The agent's bytes are still on disk; the user is comparing
1145
+ // them against the current accepted content. Overwriting with
1146
+ // freshly-fetched disk bytes (which may include the agent's
1147
+ // write) would silently end their review.
1148
+ if (matchingTab.pendingFileContent !== null) return;
1149
+ readFile(subscribedWorkspaceId, event.path)
1150
+ .then((content) => {
1151
+ if (workspaceIdRef.current !== subscribedWorkspaceId) {
1152
+ // Workspace switched while the refetch was in flight. The
1153
+ // tab list we'd be mutating is for a different branch now
1154
+ // — discard the stale result rather than apply old-branch
1155
+ // bytes to the new branch.
1156
+ return;
1157
+ }
1158
+ setOpenTabs((tabs) =>
1159
+ tabs.map((t) => {
1160
+ if (t.path !== event.path) return t;
1161
+ // Re-check pending status inside the updater — `setPendingContent`
1162
+ // may have landed during the readFile await.
1163
+ if (t.pendingFileContent !== null) return t;
1164
+ // Self-save echo: backend emits the event for our own
1165
+ // releaseLock too. Skip the update so the tab doesn't
1166
+ // re-render uselessly.
1167
+ if (content === t.savedContent && content === t.content) return t;
1168
+ return {
1169
+ ...t,
1170
+ content,
1171
+ savedContent: content,
1172
+ isDirty: false,
1173
+ pendingFileContent: null,
1174
+ };
1175
+ }),
1176
+ );
1177
+ })
1178
+ .catch((err) => {
1179
+ if (err instanceof WorkspaceApiError && err.status === 403) {
1180
+ // Read access revoked underneath us — auto-close the tab instead
1181
+ // of leaving previously-loaded bytes visible.
1182
+ if (workspaceIdRef.current !== subscribedWorkspaceId) return;
1183
+ dropTabByPath(event.path);
1184
+ return;
1185
+ }
1186
+ console.warn(`[workspace] refetch on file-changed failed for "${event.path}":`, err);
1187
+ });
1188
+ });
1189
+ const offFsTreeChanged = bus.subscribe('fs-tree-changed', (event) => {
1190
+ if (canonicalizeWorkspaceId(event.workspaceId) !== subscribedCanon) return;
1191
+ void refreshFileTree();
1192
+ });
1193
+ // Belt-and-suspenders: also refetch on `lock-released` for any open
1194
+ // tab. The teammate's save emits both `lock-released` and (when the
1195
+ // commit landed) `file-changed`, but if file-changed didn't fire —
1196
+ // e.g. the backend gated it on `if (change)` and `commitFile`
1197
+ // returned null for some edge case (whitespace-only diff stripped by
1198
+ // line-ending normalization, etc.) — the lock-released event still
1199
+ // gives us a signal that something MAY have changed. Refetching is
1200
+ // idempotent: identical bytes hit the same-content short-circuit
1201
+ // below and yield no re-render.
1202
+ const offLockReleased = bus.subscribe('lock-released', (event) => {
1203
+ if (canonicalizeWorkspaceId(event.workspaceId) !== subscribedCanon) return;
1204
+ const matchingTab = openTabsRef.current.find((t) => t.path === event.path);
1205
+ if (!matchingTab) return;
1206
+ // Skip if WE just released the lock — that path is already
1207
+ // handled by `saveFile` updating the tab + the `file-changed`
1208
+ // self-echo. Refetching here would race against that and is
1209
+ // wasted work.
1210
+ if (matchingTab.isDirty) return;
1211
+ // Don't clobber a pending agent preview — see file-changed
1212
+ // handler above for the same guard's rationale.
1213
+ if (matchingTab.pendingFileContent !== null) return;
1214
+ readFile(subscribedWorkspaceId, event.path)
1215
+ .then((content) => {
1216
+ if (workspaceIdRef.current !== subscribedWorkspaceId) return;
1217
+ setOpenTabs((tabs) => tabs.map((t) => {
1218
+ if (t.path !== event.path) return t;
1219
+ if (t.pendingFileContent !== null) return t;
1220
+ if (content === t.savedContent && content === t.content) return t;
1221
+ return {
1222
+ ...t,
1223
+ content,
1224
+ savedContent: content,
1225
+ isDirty: false,
1226
+ pendingFileContent: null,
1227
+ };
1228
+ }));
1229
+ })
1230
+ .catch((err) => {
1231
+ if (err instanceof WorkspaceApiError && err.status === 403) {
1232
+ // Read access revoked underneath us — auto-close the tab.
1233
+ if (workspaceIdRef.current !== subscribedWorkspaceId) return;
1234
+ dropTabByPath(event.path);
1235
+ return;
1236
+ }
1237
+ console.warn(`[workspace] refetch on lock-released failed for "${event.path}":`, err);
1238
+ });
1239
+ });
1240
+ return () => {
1241
+ offFileChanged();
1242
+ offFsTreeChanged();
1243
+ offLockReleased();
1244
+ };
1245
+ }, [bus, workspaceId, refreshFileTree, dropTabByPath]);
1246
+
1247
+ // ── Derived values ────────────────────────────────────────────────────────
1248
+
1249
+ const activeTab = useMemo(
1250
+ () => openTabs.find((t) => t.path === activeTabPath) ?? null,
1251
+ [openTabs, activeTabPath],
1252
+ );
1253
+ const dirtyTabFilenames = useMemo(
1254
+ () => openTabs.filter((t) => t.isDirty).map((t) => basename(t.path)),
1255
+ [openTabs],
1256
+ );
1257
+ const hasUnsavedFileChanges = dirtyTabFilenames.length > 0;
1258
+ const openFilePath = activeTab?.path ?? null;
1259
+ const openFileContent = activeTab?.content ?? null;
1260
+ const openFileSavedContent = activeTab?.savedContent ?? null;
1261
+ const pendingFileContent = activeTab?.pendingFileContent ?? null;
1262
+
1263
+ return useMemo(() => ({
1264
+ workspaceId,
1265
+ kbDirName,
1266
+ fileTree,
1267
+ openTabs,
1268
+ activeTab,
1269
+ dirtyTabFilenames,
1270
+ openFilePath,
1271
+ openFileContent,
1272
+ openFileSavedContent,
1273
+ hasUnsavedFileChanges,
1274
+ pendingFileContent,
1275
+ setHasUnsavedFileChanges,
1276
+ setActiveTabContent,
1277
+ fsRevision,
1278
+ uploadError,
1279
+ isUploading,
1280
+ uploadProgress,
1281
+ pendingUploads,
1282
+ refreshFileTree,
1283
+ bumpFsRevision: bumpFs,
1284
+ addTab,
1285
+ closeTab,
1286
+ activateTab,
1287
+ reorderTab,
1288
+ closeAllTabs,
1289
+ hydrateTabs,
1290
+ createFile,
1291
+ createDirectory,
1292
+ unzipHere,
1293
+ uploadFiles,
1294
+ dispatchUpload,
1295
+ clearUploadError,
1296
+ deleteEntry,
1297
+ moveEntry,
1298
+ saveFile,
1299
+ reloadTabFromDisk,
1300
+ setPendingContent,
1301
+ acceptPendingContent,
1302
+ rejectPendingContent,
1303
+ setPersistenceBranch,
1304
+ deleteWorkspace,
1305
+ }), [
1306
+ workspaceId, kbDirName, fileTree, openTabs, activeTab, dirtyTabFilenames,
1307
+ openFilePath, openFileContent, openFileSavedContent, hasUnsavedFileChanges, pendingFileContent,
1308
+ setHasUnsavedFileChanges, setActiveTabContent, fsRevision, uploadError, isUploading, uploadProgress, pendingUploads, refreshFileTree, bumpFs,
1309
+ addTab, closeTab, activateTab, reorderTab, closeAllTabs, hydrateTabs,
1310
+ createFile, createDirectory, unzipHere, uploadFiles, dispatchUpload, clearUploadError,
1311
+ deleteEntry, moveEntry, saveFile, reloadTabFromDisk,
1312
+ setPendingContent, acceptPendingContent, rejectPendingContent,
1313
+ setPersistenceBranch, deleteWorkspace,
1314
+ ]);
1315
+ }