@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,1068 @@
1
+ import { useState, useCallback, useEffect, useMemo, useRef, createContext, useContext } from 'react';
2
+ import {
3
+ Folder,
4
+ FolderOpen,
5
+ ChevronRight,
6
+ ChevronDown,
7
+ FilePlus,
8
+ FolderPlus,
9
+ FolderUp,
10
+ Trash2,
11
+ Pencil,
12
+ Upload,
13
+ X,
14
+ PackageOpen,
15
+ Download,
16
+ Loader2,
17
+ Pin,
18
+ PinOff,
19
+ Users,
20
+ } from 'lucide-react';
21
+ import { Icon } from '@iconify/react';
22
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
23
+ import {
24
+ validateFilename,
25
+ KNOWLEDGE_BASE_DIR,
26
+ SKILLS_DIR,
27
+ TOOLS_DIR,
28
+ DATA_DIR,
29
+ AGENTS_DIR,
30
+ PIPELINES_DIR,
31
+ } from '@bevel-software/platform-shared';
32
+ import { useWorkspace } from '../state/workspace.context';
33
+ import { mergePendingIntoTree, findKbRoot, KB_ROOT_DIRS } from '../utils/fileTree';
34
+ import { snapshotEntries } from '../utils/readDroppedEntries';
35
+ import { useFileNav } from '../routing/kb-routes';
36
+ import { authFetch } from '../../../lib/api';
37
+ import { getFileIcon } from '../../../lib/utils';
38
+ import { PullRequestsForMe } from '../../git/components/PullRequestsForMe';
39
+ import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
40
+ import { useAppRegistry } from '../../../core/registry';
41
+
42
+ // ── Pinned folders (client-side, localStorage) ──
43
+
44
+ const PINNED_STORAGE_KEY = 'bevel-pinned-folders';
45
+
46
+ function readPinnedPaths(): string[] {
47
+ if (typeof window === 'undefined') return [];
48
+ try {
49
+ const raw = window.localStorage.getItem(PINNED_STORAGE_KEY);
50
+ const parsed = raw ? JSON.parse(raw) : [];
51
+ return Array.isArray(parsed) ? parsed.filter((p): p is string => typeof p === 'string') : [];
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ interface PinnedController {
58
+ isPinned: (path: string) => boolean;
59
+ togglePin: (path: string) => void;
60
+ }
61
+
62
+ // Default no-op so a ContextMenu rendered outside the provider (e.g. in a unit
63
+ // test) never throws — the real controller is supplied by FileExplorer.
64
+ const PinnedContext = createContext<PinnedController>({
65
+ isPinned: () => false,
66
+ togglePin: () => {},
67
+ });
68
+ const usePinned = () => useContext(PinnedContext);
69
+
70
+ // Lets the deep right-click menu open the Manage access sheet without prop
71
+ // drilling through the recursive tree. FileExplorer supplies the opener and
72
+ // renders the dialog.
73
+ const ManageAccessContext = createContext<(entry: FileTreeEntry) => void>(() => {});
74
+ const useManageAccess = () => useContext(ManageAccessContext);
75
+
76
+ /** Depth-first lookup of a tree entry by its exact relativePath. */
77
+ function findEntryByPath(node: FileTreeEntry, path: string): FileTreeEntry | null {
78
+ if (node.relativePath === path) return node;
79
+ if (!node.children) return null;
80
+ for (const child of node.children) {
81
+ const found = findEntryByPath(child, path);
82
+ if (found) return found;
83
+ }
84
+ return null;
85
+ }
86
+
87
+ // ── Context Menu ──
88
+
89
+ function ContextMenu({
90
+ x,
91
+ y,
92
+ entry,
93
+ isRoot,
94
+ onClose,
95
+ onCreateFile,
96
+ onCreateFolder,
97
+ onRename,
98
+ onDownload,
99
+ }: {
100
+ x: number;
101
+ y: number;
102
+ entry: FileTreeEntry;
103
+ isRoot: boolean;
104
+ onClose: () => void;
105
+ onCreateFile?: () => void;
106
+ onCreateFolder?: () => void;
107
+ onRename?: () => void;
108
+ onDownload?: () => void;
109
+ }) {
110
+ const { deleteEntry, unzipHere } = useWorkspace();
111
+ const { isPinned, togglePin } = usePinned();
112
+ const openManageAccess = useManageAccess();
113
+ const pinned = isPinned(entry.relativePath);
114
+ const ref = useRef<HTMLDivElement>(null);
115
+ const [unzipping, setUnzipping] = useState(false);
116
+
117
+ // Only files whose name ends with `.zip` (case-insensitive) get the
118
+ // extraction affordance — matches the OS shell-extension behavior users
119
+ // already know from Windows Explorer / macOS Finder.
120
+ const isZip = entry.type === 'file' && /\.zip$/i.test(entry.name);
121
+
122
+ useEffect(() => {
123
+ const handler = (e: MouseEvent) => {
124
+ if (ref.current && !ref.current.contains(e.target as Node)) onClose();
125
+ };
126
+ document.addEventListener('mousedown', handler);
127
+ return () => document.removeEventListener('mousedown', handler);
128
+ }, [onClose]);
129
+
130
+ const handleDelete = async () => {
131
+ onClose();
132
+ try {
133
+ await deleteEntry(entry.relativePath);
134
+ } catch (err) {
135
+ console.error('Failed to delete entry:', err);
136
+ const msg = err instanceof Error ? err.message : String(err);
137
+ alert(`Failed to delete ${entry.relativePath}:\n${msg}`);
138
+ }
139
+ };
140
+
141
+ const handleUnzip = async () => {
142
+ if (unzipping) return;
143
+ setUnzipping(true);
144
+ try {
145
+ const result = await unzipHere(entry.relativePath);
146
+ onClose();
147
+ // Surface a summary banner only when something was skipped — a silent
148
+ // success is the right behavior for the happy path (matches Finder /
149
+ // Explorer's "Extract here").
150
+ if (result.skipped.length > 0) {
151
+ const preview = result.skipped
152
+ .slice(0, 5)
153
+ .map((s) => ` - ${s.path}: ${s.reason}`)
154
+ .join('\n');
155
+ const more = result.skipped.length > 5 ? `\n …and ${result.skipped.length - 5} more` : '';
156
+ alert(
157
+ `Extracted ${result.extracted} file(s) from ${entry.name}.\n` +
158
+ `Skipped ${result.skipped.length} entry(ies):\n${preview}${more}`,
159
+ );
160
+ }
161
+ } catch (err) {
162
+ console.error('Failed to unzip:', err);
163
+ const msg = err instanceof Error ? err.message : String(err);
164
+ alert(`Failed to unzip ${entry.name}:\n${msg}`);
165
+ } finally {
166
+ setUnzipping(false);
167
+ }
168
+ };
169
+
170
+ return (
171
+ <div
172
+ ref={ref}
173
+ className="fixed z-50 bg-slate-100 border border-slate-300 rounded-md shadow-xl py-1 min-w-[140px]"
174
+ style={{ left: x, top: y }}
175
+ onMouseDown={(e) => e.stopPropagation()}
176
+ >
177
+ {onCreateFile && (
178
+ <button
179
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
180
+ onClick={() => { onCreateFile(); onClose(); }}
181
+ >
182
+ <FilePlus size={14} />
183
+ New file
184
+ </button>
185
+ )}
186
+ {onCreateFolder && (
187
+ <button
188
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
189
+ onClick={() => { onCreateFolder(); onClose(); }}
190
+ >
191
+ <FolderPlus size={14} />
192
+ New folder
193
+ </button>
194
+ )}
195
+ {isZip && (
196
+ <button
197
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80 disabled:opacity-60 disabled:cursor-not-allowed"
198
+ onClick={handleUnzip}
199
+ disabled={unzipping}
200
+ >
201
+ <PackageOpen size={14} />
202
+ {unzipping ? 'Unzipping…' : 'Unzip here'}
203
+ </button>
204
+ )}
205
+ {onDownload && (
206
+ <button
207
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
208
+ onClick={() => { onDownload(); onClose(); }}
209
+ >
210
+ <Download size={14} />
211
+ {entry.type === 'directory' ? 'Download as zip' : 'Download'}
212
+ </button>
213
+ )}
214
+ {!isRoot && (
215
+ <>
216
+ <div className="my-1 border-t border-slate-200/70" />
217
+ <button
218
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-bevel-deep font-medium hover:bg-slate-200/80"
219
+ onClick={() => { openManageAccess(entry); onClose(); }}
220
+ >
221
+ <Users size={14} />
222
+ Manage access
223
+ </button>
224
+ </>
225
+ )}
226
+ {entry.type === 'directory' && !isRoot && (
227
+ <button
228
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
229
+ onClick={() => { togglePin(entry.relativePath); onClose(); }}
230
+ >
231
+ {pinned ? <PinOff size={14} /> : <Pin size={14} />}
232
+ {pinned ? 'Unpin' : 'Pin to top'}
233
+ </button>
234
+ )}
235
+ {!isRoot && onRename && (
236
+ <button
237
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-200/80"
238
+ onClick={() => { onRename(); onClose(); }}
239
+ >
240
+ <Pencil size={14} />
241
+ Rename
242
+ </button>
243
+ )}
244
+ {!isRoot && (
245
+ <button
246
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm text-red-600 hover:bg-slate-200/80"
247
+ onClick={handleDelete}
248
+ >
249
+ <Trash2 size={14} />
250
+ Delete
251
+ </button>
252
+ )}
253
+ </div>
254
+ );
255
+ }
256
+
257
+ // ── Inline Input ──
258
+
259
+ function InlineInput({
260
+ onSubmit,
261
+ onCancel,
262
+ placeholder,
263
+ }: {
264
+ onSubmit: (value: string) => void;
265
+ onCancel: () => void;
266
+ placeholder: string;
267
+ }) {
268
+ const [value, setValue] = useState('');
269
+ const trimmed = value.trim();
270
+ const error = trimmed.length === 0 ? null : validateFilename(trimmed);
271
+ const valid = trimmed.length > 0 && error === null;
272
+
273
+ const submit = () => {
274
+ if (valid) onSubmit(trimmed);
275
+ };
276
+
277
+ return (
278
+ <div className="w-full">
279
+ <input
280
+ autoFocus
281
+ className={`w-full bg-slate-100 text-slate-900 text-sm px-2 py-0.5 rounded border outline-none ${
282
+ error ? 'border-red-500' : 'border-slate-300 focus:border-slate-400'
283
+ }`}
284
+ placeholder={placeholder}
285
+ value={value}
286
+ onChange={(e) => setValue(e.target.value)}
287
+ onKeyDown={(e) => {
288
+ if (e.key === 'Enter') submit();
289
+ if (e.key === 'Escape') onCancel();
290
+ }}
291
+ onBlur={() => {
292
+ if (valid) onSubmit(trimmed);
293
+ else onCancel();
294
+ }}
295
+ title={error ?? undefined}
296
+ />
297
+ {error && (
298
+ <div className="text-[11px] text-red-700 mt-0.5 px-1">{error}</div>
299
+ )}
300
+ </div>
301
+ );
302
+ }
303
+
304
+ // ── Rename Input ──
305
+
306
+ function RenameInput({
307
+ currentName,
308
+ isFile,
309
+ onSubmit,
310
+ onCancel,
311
+ }: {
312
+ currentName: string;
313
+ isFile: boolean;
314
+ onSubmit: (value: string) => void;
315
+ onCancel: () => void;
316
+ }) {
317
+ const [value, setValue] = useState(currentName);
318
+ const trimmed = value.trim();
319
+ const error = trimmed.length === 0 ? null : validateFilename(trimmed);
320
+ const valid = trimmed.length > 0 && error === null;
321
+
322
+ const submit = () => {
323
+ if (valid && trimmed !== currentName) onSubmit(trimmed);
324
+ else onCancel();
325
+ };
326
+
327
+ return (
328
+ <div className="w-full">
329
+ <input
330
+ autoFocus
331
+ className={`w-full bg-slate-100 text-slate-900 text-sm px-2 py-0.5 rounded border outline-none ${
332
+ error ? 'border-red-500' : 'border-slate-300 focus:border-slate-400'
333
+ }`}
334
+ value={value}
335
+ onClick={(e) => e.stopPropagation()}
336
+ onMouseDown={(e) => e.stopPropagation()}
337
+ onChange={(e) => setValue(e.target.value)}
338
+ onKeyDown={(e) => {
339
+ if (e.key === 'Enter') submit();
340
+ if (e.key === 'Escape') onCancel();
341
+ }}
342
+ onBlur={submit}
343
+ onFocus={(e) => {
344
+ if (isFile) {
345
+ // Select name without extension for files
346
+ const dotIdx = currentName.lastIndexOf('.');
347
+ if (dotIdx > 0) e.target.setSelectionRange(0, dotIdx);
348
+ else e.target.select();
349
+ } else {
350
+ e.target.select();
351
+ }
352
+ }}
353
+ title={error ?? undefined}
354
+ />
355
+ {error && (
356
+ <div className="text-[11px] text-red-700 mt-0.5 px-1">{error}</div>
357
+ )}
358
+ </div>
359
+ );
360
+ }
361
+
362
+ // ── Tree Node ──
363
+
364
+ const DRAG_MIME = 'application/x-workspace-path';
365
+
366
+ function FileTreeNode({
367
+ entry,
368
+ depth,
369
+ initiallyExpanded,
370
+ accent,
371
+ collapseChildren,
372
+ }: {
373
+ entry: FileTreeEntry;
374
+ depth: number;
375
+ // Overrides the depth-based default for whether this node starts expanded.
376
+ // The explorer's Knowledge/Skills roots use this so their own children start
377
+ // collapsed regardless of depth (auto-reveal on deep links still wins).
378
+ initiallyExpanded?: boolean;
379
+ // Green-tints the folder icon + label — used for the Knowledge / Skills roots.
380
+ accent?: boolean;
381
+ // When set, this node's direct children start collapsed (so opening Knowledge
382
+ // reveals the ontologies without cascading them all open).
383
+ collapseChildren?: boolean;
384
+ }) {
385
+ const { openFilePath, createFile, createDirectory, dispatchUpload, isUploading, moveEntry, workspaceId, pendingUploads } = useWorkspace();
386
+ const { openFile } = useFileNav();
387
+
388
+ const handleDownload = useCallback(async () => {
389
+ if (!workspaceId) return;
390
+ // Files hit /file/raw; folders hit /folder/zip and arrive as <name>.zip.
391
+ // Both endpoints share the same per-path `download:` access gate, the
392
+ // same `?download=1` flag shape, and the same Content-Disposition
393
+ // handling on the backend — branching here just picks the URL.
394
+ // No preflight: a 403 surfaces in the alert below.
395
+ const isFolder = entry.type === 'directory';
396
+ const url = isFolder
397
+ ? `/api/workspace/${workspaceId}/folder/zip?path=${encodeURIComponent(entry.relativePath)}&download=1`
398
+ : `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(entry.relativePath)}&download=1`;
399
+ const savedAs = isFolder ? `${entry.name}.zip` : entry.name;
400
+ try {
401
+ const res = await authFetch(url);
402
+ if (!res.ok) {
403
+ const body = await res.text().catch(() => '');
404
+ alert(`Failed to download ${entry.name} (HTTP ${res.status})${body ? `: ${body}` : ''}`);
405
+ return;
406
+ }
407
+ const blob = await res.blob();
408
+ const blobUrl = URL.createObjectURL(blob);
409
+ const a = document.createElement('a');
410
+ a.href = blobUrl;
411
+ a.download = savedAs;
412
+ document.body.appendChild(a);
413
+ a.click();
414
+ a.remove();
415
+ URL.revokeObjectURL(blobUrl);
416
+ } catch (err) {
417
+ console.error('Failed to download:', err);
418
+ const msg = err instanceof Error ? err.message : String(err);
419
+ alert(`Failed to download ${entry.name}:\n${msg}`);
420
+ }
421
+ }, [workspaceId, entry.relativePath, entry.name, entry.type]);
422
+ // `null` = no explicit user intent; fall through to the auto-expand / depth
423
+ // default. Once the user clicks the chevron, intent wins over auto-expand
424
+ // until the auto-expand trigger transitions (new file opened, new upload),
425
+ // at which point intent is reset and auto-expand takes over again.
426
+ const [userIntent, setUserIntent] = useState<boolean | null>(null);
427
+ const [creating, setCreating] = useState<'file' | 'directory' | null>(null);
428
+ const [renaming, setRenaming] = useState(false);
429
+ const [dragOver, setDragOver] = useState(false);
430
+ // Only the root row uses these refs, but hooks must run unconditionally.
431
+ const rootFileInputRef = useRef<HTMLInputElement>(null);
432
+ const rootFolderInputRef = useRef<HTMLInputElement>(null);
433
+
434
+ const handleRootUploadClick = useCallback((e: React.MouseEvent) => {
435
+ e.stopPropagation();
436
+ rootFileInputRef.current?.click();
437
+ }, []);
438
+
439
+ const handleRootFolderClick = useCallback((e: React.MouseEvent) => {
440
+ e.stopPropagation();
441
+ rootFolderInputRef.current?.click();
442
+ }, []);
443
+
444
+ // Resetting `value` after dispatch lets users re-select the same file and
445
+ // still get an `onChange` event the second time around.
446
+ const handleRootFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
447
+ const files = Array.from(e.target.files ?? []);
448
+ e.target.value = '';
449
+ if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
450
+ }, [dispatchUpload]);
451
+
452
+ // Folder picker: each File carries a `webkitRelativePath` like
453
+ // "foldername/sub/file.txt" — we feed those straight into the upload
454
+ // pipeline as pre-resolved paths. Note: `<input webkitdirectory>` only
455
+ // enumerates files (the browser hides empty subdirs from us), so empty
456
+ // folders are only preserved via the drag-and-drop path that uses the
457
+ // FileSystem entries API.
458
+ const handleRootFolderChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
459
+ const files = Array.from(e.target.files ?? []);
460
+ e.target.value = '';
461
+ if (files.length === 0) return;
462
+ const items = files.map((file) => ({
463
+ file,
464
+ relativePath: file.webkitRelativePath || file.name,
465
+ }));
466
+ dispatchUpload({ kind: 'paths', items }, '');
467
+ }, [dispatchUpload]);
468
+ const [dragging, setDragging] = useState(false);
469
+ const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
470
+
471
+ const paddingLeft = 12 + depth * 16;
472
+ const isRoot = entry.relativePath === '.';
473
+ const isPending = pendingUploads.has(entry.relativePath);
474
+
475
+ // Auto-expand a directory whenever the open file lives inside it (so
476
+ // deep-link URLs reveal the file's row in the tree) or while files
477
+ // dropped under it are still uploading (so the user can watch them
478
+ // fill in).
479
+ const isOpenFileAncestor = entry.type === 'directory' && !!openFilePath && (
480
+ isRoot || openFilePath.startsWith(entry.relativePath + '/')
481
+ );
482
+ const autoExpanded = entry.type === 'directory' && (isPending || isOpenFileAncestor);
483
+
484
+ // Fingerprint of what currently drives auto-expand. When it transitions
485
+ // (different file opened, upload starts), the user's prior collapse intent
486
+ // is stale — reset so deep-links / new uploads can re-reveal the folder.
487
+ const autoTrigger = `${isPending ? 'P' : ''}|${isOpenFileAncestor ? openFilePath : ''}`;
488
+ const prevAutoTriggerRef = useRef(autoTrigger);
489
+ useEffect(() => {
490
+ if (prevAutoTriggerRef.current !== autoTrigger) {
491
+ prevAutoTriggerRef.current = autoTrigger;
492
+ setUserIntent(null);
493
+ }
494
+ }, [autoTrigger]);
495
+
496
+ const isExpanded = userIntent ?? (autoExpanded || (initiallyExpanded ?? depth < 2));
497
+
498
+ const handleContextMenu = useCallback((e: React.MouseEvent) => {
499
+ e.preventDefault();
500
+ e.stopPropagation();
501
+ setContextMenu({ x: e.clientX, y: e.clientY });
502
+ }, []);
503
+
504
+ // ── Drag source (internal reorder) ──
505
+ const handleDragStart = useCallback((e: React.DragEvent) => {
506
+ if (isRoot) { e.preventDefault(); return; }
507
+ e.dataTransfer.setData(DRAG_MIME, entry.relativePath);
508
+ e.dataTransfer.effectAllowed = 'move';
509
+ setDragging(true);
510
+ }, [entry.relativePath, isRoot]);
511
+
512
+ const handleDragEnd = useCallback(() => {
513
+ setDragging(false);
514
+ }, []);
515
+
516
+ // ── Drop target ──
517
+ const handleDrop = useCallback(
518
+ (e: React.DragEvent) => {
519
+ e.preventDefault();
520
+ e.stopPropagation();
521
+ setDragOver(false);
522
+
523
+ // Internal move (reorder)
524
+ const sourcePath = e.dataTransfer.getData(DRAG_MIME);
525
+ if (sourcePath) {
526
+ const targetDir = entry.type === 'directory'
527
+ ? (isRoot ? '' : entry.relativePath)
528
+ : '';
529
+ const name = sourcePath.split('/').pop()!;
530
+ const newPath = targetDir ? `${targetDir}/${name}` : name;
531
+ // Skip no-op or nesting a directory inside itself
532
+ if (
533
+ newPath === sourcePath ||
534
+ targetDir === sourcePath ||
535
+ targetDir.startsWith(sourcePath + '/')
536
+ ) {
537
+ return;
538
+ }
539
+ moveEntry(sourcePath, newPath);
540
+ return;
541
+ }
542
+
543
+ // External file/folder drop. Snapshot the entries synchronously
544
+ // before any await — the browser invalidates `DataTransfer` once the
545
+ // handler returns, and the walker awaits inside.
546
+ const dir = entry.type === 'directory' ? entry.relativePath : '';
547
+ const targetDir = dir === '.' ? '' : dir;
548
+ const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
549
+ if (entries.length > 0) {
550
+ dispatchUpload({ kind: 'items', entries }, targetDir);
551
+ return;
552
+ }
553
+ // Fallback for older browsers / non-entry drops: use the flat FileList.
554
+ const files = Array.from(e.dataTransfer.files);
555
+ if (files.length === 0) return;
556
+ dispatchUpload({ kind: 'files', files }, targetDir);
557
+ },
558
+ [entry, isRoot, dispatchUpload, moveEntry],
559
+ );
560
+
561
+ const handleDragOver = useCallback((e: React.DragEvent) => {
562
+ e.preventDefault();
563
+ e.stopPropagation();
564
+ if (entry.type === 'directory') {
565
+ e.dataTransfer.dropEffect = 'move';
566
+ setDragOver(true);
567
+ }
568
+ }, [entry.type]);
569
+
570
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
571
+ e.preventDefault();
572
+ e.stopPropagation();
573
+ setDragOver(false);
574
+ }, []);
575
+
576
+ if (entry.type === 'directory') {
577
+ const dirPath = isRoot ? '' : entry.relativePath;
578
+ return (
579
+ <div>
580
+ <div
581
+ className={`flex items-center gap-1 w-full text-left py-1 px-2 text-sm text-slate-700 hover:bg-slate-100/70 rounded group transition-colors duration-150 ${
582
+ dragOver ? 'bg-slate-200/60 ring-1 ring-bevel/50' : ''
583
+ }`}
584
+ style={{ paddingLeft, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
585
+ draggable={!isRoot && !renaming && !isPending}
586
+ onDragStart={handleDragStart}
587
+ onDragEnd={handleDragEnd}
588
+ onDrop={handleDrop}
589
+ onDragOver={handleDragOver}
590
+ onDragLeave={handleDragLeave}
591
+ onContextMenu={handleContextMenu}
592
+ >
593
+ <button
594
+ className="flex items-center gap-1.5 flex-1 min-w-0"
595
+ onClick={() => setUserIntent(!isExpanded)}
596
+ >
597
+ {isExpanded ? (
598
+ <ChevronDown size={14} className="text-slate-600 shrink-0" />
599
+ ) : (
600
+ <ChevronRight size={14} className="text-slate-600 shrink-0" />
601
+ )}
602
+ {isExpanded ? (
603
+ <FolderOpen size={14} className={`shrink-0 ${accent ? 'text-emerald-600' : 'text-slate-600'}`} />
604
+ ) : (
605
+ <Folder size={14} className={`shrink-0 ${accent ? 'text-emerald-600' : 'text-slate-600'}`} />
606
+ )}
607
+ {renaming ? (
608
+ <RenameInput
609
+ currentName={entry.name}
610
+ isFile={false}
611
+ onSubmit={async (newName) => {
612
+ const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
613
+ const newPath = parentDir ? `${parentDir}/${newName}` : newName;
614
+ // Close the input BEFORE the fallible move — see the create
615
+ // flow: on error the alert() blurs the still-mounted input,
616
+ // whose onBlur re-fires this onSubmit, looping the popup.
617
+ setRenaming(false);
618
+ try {
619
+ await moveEntry(entry.relativePath, newPath);
620
+ } catch (err) {
621
+ // Same surfacing as the create flow above — a silent failure
622
+ // reads as the rename being accepted and then reverting.
623
+ const msg = err instanceof Error ? err.message : String(err);
624
+ alert(`Failed to rename ${entry.name}:\n${msg}`);
625
+ }
626
+ }}
627
+ onCancel={() => setRenaming(false)}
628
+ />
629
+ ) : (
630
+ <span className={`truncate ${accent ? 'text-emerald-700 font-medium' : ''}`}>{entry.name}</span>
631
+ )}
632
+ </button>
633
+ <div className="hidden group-hover:flex group-focus-within:flex items-center gap-0.5 shrink-0">
634
+ <button
635
+ className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-700"
636
+ title="New file"
637
+ onClick={(e) => {
638
+ e.stopPropagation();
639
+ setUserIntent(true);
640
+ setCreating('file');
641
+ }}
642
+ >
643
+ <FilePlus size={13} />
644
+ </button>
645
+ <button
646
+ className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-700"
647
+ title="New folder"
648
+ onClick={(e) => {
649
+ e.stopPropagation();
650
+ setUserIntent(true);
651
+ setCreating('directory');
652
+ }}
653
+ >
654
+ <FolderPlus size={13} />
655
+ </button>
656
+ </div>
657
+ {isRoot && (
658
+ <>
659
+ <button
660
+ type="button"
661
+ className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-900 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
662
+ title="Add files"
663
+ aria-label="Add files"
664
+ disabled={isUploading}
665
+ onClick={handleRootUploadClick}
666
+ >
667
+ <Upload size={13} />
668
+ </button>
669
+ <input
670
+ ref={rootFileInputRef}
671
+ type="file"
672
+ multiple
673
+ hidden
674
+ aria-hidden="true"
675
+ data-testid="file-explorer-file-input"
676
+ onChange={handleRootFileChange}
677
+ />
678
+ <button
679
+ type="button"
680
+ className="p-0.5 rounded hover:bg-slate-200 text-slate-600 hover:text-slate-900 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
681
+ title="Add folder"
682
+ aria-label="Add folder"
683
+ disabled={isUploading}
684
+ onClick={handleRootFolderClick}
685
+ >
686
+ <FolderUp size={13} />
687
+ </button>
688
+ <input
689
+ ref={rootFolderInputRef}
690
+ type="file"
691
+ multiple
692
+ webkitdirectory=""
693
+ hidden
694
+ aria-hidden="true"
695
+ data-testid="file-explorer-folder-input"
696
+ onChange={handleRootFolderChange}
697
+ />
698
+ </>
699
+ )}
700
+ </div>
701
+ {isExpanded && (
702
+ <div>
703
+ {creating && (
704
+ <div style={{ paddingLeft: paddingLeft + 34 }} className="py-0.5 px-2">
705
+ <InlineInput
706
+ placeholder={creating === 'file' ? 'filename' : 'folder name'}
707
+ onSubmit={async (name) => {
708
+ const fullPath = dirPath ? `${dirPath}/${name}` : name;
709
+ const kind = creating;
710
+ // Close the inline input BEFORE anything can fail. On
711
+ // error the alert() below steals focus; leaving the input
712
+ // mounted means dismissing the alert blurs it, and the
713
+ // input's onBlur re-fires this same onSubmit — an infinite
714
+ // "Failed to create …" popup loop against an unchanging
715
+ // 403. Unmounting first breaks that cycle.
716
+ setCreating(null);
717
+ try {
718
+ if (kind === 'file') await createFile(fullPath);
719
+ else await createDirectory(fullPath);
720
+ } catch (err) {
721
+ // Surface the refusal (e.g. a protected branch's write
722
+ // gate: "You don't have permission to write to …") —
723
+ // otherwise the input clears and nothing appears, which
724
+ // reads as the file silently vanishing.
725
+ const msg = err instanceof Error ? err.message : String(err);
726
+ alert(`Failed to create ${name}:\n${msg}`);
727
+ }
728
+ }}
729
+ onCancel={() => setCreating(null)}
730
+ />
731
+ </div>
732
+ )}
733
+ {entry.children?.map((child) => (
734
+ <FileTreeNode
735
+ key={child.relativePath}
736
+ entry={child}
737
+ depth={depth + 1}
738
+ initiallyExpanded={collapseChildren ? false : undefined}
739
+ />
740
+ ))}
741
+ </div>
742
+ )}
743
+ {contextMenu && (
744
+ <ContextMenu
745
+ x={contextMenu.x}
746
+ y={contextMenu.y}
747
+ entry={entry}
748
+ isRoot={isRoot}
749
+ onClose={() => setContextMenu(null)}
750
+ onCreateFile={() => { setUserIntent(true); setCreating('file'); }}
751
+ onCreateFolder={() => { setUserIntent(true); setCreating('directory'); }}
752
+ onRename={() => setRenaming(true)}
753
+ onDownload={handleDownload}
754
+ />
755
+ )}
756
+ </div>
757
+ );
758
+ }
759
+
760
+ const isActive = entry.relativePath === openFilePath;
761
+ const iconName = getFileIcon(entry.name);
762
+
763
+ return (
764
+ <>
765
+ <button
766
+ className={`flex items-center gap-1.5 w-full text-left py-1 px-2 text-sm rounded transition-colors duration-150 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-bevel/60 ${
767
+ isActive
768
+ ? 'bg-slate-200/80 text-slate-900'
769
+ : 'text-slate-600 hover:bg-slate-100/70 hover:text-slate-900'
770
+ } ${isPending ? 'cursor-progress' : ''}`}
771
+ style={{ paddingLeft: paddingLeft + 18, opacity: dragging ? 0.5 : isPending ? 0.6 : 1 }}
772
+ draggable={!renaming && !isPending}
773
+ onDragStart={handleDragStart}
774
+ onDragEnd={handleDragEnd}
775
+ onClick={() => { if (!renaming && !isPending) openFile(entry.relativePath); }}
776
+ onContextMenu={handleContextMenu}
777
+ title={isPending ? 'Adding…' : undefined}
778
+ >
779
+ {isPending ? (
780
+ <Loader2 size={14} className="shrink-0 animate-spin text-slate-500" />
781
+ ) : (
782
+ <Icon
783
+ icon={`material-icon-theme:${iconName}`}
784
+ width={16}
785
+ height={16}
786
+ className="shrink-0"
787
+ />
788
+ )}
789
+ {renaming ? (
790
+ <RenameInput
791
+ currentName={entry.name}
792
+ isFile={true}
793
+ onSubmit={async (newName) => {
794
+ const parentDir = entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'));
795
+ const newPath = parentDir ? `${parentDir}/${newName}` : newName;
796
+ // Close the input BEFORE the fallible move — see the create
797
+ // flow: on error the alert() blurs the still-mounted input,
798
+ // whose onBlur re-fires this onSubmit, looping the popup.
799
+ setRenaming(false);
800
+ try {
801
+ await moveEntry(entry.relativePath, newPath);
802
+ } catch (err) {
803
+ // Same surfacing as the create flow — a silent failure reads
804
+ // as the rename being accepted and then reverting.
805
+ const msg = err instanceof Error ? err.message : String(err);
806
+ alert(`Failed to rename ${entry.name}:\n${msg}`);
807
+ }
808
+ }}
809
+ onCancel={() => setRenaming(false)}
810
+ />
811
+ ) : (
812
+ <span className="truncate">{entry.name}</span>
813
+ )}
814
+ </button>
815
+ {contextMenu && (
816
+ <ContextMenu
817
+ x={contextMenu.x}
818
+ y={contextMenu.y}
819
+ entry={entry}
820
+ isRoot={false}
821
+ onClose={() => setContextMenu(null)}
822
+ onRename={() => setRenaming(true)}
823
+ onDownload={handleDownload}
824
+ />
825
+ )}
826
+ </>
827
+ );
828
+ }
829
+
830
+ // ── Explorer Root ──
831
+
832
+ /**
833
+ * Walk down to the node that actually holds the KB content. The file tree roots
834
+ * at the per-branch workspace dir and wraps the KB clone a level or two deep
835
+ * (`<branch>/<kbDir>/{KnowledgeBase,Data,Agents,Pipelines,Skills,Tools,…}`), so
836
+ * the split lives below the visible root. Returns the first node whose children
837
+ * include one of those well-known root directories, or null when there's no
838
+ * such split (legacy clones).
839
+ */
840
+ // (`findKbRoot` lives in `../utils/fileTree` — shared with registry-
841
+ // contributed explorer items.)
842
+
843
+ export function FileExplorer() {
844
+ const { fileTree, dispatchUpload, uploadError, clearUploadError, pendingUploads } = useWorkspace();
845
+ const [dragOver, setDragOver] = useState(false);
846
+ // Download is now a per-path permission (resolved server-side from the
847
+ // access tree's `download:` verb), so there's no global preflight gate
848
+ // here anymore. The menu items always render; if the user clicks on a
849
+ // file they don't have download permission for, the backend returns 403
850
+ // and `handleDownload` shows the error.
851
+ // Optimistic overlay: every dropped/picked file shows up in the tree
852
+ // within a frame, even before its commit echoes back from the server.
853
+ const mergedTree = useMemo(
854
+ () => (fileTree ? mergePendingIntoTree(fileTree, pendingUploads) : null),
855
+ [fileTree, pendingUploads],
856
+ );
857
+
858
+ // Pinned folders — a personal, client-side shortcut list surfaced at the top
859
+ // of the explorer. Stored as relativePaths in localStorage; toggled from the
860
+ // right-click menu (Pin to top / Unpin).
861
+ const [pinnedPaths, setPinnedPaths] = useState<string[]>(readPinnedPaths);
862
+ const togglePin = useCallback((path: string) => {
863
+ setPinnedPaths((prev) => {
864
+ const next = prev.includes(path) ? prev.filter((p) => p !== path) : [...prev, path];
865
+ try {
866
+ window.localStorage.setItem(PINNED_STORAGE_KEY, JSON.stringify(next));
867
+ } catch {
868
+ // localStorage unavailable — pins stay in memory for this session.
869
+ }
870
+ return next;
871
+ });
872
+ }, []);
873
+ const pinnedController = useMemo<PinnedController>(
874
+ () => ({ isPinned: (path) => pinnedPaths.includes(path), togglePin }),
875
+ [pinnedPaths, togglePin],
876
+ );
877
+ // Resolve pinned paths to live tree entries, dropping any that no longer
878
+ // exist on this branch (a folder pinned elsewhere may be absent here).
879
+ const pinnedEntries = useMemo(
880
+ () =>
881
+ mergedTree
882
+ ? pinnedPaths
883
+ .map((p) => findEntryByPath(mergedTree, p))
884
+ .filter((e): e is FileTreeEntry => e != null)
885
+ : [],
886
+ [mergedTree, pinnedPaths],
887
+ );
888
+
889
+ // Registry-contributed rows for the Pinned section (rendered below the
890
+ // pinned folders). The enterprise knowledge system contributes its
891
+ // "Graph view" entry — the interactive ontology graph — this way; the core
892
+ // ships none of its own.
893
+ const { explorerItems } = useAppRegistry();
894
+
895
+ // Right-click → Manage access opens this sheet for the chosen entry.
896
+ const [accessTarget, setAccessTarget] = useState<FileTreeEntry | null>(null);
897
+
898
+ // KB content splits Knowledge (`KnowledgeBase/`), Data (`Data/`), Agents
899
+ // (`Agents/`), Pipelines (`Pipelines/`), Skills (`Skills/`) and Tools
900
+ // (`Tools/`) into separate top-level folders; surface them as labelled sections
901
+ // rather than a single flat root. The Knowledge section hoists `KnowledgeBase/`'s
902
+ // children and folds in any other top-level content folder (e.g. a stray
903
+ // `Legal/`); loose top-level files (access.md, roles.yaml) sit below a divider.
904
+ // Clones that predate the split (none of the well-known root dirs) fall back
905
+ // to the flat tree.
906
+ const sections = useMemo(() => {
907
+ // Descend past the workspace / KB-clone wrapper levels to the node that
908
+ // actually holds the well-known root dirs, then split that level.
909
+ const kids = findKbRoot(mergedTree)?.children;
910
+ if (!kids) return null;
911
+ const findDir = (name: string) =>
912
+ kids.find((c) => c.type === 'directory' && c.name === name);
913
+ const knowledgeBase = findDir(KNOWLEDGE_BASE_DIR);
914
+ const data = findDir(DATA_DIR);
915
+ const agents = findDir(AGENTS_DIR);
916
+ const pipelines = findDir(PIPELINES_DIR);
917
+ const skills = findDir(SKILLS_DIR);
918
+ const tools = findDir(TOOLS_DIR);
919
+ if (!knowledgeBase && !data && !agents && !pipelines && !skills && !tools) return null;
920
+ // Any other top-level content folder (e.g. a stray `Legal/`) folds into Knowledge.
921
+ const otherDirs = kids.filter(
922
+ (c) => c.type === 'directory' && !KB_ROOT_DIRS.has(c.name),
923
+ );
924
+ // Present Knowledge, Data, Agents, Pipelines, Skills and Tools as named
925
+ // roots. Knowledge is synthetic so it can relabel `KnowledgeBase` and
926
+ // absorb the stray content folders; it reuses KnowledgeBase's own path so
927
+ // file ops on the row still resolve.
928
+ const knowledge: FileTreeEntry | null = knowledgeBase
929
+ ? {
930
+ ...knowledgeBase,
931
+ name: 'Knowledge',
932
+ children: [...(knowledgeBase.children ?? []), ...otherDirs],
933
+ }
934
+ : otherDirs.length > 0
935
+ ? { name: 'Knowledge', relativePath: otherDirs[0].relativePath, type: 'directory', children: otherDirs }
936
+ : null;
937
+ const dataRoot: FileTreeEntry | null = data ? { ...data, name: DATA_DIR } : null;
938
+ const agentsRoot: FileTreeEntry | null = agents ? { ...agents, name: AGENTS_DIR } : null;
939
+ const pipelinesRoot: FileTreeEntry | null = pipelines
940
+ ? { ...pipelines, name: PIPELINES_DIR }
941
+ : null;
942
+ const skillsRoot: FileTreeEntry | null = skills ? { ...skills, name: SKILLS_DIR } : null;
943
+ const toolsRoot: FileTreeEntry | null = tools ? { ...tools, name: TOOLS_DIR } : null;
944
+ return {
945
+ knowledge,
946
+ data: dataRoot,
947
+ agents: agentsRoot,
948
+ pipelines: pipelinesRoot,
949
+ skills: skillsRoot,
950
+ tools: toolsRoot,
951
+ looseFiles: kids.filter((c) => c.type === 'file'),
952
+ };
953
+ }, [mergedTree]);
954
+
955
+ const handleDrop = useCallback(
956
+ (e: React.DragEvent) => {
957
+ e.preventDefault();
958
+ setDragOver(false);
959
+ // Only handle external file/folder drops at the root level.
960
+ if (e.dataTransfer.getData(DRAG_MIME)) return;
961
+ const entries = e.dataTransfer.items ? snapshotEntries(e.dataTransfer.items) : [];
962
+ if (entries.length > 0) {
963
+ dispatchUpload({ kind: 'items', entries }, '');
964
+ return;
965
+ }
966
+ const files = Array.from(e.dataTransfer.files);
967
+ if (files.length > 0) dispatchUpload({ kind: 'files', files }, '');
968
+ },
969
+ [dispatchUpload],
970
+ );
971
+
972
+ return (
973
+ <>
974
+ <aside
975
+ className={`h-full w-full min-w-0 flex flex-col bg-white overflow-hidden ${
976
+ dragOver ? 'ring-2 ring-inset ring-bevel/40' : ''
977
+ }`}
978
+ onDrop={handleDrop}
979
+ onDragOver={(e) => {
980
+ e.preventDefault();
981
+ setDragOver(true);
982
+ }}
983
+ onDragLeave={(e) => {
984
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
985
+ setDragOver(false);
986
+ }}
987
+ >
988
+ {uploadError && (
989
+ <div
990
+ role="alert"
991
+ className="flex items-start gap-1 px-2 py-1 text-xs text-red-700 bg-red-50 border-b border-red-200 shrink-0"
992
+ >
993
+ <span className="flex-1 truncate" title={uploadError.reason}>
994
+ Couldn't add {uploadError.filename}: {uploadError.reason}
995
+ </span>
996
+ <button
997
+ type="button"
998
+ onClick={clearUploadError}
999
+ className="p-0.5 rounded hover:bg-red-100 text-red-600 hover:text-red-800 shrink-0"
1000
+ title="Dismiss"
1001
+ aria-label="Dismiss upload error"
1002
+ >
1003
+ <X size={12} />
1004
+ </button>
1005
+ </div>
1006
+ )}
1007
+ <PinnedContext.Provider value={pinnedController}>
1008
+ <ManageAccessContext.Provider value={setAccessTarget}>
1009
+ <div className="flex-1 overflow-y-auto py-1 min-h-0">
1010
+ <div className="px-3 pt-2 pb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">
1011
+ Pinned
1012
+ </div>
1013
+ {pinnedEntries.map((e) => (
1014
+ <FileTreeNode key={`pin:${e.relativePath}`} entry={e} depth={0} collapseChildren />
1015
+ ))}
1016
+ {explorerItems.map(({ id, Component }) => (
1017
+ <Component key={id} tree={mergedTree} />
1018
+ ))}
1019
+ <div className="mx-3 my-2 border-t border-slate-100" />
1020
+ {!mergedTree ? (
1021
+ <div className="px-3 py-4 text-xs text-slate-600">Loading...</div>
1022
+ ) : sections ? (
1023
+ <>
1024
+ {sections.knowledge && (
1025
+ <FileTreeNode entry={sections.knowledge} depth={0} accent collapseChildren />
1026
+ )}
1027
+ {sections.data && (
1028
+ <FileTreeNode entry={sections.data} depth={0} accent collapseChildren />
1029
+ )}
1030
+ {sections.agents && (
1031
+ <FileTreeNode entry={sections.agents} depth={0} accent collapseChildren />
1032
+ )}
1033
+ {sections.pipelines && (
1034
+ <FileTreeNode entry={sections.pipelines} depth={0} accent collapseChildren />
1035
+ )}
1036
+ {sections.skills && (
1037
+ <FileTreeNode entry={sections.skills} depth={0} accent collapseChildren />
1038
+ )}
1039
+ {sections.tools && (
1040
+ <FileTreeNode entry={sections.tools} depth={0} accent collapseChildren />
1041
+ )}
1042
+ {sections.looseFiles.length > 0 && (
1043
+ <>
1044
+ <div className="mx-3 my-2 border-t border-slate-100" />
1045
+ {sections.looseFiles.map((c) => (
1046
+ <FileTreeNode key={c.relativePath} entry={c} depth={0} />
1047
+ ))}
1048
+ </>
1049
+ )}
1050
+ </>
1051
+ ) : (
1052
+ <FileTreeNode entry={mergedTree} depth={0} />
1053
+ )}
1054
+ </div>
1055
+ </ManageAccessContext.Provider>
1056
+ </PinnedContext.Provider>
1057
+ <PullRequestsForMe />
1058
+ </aside>
1059
+ {accessTarget && (
1060
+ <ManageAccessDialog
1061
+ key={accessTarget.relativePath}
1062
+ entry={accessTarget}
1063
+ onClose={() => setAccessTarget(null)}
1064
+ />
1065
+ )}
1066
+ </>
1067
+ );
1068
+ }