@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.
- package/LICENSE +202 -0
- package/package.json +70 -0
- package/src/core/CoreAppShell.tsx +444 -0
- package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
- package/src/core/events.ts +29 -0
- package/src/core/registry.ts +336 -0
- package/src/css-side-effect-imports.d.ts +7 -0
- package/src/html-extensions.ts +12 -0
- package/src/index.css +49 -0
- package/src/index.ts +23 -0
- package/src/lib/api.ts +57 -0
- package/src/lib/utils.ts +138 -0
- package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
- package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
- package/src/modules/access/api.ts +205 -0
- package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
- package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
- package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
- package/src/modules/access/hooks/useFileAccess.ts +151 -0
- package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
- package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
- package/src/modules/admin/services/admin.api.ts +92 -0
- package/src/modules/admin/services/roles.api.ts +136 -0
- package/src/modules/admin/state/admin.context.tsx +223 -0
- package/src/modules/auth/components/LoginScreen.tsx +135 -0
- package/src/modules/auth/hooks/useAuthState.ts +59 -0
- package/src/modules/auth/services/auth.api.ts +24 -0
- package/src/modules/auth/services/microsoft-oauth.ts +57 -0
- package/src/modules/auth/state/auth.context.ts +18 -0
- package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
- package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
- package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
- package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
- package/src/modules/git/__tests__/git.api.test.ts +113 -0
- package/src/modules/git/__tests__/pr.api.test.ts +44 -0
- package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
- package/src/modules/git/components/BranchSwitcher.tsx +527 -0
- package/src/modules/git/components/DiffView.tsx +30 -0
- package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
- package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
- package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
- package/src/modules/git/components/PullNeededBanner.tsx +204 -0
- package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
- package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
- package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
- package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
- package/src/modules/git/hooks/useGitState.ts +335 -0
- package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
- package/src/modules/git/services/error-messages.ts +257 -0
- package/src/modules/git/services/git.api.ts +163 -0
- package/src/modules/git/services/pr-prompts.ts +159 -0
- package/src/modules/git/services/pr.api.ts +39 -0
- package/src/modules/git/state/auto-update.context.ts +21 -0
- package/src/modules/git/state/git.context.ts +82 -0
- package/src/modules/layout/components/AppLayout.tsx +40 -0
- package/src/modules/layout/components/DemoBanner.tsx +57 -0
- package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
- package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
- package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
- package/src/modules/layout/components/SlideOverlay.tsx +224 -0
- package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
- package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
- package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
- package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
- package/src/modules/layout/state/layout.context.ts +46 -0
- package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
- package/src/modules/library/__tests__/diff.test.ts +62 -0
- package/src/modules/library/__tests__/loadout.test.tsx +72 -0
- package/src/modules/library/__tests__/status.test.ts +117 -0
- package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
- package/src/modules/library/components/CompareView.tsx +357 -0
- package/src/modules/library/components/DetailDialog.tsx +566 -0
- package/src/modules/library/components/GearIcon.tsx +12 -0
- package/src/modules/library/components/LibraryCard.tsx +132 -0
- package/src/modules/library/components/LibraryPage.tsx +254 -0
- package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
- package/src/modules/library/components/StatusGem.tsx +21 -0
- package/src/modules/library/components/SuggestChange.tsx +171 -0
- package/src/modules/library/components/particles.ts +50 -0
- package/src/modules/library/hooks/useLibraryData.ts +119 -0
- package/src/modules/library/hooks/useSkillDetail.ts +74 -0
- package/src/modules/library/library.css +320 -0
- package/src/modules/library/services/library.api.ts +164 -0
- package/src/modules/library/state/loadout.tsx +129 -0
- package/src/modules/library/state/toast.tsx +42 -0
- package/src/modules/library/utils/diff.ts +102 -0
- package/src/modules/library/utils/status.ts +116 -0
- package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
- package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
- package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
- package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
- package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
- package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
- package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
- package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
- package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
- package/src/modules/pr/components/PrCancelButton.tsx +99 -0
- package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
- package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
- package/src/modules/pr/components/PrCommentThread.tsx +168 -0
- package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
- package/src/modules/pr/components/PrDiffPane.tsx +425 -0
- package/src/modules/pr/components/PrFileRow.tsx +164 -0
- package/src/modules/pr/components/PrFilesList.tsx +53 -0
- package/src/modules/pr/components/PrHeader.tsx +45 -0
- package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
- package/src/modules/pr/components/PrMergeButton.tsx +268 -0
- package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
- package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
- package/src/modules/pr/components/PrViewer.tsx +364 -0
- package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
- package/src/modules/pr/services/pr-approvals.api.ts +31 -0
- package/src/modules/pr/services/pr-cancel.api.ts +19 -0
- package/src/modules/pr/services/pr-comments.api.ts +45 -0
- package/src/modules/pr/services/pr-detail.api.ts +17 -0
- package/src/modules/pr/services/pr-merge.api.ts +53 -0
- package/src/modules/pr/services/pr-open.api.ts +30 -0
- package/src/modules/pr/state/pr-viewer.context.ts +34 -0
- package/src/modules/pr/utils/bucketize-comments.ts +55 -0
- package/src/modules/pr/utils/parsePatch.ts +57 -0
- package/src/modules/review/__tests__/review.api.test.ts +121 -0
- package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
- package/src/modules/review/components/DiffViewer.tsx +78 -0
- package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
- package/src/modules/review/components/ReviewFileRow.tsx +114 -0
- package/src/modules/review/components/ReviewPanel.tsx +260 -0
- package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
- package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
- package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
- package/src/modules/review/hooks/useReviewState.ts +256 -0
- package/src/modules/review/services/review.api.ts +72 -0
- package/src/modules/review/state/ReviewProvider.tsx +28 -0
- package/src/modules/review/state/review.context.ts +29 -0
- package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
- package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
- package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
- package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
- package/src/modules/secrets-vault/services/connect.api.ts +113 -0
- package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
- package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
- package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
- package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
- package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
- package/src/modules/toolbar/components/Toolbar.tsx +123 -0
- package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
- package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
- package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
- package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
- package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
- package/src/modules/workflow/hooks/useFileLock.ts +430 -0
- package/src/modules/workflow/services/lock.api.ts +139 -0
- package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
- package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
- package/src/modules/workflow/state/event-bus.context.ts +75 -0
- package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
- package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
- package/src/modules/workspace/components/EditorTabs.tsx +384 -0
- package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
- package/src/modules/workspace/components/FileRoute.tsx +392 -0
- package/src/modules/workspace/components/FileViewer.tsx +906 -0
- package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
- package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
- package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
- package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
- package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
- package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
- package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
- package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
- package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
- package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
- package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
- package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
- package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
- package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
- package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
- package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
- package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
- package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
- package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
- package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
- package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
- package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
- package/src/modules/workspace/components/renderers/index.ts +39 -0
- package/src/modules/workspace/components/renderers/types.ts +27 -0
- package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
- package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
- package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
- package/src/modules/workspace/routing/kb-routes.ts +266 -0
- package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
- package/src/modules/workspace/services/workspace.api.ts +185 -0
- package/src/modules/workspace/state/workspace.context.ts +235 -0
- package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
- package/src/modules/workspace/utils/diff.ts +53 -0
- package/src/modules/workspace/utils/fileTree.ts +179 -0
- package/src/modules/workspace/utils/frontmatter.ts +80 -0
- package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
- package/src/modules/workspace/utils/tab-persistence.ts +23 -0
- package/src/shared/components/Dialog.tsx +198 -0
- package/src/shared/components/PageShell.tsx +51 -0
- package/src/shared/components/useModalLayer.ts +35 -0
- package/src/shared/markdown/Markdown.tsx +62 -0
- package/src/test-setup.ts +59 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
|
2
|
+
import type { WorkflowEvent } from '@bevel-software/platform-shared';
|
|
3
|
+
import { EventBusContext, type EventBusContextValue, type EventHandler } from './event-bus.context';
|
|
4
|
+
|
|
5
|
+
/** Storage key for the per-tab sessionId. SessionStorage so it survives a
|
|
6
|
+
* page refresh (allowing Last-Event-ID replay across the gap) but doesn't
|
|
7
|
+
* leak across browser tabs (each tab has its own connection). */
|
|
8
|
+
// Exported so `authFetch` can stamp the per-tab session id onto outgoing
|
|
9
|
+
// requests as an `x-bevel-session` header. Route handlers that emit
|
|
10
|
+
// originating-session-scoped events include this id so the originating tab
|
|
11
|
+
// can self-skip and only OTHER tabs of the same user act on the event.
|
|
12
|
+
export const SESSION_ID_KEY = 'bevel-event-bus-session-id';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Provider that owns the single EventSource connection for this browser
|
|
16
|
+
* tab and demultiplexes incoming events to registered handlers.
|
|
17
|
+
*
|
|
18
|
+
* **Lifecycle.** One EventSource is opened on mount and closed on unmount
|
|
19
|
+
* — that's the entire lifetime. Branch switches, route changes, chat
|
|
20
|
+
* turns, and reconnect storms all happen *inside* this connection. We
|
|
21
|
+
* never re-open per workspace; the backend's focus endpoint is what
|
|
22
|
+
* changes which workspace events we receive.
|
|
23
|
+
*
|
|
24
|
+
* **Reconnect.** The browser's EventSource auto-reconnects with a default
|
|
25
|
+
* ~3 s backoff. We don't do anything to help it — but we DO re-POST the
|
|
26
|
+
* current focus on every `open` event so the server's session map picks
|
|
27
|
+
* up the desired filter again after a transient drop.
|
|
28
|
+
*
|
|
29
|
+
* **Auth.** EventSource can't set headers, so authentication happens via
|
|
30
|
+
* the `bevel_token` cookie set at login. `withCredentials: true` makes
|
|
31
|
+
* the browser include it. The cookie is HttpOnly + SameSite=Lax, so the
|
|
32
|
+
* frontend can't read it directly — that's fine, the server reads it.
|
|
33
|
+
*/
|
|
34
|
+
export function EventBusProvider({ children }: { children: ReactNode }) {
|
|
35
|
+
// Per-tab session id. Generated once and persisted in sessionStorage so
|
|
36
|
+
// a refresh keeps the same id (which lets the server's ring buffer
|
|
37
|
+
// replay anything missed in the gap via Last-Event-ID).
|
|
38
|
+
const sessionId = useMemo(() => {
|
|
39
|
+
if (typeof window === 'undefined') return ''; // SSR / test fallback
|
|
40
|
+
let id = window.sessionStorage.getItem(SESSION_ID_KEY);
|
|
41
|
+
if (!id) {
|
|
42
|
+
id = (window.crypto?.randomUUID?.() ?? `s-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
43
|
+
window.sessionStorage.setItem(SESSION_ID_KEY, id);
|
|
44
|
+
}
|
|
45
|
+
return id;
|
|
46
|
+
}, []);
|
|
47
|
+
|
|
48
|
+
// Subscriber registry. Keyed by event kind so dispatch is O(handlers
|
|
49
|
+
// for THIS kind) rather than scanning every subscriber on every event.
|
|
50
|
+
// `Set` so duplicate registrations don't double-fire.
|
|
51
|
+
const subscribersRef = useRef<Map<string, Set<EventHandler<WorkflowEvent['kind']>>>>(new Map());
|
|
52
|
+
|
|
53
|
+
// **Two focus refs, not one** — the "synced" focus (what the server
|
|
54
|
+
// confirmed) and the "desired" focus (what the client wants).
|
|
55
|
+
//
|
|
56
|
+
// Why this matters: without the split, a failed POST left `focusRef`
|
|
57
|
+
// advanced to the new value, so the next `setFocus(sameValue)` would
|
|
58
|
+
// short-circuit on equality and never retry — the server stays stuck
|
|
59
|
+
// on the OLD focus, and the client thinks it's on the new one. With
|
|
60
|
+
// the split, `desiredFocusRef` is what `setFocus` updates and what
|
|
61
|
+
// the post-attempt reads; `focusRef` only advances on a 2xx, so a
|
|
62
|
+
// retry is possible whenever desired ≠ synced.
|
|
63
|
+
const focusRef = useRef<string | null>(null);
|
|
64
|
+
const desiredFocusRef = useRef<string | null>(null);
|
|
65
|
+
const [focusVersion, setFocusVersion] = useState(0);
|
|
66
|
+
|
|
67
|
+
const dispatch = useCallback((event: WorkflowEvent) => {
|
|
68
|
+
// Heartbeats are connection-keepalives only — they shouldn't reach
|
|
69
|
+
// app code. Same for resync (we'd want to refetch state from
|
|
70
|
+
// scratch, but that's left to consumers that subscribe to it
|
|
71
|
+
// explicitly).
|
|
72
|
+
if (event.kind === 'heartbeat') return;
|
|
73
|
+
const handlers = subscribersRef.current.get(event.kind);
|
|
74
|
+
// One-line dispatch log: which event arrived, how many local
|
|
75
|
+
// handlers it'll fan out to, and the most useful identifying
|
|
76
|
+
// fields. Helps catch "event arrived but no handler was
|
|
77
|
+
// subscribed" symptoms quickly in DevTools.
|
|
78
|
+
const path = 'path' in event && event.path ? event.path : undefined;
|
|
79
|
+
const sha = 'newSha' in event ? event.newSha : undefined;
|
|
80
|
+
console.debug('[event-bus] receive', {
|
|
81
|
+
kind: event.kind,
|
|
82
|
+
id: 'id' in event ? event.id : undefined,
|
|
83
|
+
handlerCount: handlers?.size ?? 0,
|
|
84
|
+
...(path !== undefined ? { path } : {}),
|
|
85
|
+
...(sha !== undefined ? { newSha: sha } : {}),
|
|
86
|
+
});
|
|
87
|
+
if (!handlers) return;
|
|
88
|
+
for (const handler of handlers) {
|
|
89
|
+
try {
|
|
90
|
+
handler(event as never);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
console.warn(`[event-bus] handler for ${event.kind} threw:`, err);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}, []);
|
|
96
|
+
|
|
97
|
+
const subscribe = useCallback<EventBusContextValue['subscribe']>((kind, handler) => {
|
|
98
|
+
let bucket = subscribersRef.current.get(kind);
|
|
99
|
+
if (!bucket) {
|
|
100
|
+
bucket = new Set();
|
|
101
|
+
subscribersRef.current.set(kind, bucket);
|
|
102
|
+
}
|
|
103
|
+
bucket.add(handler as unknown as EventHandler<WorkflowEvent['kind']>);
|
|
104
|
+
return () => {
|
|
105
|
+
bucket?.delete(handler as unknown as EventHandler<WorkflowEvent['kind']>);
|
|
106
|
+
if (bucket && bucket.size === 0) {
|
|
107
|
+
subscribersRef.current.delete(kind);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}, []);
|
|
111
|
+
|
|
112
|
+
const postFocus = useCallback(async (workspaceId: string | null) => {
|
|
113
|
+
if (!sessionId) return;
|
|
114
|
+
if (workspaceId === null) {
|
|
115
|
+
// No "clear focus" endpoint server-side; setting null is a frontend
|
|
116
|
+
// signal that we don't currently want workspace events. The next
|
|
117
|
+
// setFocus(workspaceId) re-syncs the server. This is fine because
|
|
118
|
+
// an idle focus simply means no workspace-scoped events arrive.
|
|
119
|
+
focusRef.current = null;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const response = await fetch(`/api/events/${encodeURIComponent(sessionId)}/focus`, {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
credentials: 'include',
|
|
126
|
+
headers: { 'Content-Type': 'application/json' },
|
|
127
|
+
body: JSON.stringify({ workspaceId }),
|
|
128
|
+
});
|
|
129
|
+
if (!response.ok) {
|
|
130
|
+
// Server rejected the focus update (most likely 404 — session
|
|
131
|
+
// expired or was evicted, e.g. after a backend restart). The
|
|
132
|
+
// SSE connection's `open` handler re-POSTs the latest desired
|
|
133
|
+
// focus on every reconnect, so a transient rejection corrects
|
|
134
|
+
// itself the next time the connection cycles.
|
|
135
|
+
let detail = '';
|
|
136
|
+
try { detail = await response.text(); } catch { /* ignore */ }
|
|
137
|
+
console.warn(
|
|
138
|
+
`[event-bus] focus POST rejected: ${response.status}`,
|
|
139
|
+
detail || '(no body)',
|
|
140
|
+
);
|
|
141
|
+
// Leave `focusRef` (synced) UN-advanced so the next
|
|
142
|
+
// `setFocus(sameWorkspaceId)` doesn't short-circuit on
|
|
143
|
+
// equality — the desired focus is still unsynced and we want
|
|
144
|
+
// to retry.
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
// Server accepted: synced focus catches up to desired.
|
|
148
|
+
focusRef.current = workspaceId;
|
|
149
|
+
} catch (err) {
|
|
150
|
+
// Network blip — `focusRef` stays at its last successfully-synced
|
|
151
|
+
// value, so a follow-up setFocus to the same workspaceId still
|
|
152
|
+
// detects desync and retries.
|
|
153
|
+
console.warn('[event-bus] focus POST failed:', err);
|
|
154
|
+
}
|
|
155
|
+
}, [sessionId]);
|
|
156
|
+
|
|
157
|
+
const setFocus = useCallback<EventBusContextValue['setFocus']>((workspaceId) => {
|
|
158
|
+
// Compare against SYNCED focus, not desired — that way a retry
|
|
159
|
+
// after a previous POST failure isn't short-circuited.
|
|
160
|
+
if (focusRef.current === workspaceId) {
|
|
161
|
+
desiredFocusRef.current = workspaceId;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
console.debug('[event-bus] setFocus', { from: focusRef.current, to: workspaceId });
|
|
165
|
+
desiredFocusRef.current = workspaceId;
|
|
166
|
+
setFocusVersion((v) => v + 1);
|
|
167
|
+
}, []);
|
|
168
|
+
|
|
169
|
+
// EventSource lifecycle. One connection per tab, opened once on mount,
|
|
170
|
+
// closed on unmount. The browser handles reconnect with its built-in
|
|
171
|
+
// backoff; we re-POST focus inside the `open` handler so reconnects
|
|
172
|
+
// resynchronise the server's session filter for free.
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
if (!sessionId || typeof EventSource === 'undefined') return;
|
|
175
|
+
const url = `/api/events?session=${encodeURIComponent(sessionId)}`;
|
|
176
|
+
const source = new EventSource(url, { withCredentials: true });
|
|
177
|
+
|
|
178
|
+
const handleOpen = () => {
|
|
179
|
+
console.debug('[event-bus] SSE open', { session: sessionId, desiredFocus: desiredFocusRef.current });
|
|
180
|
+
// Reconnect path: re-POST the DESIRED focus so the new connection
|
|
181
|
+
// catches up to what the client wants — using `desiredFocusRef`
|
|
182
|
+
// (not synced `focusRef`) means a previous POST failure also
|
|
183
|
+
// self-heals on the next open. First-time-open will have desired
|
|
184
|
+
// === null until a consumer (workspace state) calls setFocus.
|
|
185
|
+
if (desiredFocusRef.current !== null) {
|
|
186
|
+
void postFocus(desiredFocusRef.current);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const handleMessage = (e: MessageEvent<string>) => {
|
|
191
|
+
try {
|
|
192
|
+
const event = JSON.parse(e.data) as WorkflowEvent;
|
|
193
|
+
dispatch(event);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
console.warn('[event-bus] failed to parse SSE payload:', err);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const handleError = (e: Event) => {
|
|
200
|
+
// EventSource auto-reconnects; we just log so a misbehaving
|
|
201
|
+
// backend surfaces in the console. Don't close — closing would
|
|
202
|
+
// cancel the auto-reconnect.
|
|
203
|
+
console.warn('[event-bus] connection error (auto-reconnecting):', e);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
source.addEventListener('open', handleOpen);
|
|
207
|
+
source.addEventListener('message', handleMessage);
|
|
208
|
+
source.addEventListener('error', handleError);
|
|
209
|
+
|
|
210
|
+
return () => {
|
|
211
|
+
source.removeEventListener('open', handleOpen);
|
|
212
|
+
source.removeEventListener('message', handleMessage);
|
|
213
|
+
source.removeEventListener('error', handleError);
|
|
214
|
+
source.close();
|
|
215
|
+
};
|
|
216
|
+
// Intentionally re-subscribing only on sessionId / postFocus / dispatch
|
|
217
|
+
// identity changes. Focus updates flow through `postFocus` directly
|
|
218
|
+
// (no reconnect needed); a focus change must never tear the
|
|
219
|
+
// connection down.
|
|
220
|
+
}, [sessionId, dispatch, postFocus]);
|
|
221
|
+
|
|
222
|
+
// Propagate focus changes to the server. Decoupled from the EventSource
|
|
223
|
+
// lifecycle so a focus change doesn't reconnect.
|
|
224
|
+
useEffect(() => {
|
|
225
|
+
if (focusVersion === 0) return;
|
|
226
|
+
void postFocus(desiredFocusRef.current);
|
|
227
|
+
}, [focusVersion, postFocus]);
|
|
228
|
+
|
|
229
|
+
const value = useMemo<EventBusContextValue>(() => ({ subscribe, setFocus }), [subscribe, setFocus]);
|
|
230
|
+
|
|
231
|
+
return <EventBusContext.Provider value={value}>{children}</EventBusContext.Provider>;
|
|
232
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react';
|
|
2
|
+
import type { WorkflowEvent } from '@bevel-software/platform-shared';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Handler signature for an event-bus subscription. The handler runs
|
|
6
|
+
* synchronously inside the React render pass — keep it side-effect-light
|
|
7
|
+
* (state updates, callbacks); long-running work should be deferred via
|
|
8
|
+
* `useEffect` / setState batching.
|
|
9
|
+
*/
|
|
10
|
+
export type EventHandler<K extends WorkflowEvent['kind']> = (
|
|
11
|
+
event: Extract<WorkflowEvent, { kind: K }>,
|
|
12
|
+
) => void;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Public API of the event bus exposed via React context. Two responsibilities:
|
|
16
|
+
*
|
|
17
|
+
* - `subscribe(kind, handler)` — register a typed handler for a single
|
|
18
|
+
* event kind. Returns the unsubscribe fn. Multiple handlers per kind
|
|
19
|
+
* are supported; they all fire in registration order on each event.
|
|
20
|
+
*
|
|
21
|
+
* - `setFocus(workspaceId)` — tell the backend which workspace's
|
|
22
|
+
* broadcast events this session wants. Called by hooks that follow
|
|
23
|
+
* the active branch (typically `useEventBusFocus` driven from
|
|
24
|
+
* `useWorkspaceState`). Setting `null` clears the focus — the session
|
|
25
|
+
* stays alive but receives no workspace-scoped events.
|
|
26
|
+
*
|
|
27
|
+
* The provider owns one EventSource per tab; this interface intentionally
|
|
28
|
+
* doesn't expose connection state — consumers shouldn't care whether the
|
|
29
|
+
* underlying stream is open, reconnecting, or replaying. If a feature
|
|
30
|
+
* needs to know (e.g. a status banner), we'll add it then.
|
|
31
|
+
*/
|
|
32
|
+
export interface EventBusContextValue {
|
|
33
|
+
subscribe<K extends WorkflowEvent['kind']>(kind: K, handler: EventHandler<K>): () => void;
|
|
34
|
+
setFocus(workspaceId: string | null): void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const EventBusContext = createContext<EventBusContextValue | null>(null);
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Read the event-bus context. Returns `null` when used outside the provider
|
|
41
|
+
* — consumers should null-check (or use the typed hooks below which are
|
|
42
|
+
* no-ops in tests that don't mount the provider). Throwing here would
|
|
43
|
+
* force every test of every component to mount the provider, which is
|
|
44
|
+
* worse than the null check at the consumer.
|
|
45
|
+
*/
|
|
46
|
+
export function useEventBus(): EventBusContextValue | null {
|
|
47
|
+
return useContext(EventBusContext);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Decode-once (idempotent on already-decoded input). Used in every SSE
|
|
52
|
+
* handler that compares `event.workspaceId` to a local `workspaceId`
|
|
53
|
+
* prop / state. The two sides arrive in DIFFERENT encodings:
|
|
54
|
+
*
|
|
55
|
+
* - Local state / `workspace.id` is the URL-encoded form
|
|
56
|
+
* (`encodeURIComponent(branch)` → `razvan-radulescu%2Fsc`) because
|
|
57
|
+
* that's what `workspaceIdForBranch` returns and what we put in URLs.
|
|
58
|
+
* - `event.workspaceId` on incoming events is the URL-DECODED form
|
|
59
|
+
* (`razvan-radulescu/sc`) because the backend extracts it via
|
|
60
|
+
* `req.params.id` which Express auto-decodes.
|
|
61
|
+
*
|
|
62
|
+
* Without canonicalisation, every `event.workspaceId !== workspaceId`
|
|
63
|
+
* check silently fails for branches containing a `/` (every feature
|
|
64
|
+
* branch under the `<email-localpart>/<kebab-slug>` convention) — the
|
|
65
|
+
* handler appears subscribed but bails before doing any work, which is
|
|
66
|
+
* exactly what made lock banners / live content refresh look broken
|
|
67
|
+
* on feature branches.
|
|
68
|
+
*/
|
|
69
|
+
export function canonicalizeWorkspaceId(workspaceId: string): string {
|
|
70
|
+
try {
|
|
71
|
+
return decodeURIComponent(workspaceId);
|
|
72
|
+
} catch {
|
|
73
|
+
return workspaceId;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Shared test fixtures for WorkspaceContextValue. Avoids the trap where each
|
|
2
|
+
// test file ad-hocs its own object literal — the moment the interface gains a
|
|
3
|
+
// required field, every one of those literals fails type-checking. Centralise
|
|
4
|
+
// the defaults here so adding `unzipHere`, `bumpFsRevision`, etc. is a
|
|
5
|
+
// one-line edit instead of a sweep.
|
|
6
|
+
|
|
7
|
+
import type { WorkspaceContextValue } from '../state/workspace.context';
|
|
8
|
+
|
|
9
|
+
export function makeWorkspaceFixture(
|
|
10
|
+
overrides: Partial<WorkspaceContextValue> = {},
|
|
11
|
+
): WorkspaceContextValue {
|
|
12
|
+
return {
|
|
13
|
+
workspaceId: 'ws-1',
|
|
14
|
+
kbDirName: 'knowledge-base',
|
|
15
|
+
fileTree: null,
|
|
16
|
+
openTabs: [],
|
|
17
|
+
activeTab: null,
|
|
18
|
+
dirtyTabFilenames: [],
|
|
19
|
+
openFilePath: null,
|
|
20
|
+
openFileContent: null,
|
|
21
|
+
openFileSavedContent: null,
|
|
22
|
+
hasUnsavedFileChanges: false,
|
|
23
|
+
pendingFileContent: null,
|
|
24
|
+
setActiveTabContent: () => {},
|
|
25
|
+
bumpFsRevision: () => {},
|
|
26
|
+
setPersistenceBranch: () => {},
|
|
27
|
+
fsRevision: 0,
|
|
28
|
+
uploadError: null,
|
|
29
|
+
isUploading: false,
|
|
30
|
+
uploadProgress: null,
|
|
31
|
+
pendingUploads: new Map(),
|
|
32
|
+
refreshFileTree: async () => null,
|
|
33
|
+
addTab: async () => true,
|
|
34
|
+
closeTab: async () => ({ closed: true, newActivePath: null }),
|
|
35
|
+
activateTab: () => {},
|
|
36
|
+
reorderTab: () => {},
|
|
37
|
+
closeAllTabs: () => {},
|
|
38
|
+
hydrateTabs: async () => ({ surviving: [], dropped: [], denied: [] }),
|
|
39
|
+
createFile: async () => {},
|
|
40
|
+
createDirectory: async () => {},
|
|
41
|
+
unzipHere: async () => ({ extracted: 0, skipped: [], destination: '' }),
|
|
42
|
+
uploadFiles: async () => {},
|
|
43
|
+
dispatchUpload: async () => {},
|
|
44
|
+
clearUploadError: () => {},
|
|
45
|
+
deleteEntry: async () => {},
|
|
46
|
+
moveEntry: async () => {},
|
|
47
|
+
saveFile: async () => {},
|
|
48
|
+
reloadTabFromDisk: async () => {},
|
|
49
|
+
setPendingContent: () => {},
|
|
50
|
+
acceptPendingContent: async () => {},
|
|
51
|
+
rejectPendingContent: async () => {},
|
|
52
|
+
...overrides,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { renderHook, act, waitFor } from '@testing-library/react';
|
|
3
|
+
|
|
4
|
+
// Mock the workspace API before importing the hook — the hook's top-level import
|
|
5
|
+
// binds to the mocked module.
|
|
6
|
+
vi.mock('../services/workspace.api', () => ({
|
|
7
|
+
getOrCreateWorkspace: vi.fn().mockResolvedValue({
|
|
8
|
+
workspace: { id: 'ws-1' },
|
|
9
|
+
fileTree: { name: '.', relativePath: '.', type: 'directory', children: [] },
|
|
10
|
+
}),
|
|
11
|
+
listFiles: vi.fn().mockResolvedValue({
|
|
12
|
+
name: '.', relativePath: '.', type: 'directory', children: [],
|
|
13
|
+
}),
|
|
14
|
+
readFile: vi.fn().mockResolvedValue(''),
|
|
15
|
+
writeFile: vi.fn().mockResolvedValue(undefined),
|
|
16
|
+
createDirectory: vi.fn().mockResolvedValue(undefined),
|
|
17
|
+
uploadFile: vi.fn().mockResolvedValue(undefined),
|
|
18
|
+
deleteFile: vi.fn().mockResolvedValue(undefined),
|
|
19
|
+
moveEntry: vi.fn().mockResolvedValue(undefined),
|
|
20
|
+
deleteWorkspace: vi.fn().mockResolvedValue(undefined),
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
import { useWorkspaceState } from '../hooks/useWorkspaceState';
|
|
24
|
+
import * as api from '../services/workspace.api';
|
|
25
|
+
|
|
26
|
+
describe('useWorkspaceState fsRevision', () => {
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
vi.clearAllMocks();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
async function mountReady() {
|
|
32
|
+
const { result } = renderHook(() => useWorkspaceState());
|
|
33
|
+
// Wait for the initial getOrCreateWorkspace effect to settle and the workspaceId
|
|
34
|
+
// to populate — mutations early-return without it.
|
|
35
|
+
await waitFor(() => expect(result.current.workspaceId).toBe('ws-1'));
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
it('starts at 0 and does not bump on read-only ops', async () => {
|
|
40
|
+
const result = await mountReady();
|
|
41
|
+
expect(result.current.fsRevision).toBe(0);
|
|
42
|
+
await act(async () => {
|
|
43
|
+
await result.current.refreshFileTree();
|
|
44
|
+
await expect(result.current.addTab('a.md')).resolves.toBe(true);
|
|
45
|
+
});
|
|
46
|
+
expect(result.current.fsRevision).toBe(0);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('bumps on each mutating call', async () => {
|
|
50
|
+
const result = await mountReady();
|
|
51
|
+
const start = result.current.fsRevision;
|
|
52
|
+
|
|
53
|
+
await act(async () => { await result.current.createFile('a.md'); });
|
|
54
|
+
expect(result.current.fsRevision).toBe(start + 1);
|
|
55
|
+
|
|
56
|
+
await act(async () => { await result.current.createDirectory('d'); });
|
|
57
|
+
expect(result.current.fsRevision).toBe(start + 2);
|
|
58
|
+
|
|
59
|
+
await act(async () => { await result.current.saveFile('a.md', 'x'); });
|
|
60
|
+
expect(result.current.fsRevision).toBe(start + 3);
|
|
61
|
+
|
|
62
|
+
await act(async () => { await result.current.moveEntry('a.md', 'b.md'); });
|
|
63
|
+
expect(result.current.fsRevision).toBe(start + 4);
|
|
64
|
+
|
|
65
|
+
await act(async () => { await result.current.deleteEntry('b.md'); });
|
|
66
|
+
expect(result.current.fsRevision).toBe(start + 5);
|
|
67
|
+
|
|
68
|
+
await act(async () => {
|
|
69
|
+
await result.current.uploadFiles([new File(['hi'], 'c.md')], '');
|
|
70
|
+
});
|
|
71
|
+
expect(result.current.fsRevision).toBe(start + 6);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// `deleteEntry` uses optimistic UI: it prunes the local tree before
|
|
75
|
+
// awaiting the server, then rolls back on failure. Both transitions
|
|
76
|
+
// are real state changes watchers (memoised tree derivations,
|
|
77
|
+
// explorer re-renders) need to see, so `fsRevision` legitimately
|
|
78
|
+
// bumps twice on the failure path — that's the cost of the folder
|
|
79
|
+
// vanishing instantly on click. The old "no bump on failure" test
|
|
80
|
+
// assumed the pre-optimistic synchronous flow.
|
|
81
|
+
it('bumps optimistically and again on rollback when a mutation fails', async () => {
|
|
82
|
+
const result = await mountReady();
|
|
83
|
+
const start = result.current.fsRevision;
|
|
84
|
+
|
|
85
|
+
vi.mocked(api.deleteFile).mockRejectedValueOnce(new Error('boom'));
|
|
86
|
+
await act(async () => {
|
|
87
|
+
await expect(result.current.deleteEntry('a.md')).rejects.toThrow('boom');
|
|
88
|
+
});
|
|
89
|
+
expect(result.current.fsRevision).toBeGreaterThan(start);
|
|
90
|
+
});
|
|
91
|
+
});
|