@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,392 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { useParams, useNavigate, useLocation } from 'react-router-dom';
3
+ import { useWorkspace } from '../state/workspace.context';
4
+ import { WorkspaceApiError } from '../services/workspace.api';
5
+ import { useGit } from '../../git/state/git.context';
6
+ import { readPersistedTabs } from '../utils/tab-persistence';
7
+ import {
8
+ NODE_ID_LINK_RE,
9
+ kbNodeUrl,
10
+ fetchNodeWorkspacePath,
11
+ fetchNodeId,
12
+ } from '../routing/kb-routes';
13
+ import { FileViewer } from './FileViewer';
14
+
15
+ type SyncError =
16
+ | { kind: 'dirty'; current: string; target: string; dirtyFilenames: string[] }
17
+ | { kind: 'file-missing'; path: string }
18
+ | { kind: 'file-denied'; path: string }
19
+ | { kind: 'file-load-failed'; path: string; message: string }
20
+ | null;
21
+
22
+ export function FileRoute() {
23
+ const params = useParams<{ branch: string; '*': string }>();
24
+ const navigate = useNavigate();
25
+ const location = useLocation();
26
+ const branchFromUrl = params.branch ? decodeURIComponent(params.branch) : '';
27
+ // The trailing URL segment is either a node id (`/workspace/<branch>/<id>` —
28
+ // the canonical node URL) or a file path (`/workspace/<branch>/<path>`). The id
29
+ // grammar (lowercase, no slash/dot) is disjoint from a real workspace path, so
30
+ // we can tell them apart up front. An id segment is resolved to its file path
31
+ // below before driving the path-keyed tab system; a path segment that turns out
32
+ // to be a node is canonicalized to its id URL (the redirect effect).
33
+ const segment = params['*'] ?? '';
34
+ const segmentIsId = NODE_ID_LINK_RE.test(segment);
35
+
36
+ const workspace = useWorkspace();
37
+ const git = useGit();
38
+ const [error, setError] = useState<SyncError>(null);
39
+ // True while a manual Retry is re-fetching, so the button can disable itself
40
+ // and avoid stacking concurrent reads on a double-click.
41
+ const [retrying, setRetrying] = useState(false);
42
+ // Resolution of an id segment → its file path. `seg`+`branch` tag which segment
43
+ // *and branch* the result is for so a stale async result — or a path resolved on
44
+ // the previous branch after a branch switch keeps the same id segment — is
45
+ // ignored; `path: null` means the id resolved to no readable node (a dangling
46
+ // id, or a bare token that's actually a plain file — we then fall back to
47
+ // loading the segment as a literal path).
48
+ const [idResolved, setIdResolved] = useState<
49
+ { seg: string; branch: string; path: string | null } | null
50
+ >(null);
51
+
52
+ const currentBranch = git.status?.branch ?? null;
53
+ // In-memory edits the user typed into the renderer but hasn't saved yet,
54
+ // computed across ALL open tabs. Without this, switching branches could
55
+ // discard typed-but-unsaved bytes silently in any background tab.
56
+ const hasUnsavedEdits = workspace.hasUnsavedFileChanges;
57
+
58
+ // (workspaceId, branch) pair we've successfully hydrated tabs for. Reset to
59
+ // null on branch switch so re-hydration fires for the new branch.
60
+ const lastHydratedKeyRef = useRef<string | null>(null);
61
+
62
+ const {
63
+ workspaceId,
64
+ openFilePath,
65
+ addTab,
66
+ hydrateTabs,
67
+ setPersistenceBranch,
68
+ dirtyTabFilenames,
69
+ } = workspace;
70
+
71
+ // The file path the tab system actually loads. For a path segment it's the
72
+ // segment verbatim. For an id segment it's the resolved file path — empty
73
+ // while the async resolve is in flight (so we don't briefly load the id token
74
+ // as a path), falling back to the literal segment if the id resolved to no
75
+ // node (the bare-token-is-really-a-file case).
76
+ const pathFromUrl = segmentIsId
77
+ ? idResolved && idResolved.seg === segment && idResolved.branch === branchFromUrl
78
+ ? idResolved.path ?? segment
79
+ : ''
80
+ : segment;
81
+
82
+ // ── Resolve an id segment → its file path ────────────────────────────────
83
+ useEffect(() => {
84
+ if (!segmentIsId) {
85
+ setIdResolved(null);
86
+ return;
87
+ }
88
+ if (!branchFromUrl) return;
89
+ let cancelled = false;
90
+ (async () => {
91
+ const path = await fetchNodeWorkspacePath(branchFromUrl, segment);
92
+ if (!cancelled) setIdResolved({ seg: segment, branch: branchFromUrl, path });
93
+ })();
94
+ return () => {
95
+ cancelled = true;
96
+ };
97
+ }, [segmentIsId, segment, branchFromUrl]);
98
+
99
+ // ── Canonicalize a path URL → the node's id URL ──────────────────────────
100
+ // Once the file is the active tab, look up its node id and replace the path
101
+ // URL with `/workspace/<branch>/<id>`. Non-node files (no id) stay path-based.
102
+ // Guarded by `segmentIsId` so an already-canonical id URL no-ops and this can't
103
+ // ping-pong; gated on `openFilePath === segment` so the subsequent id→path
104
+ // load reuses the already-open tab instead of racing a second fetch.
105
+ useEffect(() => {
106
+ if (segmentIsId || !segment || !branchFromUrl) return;
107
+ if (openFilePath !== segment) return;
108
+ let cancelled = false;
109
+ (async () => {
110
+ const nodeId = await fetchNodeId(branchFromUrl, segment);
111
+ if (!cancelled && nodeId) {
112
+ navigate(kbNodeUrl(branchFromUrl, nodeId) + location.hash, { replace: true });
113
+ }
114
+ })();
115
+ return () => {
116
+ cancelled = true;
117
+ };
118
+ }, [segmentIsId, segment, branchFromUrl, openFilePath, location.hash, navigate]);
119
+
120
+ // ── Branch sync + hydrate + URL → state (forward direction) ──────────────
121
+
122
+ useEffect(() => {
123
+ if (!workspaceId) return;
124
+ if (!branchFromUrl) return;
125
+
126
+ let cancelled = false;
127
+ const branchKnown = currentBranch !== null;
128
+ const branchMatches = branchKnown && currentBranch === branchFromUrl;
129
+
130
+ (async () => {
131
+ // 1) URL points at a different branch than the workspace currently
132
+ // backing this route. Under the per-branch workspace model
133
+ // (`workspaces/<encodeURIComponent(branch)>/`), the "switch" is
134
+ // purely a workspace re-bootstrap to the new branch's clone — no
135
+ // git checkout, no server round-trip beyond cloning if needed.
136
+ // Setting `persistenceBranch` is what drives that bootstrap (see
137
+ // `useWorkspaceState`); when it resolves, `workspaceId` changes,
138
+ // `useGitState` re-fetches status against the new workspace, and
139
+ // this effect re-runs with `branchMatches === true` to proceed to
140
+ // the hydrate step.
141
+ //
142
+ // The ONLY gate is in-memory tab dirtiness — typed-but-not-saved
143
+ // bytes in an open tab haven't reached the lock-release commit
144
+ // yet, and re-bootstrapping would discard them. Git working-tree
145
+ // state is NOT a gate here: per the save=share invariant the
146
+ // working tree is never dirty, and even if a bug leaves it dirty
147
+ // the user is moving to a different on-disk workspace anyway.
148
+ if (branchKnown && !branchMatches) {
149
+ if (hasUnsavedEdits) {
150
+ setError({
151
+ kind: 'dirty',
152
+ current: currentBranch,
153
+ target: branchFromUrl,
154
+ dirtyFilenames: dirtyTabFilenames,
155
+ });
156
+ return;
157
+ }
158
+ setError(null);
159
+ setPersistenceBranch(branchFromUrl);
160
+ // Bail out and wait for the bootstrap to update workspaceId +
161
+ // currentBranch. The hydration block below keys on
162
+ // `(workspaceId, branch)` so it won't fire until both reflect the
163
+ // new branch.
164
+ return;
165
+ }
166
+
167
+ // 2) Hydrate tabs once per (workspaceId, branch) pair. This handles
168
+ // both the persisted state and the URL deeplink in one pass — the URL
169
+ // path (if any) is appended to the persisted paths and used as the
170
+ // requested active path.
171
+ const hydrationKey = `${workspaceId}.${branchFromUrl}`;
172
+ if (lastHydratedKeyRef.current !== hydrationKey) {
173
+ const persisted = readPersistedTabs(workspaceId, branchFromUrl);
174
+ const paths = persisted.paths.slice();
175
+ if (pathFromUrl && !paths.includes(pathFromUrl)) {
176
+ paths.push(pathFromUrl);
177
+ }
178
+ const activePath = pathFromUrl || persisted.activePath;
179
+ setPersistenceBranch(branchFromUrl);
180
+ try {
181
+ const { dropped, denied } = await hydrateTabs(paths, activePath);
182
+ if (cancelled) return;
183
+ lastHydratedKeyRef.current = hydrationKey;
184
+ // If the URL deeplinked to a path that 404'd or 403'd, say why
185
+ // nothing is showing. Persisted (non-deeplinked) tabs that fell in
186
+ // either bucket were silently auto-closed by hydrateTabs.
187
+ if (pathFromUrl && denied.includes(pathFromUrl)) {
188
+ setError({ kind: 'file-denied', path: pathFromUrl });
189
+ } else if (pathFromUrl && dropped.includes(pathFromUrl)) {
190
+ setError({ kind: 'file-missing', path: pathFromUrl });
191
+ } else {
192
+ setError(null);
193
+ }
194
+ } catch (err) {
195
+ if (!cancelled) {
196
+ const message = err instanceof Error ? err.message : 'Unknown error';
197
+ setError({ kind: 'file-load-failed', path: pathFromUrl, message });
198
+ }
199
+ }
200
+ return;
201
+ }
202
+
203
+ // 3) URL → state delta (after hydrate; fires when the user navigates to
204
+ // a different file within the same branch).
205
+ if (pathFromUrl) {
206
+ if (openFilePath !== pathFromUrl) {
207
+ try {
208
+ await addTab(pathFromUrl);
209
+ if (!cancelled) setError(null);
210
+ } catch (err) {
211
+ if (cancelled) return;
212
+ if (err instanceof WorkspaceApiError && err.status === 404) {
213
+ setError({ kind: 'file-missing', path: pathFromUrl });
214
+ } else if (err instanceof WorkspaceApiError && err.status === 403) {
215
+ setError({ kind: 'file-denied', path: pathFromUrl });
216
+ } else {
217
+ const message = err instanceof Error ? err.message : 'Unknown error';
218
+ setError({ kind: 'file-load-failed', path: pathFromUrl, message });
219
+ }
220
+ }
221
+ } else if (!cancelled) {
222
+ setError(null);
223
+ }
224
+ } else if (!cancelled) {
225
+ // URL with no path = "no active tab"; tabs in the strip stay open.
226
+ setError(null);
227
+ }
228
+ })();
229
+
230
+ return () => {
231
+ cancelled = true;
232
+ };
233
+ // Intentionally omitted from the dependency list:
234
+ // - hydrateTabs, addTab, setPersistenceBranch — provided by useWorkspace,
235
+ // wrapped in useCallback in useWorkspaceState so their identities are
236
+ // stable across renders.
237
+ // - dirtyTabFilenames — only read inside the dirty-branch-switch error
238
+ // branch; we want the value at the moment of the URL/branch change,
239
+ // not to re-run this effect every time a tab's dirty flag toggles.
240
+ // The effect's run-conditions are the URL inputs, workspace identity, and
241
+ // the current-branch signal; adding the destructured callbacks would only
242
+ // cause spurious re-runs.
243
+ // eslint-disable-next-line react-hooks/exhaustive-deps
244
+ }, [
245
+ branchFromUrl,
246
+ pathFromUrl,
247
+ workspaceId,
248
+ currentBranch,
249
+ hasUnsavedEdits,
250
+ ]);
251
+
252
+ // Manual retry for a failed load. Re-runs `addTab`, which re-fetches the
253
+ // file AND re-evaluates read access server-side — so a transient failure or a
254
+ // since-granted permission recovers without a full page reload. On success
255
+ // the error clears; on a fresh failure we re-surface the matching error.
256
+ const retryLoad = async (path: string) => {
257
+ if (!path || retrying) return;
258
+ setRetrying(true);
259
+ try {
260
+ await addTab(path);
261
+ setError(null);
262
+ } catch (err) {
263
+ if (err instanceof WorkspaceApiError && err.status === 404) {
264
+ setError({ kind: 'file-missing', path });
265
+ } else if (err instanceof WorkspaceApiError && err.status === 403) {
266
+ setError({ kind: 'file-denied', path });
267
+ } else {
268
+ const message = err instanceof Error ? err.message : 'Unknown error';
269
+ setError({ kind: 'file-load-failed', path, message });
270
+ }
271
+ } finally {
272
+ setRetrying(false);
273
+ }
274
+ };
275
+
276
+ // No state→URL effect. The URL is the single authority for "what's active",
277
+ // and only one direction of sync runs at a time:
278
+ // - User clicks a tab in EditorTabs → useFileNav.openFile(path) → URL changes → URL→state activates
279
+ // - User closes a tab in EditorTabs → workspace.closeTab(tab); EditorTabs explicitly navigates after, using closeTab's returned newActivePath
280
+ // - Tree click in FileExplorer → useFileNav.openFile(path) → URL changes → URL→state activates
281
+ // - URL deeplink / hydrate → URL→state addTab activates
282
+ // A reactive state→URL effect was tried earlier and caused an oscillation:
283
+ // URL change → effect fires with stale activeTab in closure → navigates
284
+ // back to the old path → URL→state catches up state → state→URL fires
285
+ // again with the now-stale OTHER value → ping-pong.
286
+
287
+ if (error?.kind === 'dirty') {
288
+ return (
289
+ <div className="h-full w-full flex items-center justify-center bg-white px-6">
290
+ <div className="max-w-md text-center space-y-3">
291
+ <h2 className="text-slate-900 text-base font-medium">
292
+ Save your changes before opening this link
293
+ </h2>
294
+ <p className="text-slate-600 text-sm">
295
+ This link is on{' '}
296
+ <span className="font-mono text-slate-900">{error.target}</span>, but you have
297
+ unsaved changes on{' '}
298
+ <span className="font-mono text-slate-900">{error.current}</span>. Save the
299
+ files below first (Ctrl/Cmd+S, or click <span className="font-medium">Save</span>{' '}
300
+ in the editor toolbar) — that releases the lock and auto-commits and auto-pushes
301
+ your changes — then this link will open.
302
+ </p>
303
+ {error.dirtyFilenames.length > 0 && (
304
+ <div className="text-left bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs text-slate-700">
305
+ <div className="font-medium text-slate-900 mb-1">Unsaved files:</div>
306
+ <ul className="list-disc pl-5 space-y-0.5">
307
+ {error.dirtyFilenames.map((name) => (
308
+ <li key={name} className="font-mono">{name}</li>
309
+ ))}
310
+ </ul>
311
+ </div>
312
+ )}
313
+ </div>
314
+ </div>
315
+ );
316
+ }
317
+
318
+ if (error?.kind === 'file-missing') {
319
+ return (
320
+ <div className="h-full w-full flex items-center justify-center bg-white px-6">
321
+ <div className="max-w-md text-center space-y-3">
322
+ <h2 className="text-slate-900 text-base font-medium">File not found</h2>
323
+ <p className="text-slate-600 text-sm">
324
+ <span className="font-mono text-slate-900">{error.path}</span> doesn't exist on{' '}
325
+ <span className="font-mono text-slate-900">{branchFromUrl}</span>.
326
+ </p>
327
+ <p className="text-slate-600 text-xs">
328
+ It may have been renamed or removed, or this link may be from a different branch.
329
+ </p>
330
+ </div>
331
+ </div>
332
+ );
333
+ }
334
+
335
+ if (error?.kind === 'file-denied') {
336
+ const denyName = error.path.slice(error.path.lastIndexOf('/') + 1);
337
+ return (
338
+ <div className="h-full w-full flex items-center justify-center bg-white px-6">
339
+ <div role="alert" className="max-w-md text-center space-y-3">
340
+ <h2 className="text-slate-900 text-base font-medium">
341
+ You don&apos;t have access to this file
342
+ </h2>
343
+ <p className="text-slate-600 text-sm">
344
+ <span className="font-mono text-slate-900">{denyName}</span> is restricted. Ask an
345
+ owner to grant you read access.
346
+ </p>
347
+ {/* Retry re-runs addTab, which re-checks access server-side — a user
348
+ who was just granted access recovers in place. No tab exists for
349
+ the denied file (denied tabs auto-close). */}
350
+ <button
351
+ type="button"
352
+ onClick={() => retryLoad(error.path)}
353
+ disabled={retrying}
354
+ className="inline-flex items-center justify-center rounded border border-slate-300 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
355
+ >
356
+ {retrying ? 'Retrying…' : 'Retry'}
357
+ </button>
358
+ </div>
359
+ </div>
360
+ );
361
+ }
362
+
363
+ if (error?.kind === 'file-load-failed') {
364
+ return (
365
+ <div className="h-full w-full flex items-center justify-center bg-white px-6">
366
+ <div className="max-w-md text-center space-y-3">
367
+ <h2 className="text-slate-900 text-base font-medium">Couldn't load this file</h2>
368
+ <p className="text-slate-600 text-sm">
369
+ Something went wrong reading{' '}
370
+ <span className="font-mono text-slate-900">{error.path}</span>.
371
+ </p>
372
+ <p className="text-slate-600 text-xs font-mono">{error.message}</p>
373
+ {/* Only offer Retry when we have a concrete file to re-fetch. A hydrate
374
+ failure with no deeplinked path leaves `error.path` empty, and
375
+ `retryLoad('')` is a no-op — so the button would be dead. */}
376
+ {error.path && (
377
+ <button
378
+ type="button"
379
+ onClick={() => retryLoad(error.path)}
380
+ disabled={retrying}
381
+ className="inline-flex items-center justify-center rounded border border-slate-300 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
382
+ >
383
+ {retrying ? 'Retrying…' : 'Retry'}
384
+ </button>
385
+ )}
386
+ </div>
387
+ </div>
388
+ );
389
+ }
390
+
391
+ return <FileViewer />;
392
+ }