@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,119 @@
1
+ // Streaming walker for HTML5 drag-and-drop folder uploads.
2
+ //
3
+ // `DataTransfer.files` returns a flat FileList — when the user drops a folder,
4
+ // folder entries appear as bogus zero-byte File objects, NOT as a recursive
5
+ // listing of the folder's contents. To preserve folder structure we have to
6
+ // walk `DataTransfer.items` via `webkitGetAsEntry()`, which exposes the
7
+ // FileSystem API (FileSystemFileEntry / FileSystemDirectoryEntry). The name is
8
+ // prefixed for historical reasons; the API is supported across all current
9
+ // evergreen browsers.
10
+ //
11
+ // Yielded as an async generator so the upload pipeline can start sending the
12
+ // first file before the rest of the tree has been enumerated — for deep or
13
+ // large folders the walk itself can take hundreds of ms.
14
+ //
15
+ // IMPORTANT: callers must snapshot `webkitGetAsEntry()` for each item
16
+ // synchronously inside the drop handler before any `await`, because the
17
+ // browser invalidates the `DataTransfer` once the drop handler returns.
18
+ // `walkEntries` accepts the snapshot array; `walkDroppedItems` is a
19
+ // convenience that takes a live `DataTransferItemList` and must itself only
20
+ // be called synchronously from within the drop handler.
21
+
22
+ export type DroppedItem =
23
+ | { kind: 'file'; file: File; relativePath: string }
24
+ | { kind: 'dir'; relativePath: string };
25
+
26
+ /**
27
+ * OS-generated noise that should never make it into a KB. Mirrors the
28
+ * filter the backend's `/unzip` route already applies in
29
+ * `workspace.service.ts`, so behavior is consistent across "drop a folder"
30
+ * and "upload + extract a zip."
31
+ *
32
+ * - `__MACOSX/`, plain `__MACOSX` — Apple archive metadata directory.
33
+ * - `.DS_Store` at any depth — Finder folder-state cache.
34
+ * - `._<anything>` at any depth — macOS resource-fork sidecar files.
35
+ */
36
+ export function isUploadNoise(relativePath: string): boolean {
37
+ return (
38
+ relativePath.startsWith('__MACOSX/')
39
+ || relativePath === '__MACOSX'
40
+ || relativePath.endsWith('/.DS_Store')
41
+ || relativePath === '.DS_Store'
42
+ || /(^|\/)\._/.test(relativePath)
43
+ );
44
+ }
45
+
46
+ /**
47
+ * Snapshot the entries from a `DataTransferItemList` synchronously. Must be
48
+ * called from inside the drop handler before the first `await`.
49
+ */
50
+ export function snapshotEntries(items: DataTransferItemList): FileSystemEntry[] {
51
+ const out: FileSystemEntry[] = [];
52
+ for (let i = 0; i < items.length; i++) {
53
+ const item = items[i];
54
+ if (item.kind !== 'file') continue;
55
+ const entry = item.webkitGetAsEntry?.();
56
+ if (entry) out.push(entry);
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /**
62
+ * Walk a pre-snapshotted array of FileSystemEntry, yielding files and
63
+ * directories in tree order (each directory yielded before its children).
64
+ *
65
+ * Errors on individual entries (broken aliases, permission denials) are
66
+ * logged and skipped — the rest of the walk continues so a single bad file
67
+ * doesn't abort the whole drop.
68
+ */
69
+ export async function* walkEntries(entries: FileSystemEntry[]): AsyncGenerator<DroppedItem> {
70
+ for (const entry of entries) {
71
+ yield* walkEntry(entry, '');
72
+ }
73
+ }
74
+
75
+ async function* walkEntry(entry: FileSystemEntry, prefix: string): AsyncGenerator<DroppedItem> {
76
+ const name = entry.name;
77
+ const relativePath = prefix ? `${prefix}/${name}` : name;
78
+ if (entry.isFile) {
79
+ try {
80
+ const file = await fileEntryAsFile(entry as FileSystemFileEntry);
81
+ yield { kind: 'file', file, relativePath };
82
+ } catch (err) {
83
+ console.warn(`[upload] skipping file entry "${relativePath}":`, err);
84
+ }
85
+ return;
86
+ }
87
+ if (entry.isDirectory) {
88
+ yield { kind: 'dir', relativePath };
89
+ try {
90
+ for await (const child of readDirectoryEntries(entry as FileSystemDirectoryEntry)) {
91
+ yield* walkEntry(child, relativePath);
92
+ }
93
+ } catch (err) {
94
+ console.warn(`[upload] failed to read directory "${relativePath}":`, err);
95
+ }
96
+ }
97
+ }
98
+
99
+ function fileEntryAsFile(entry: FileSystemFileEntry): Promise<File> {
100
+ return new Promise((resolve, reject) => {
101
+ entry.file(resolve, reject);
102
+ });
103
+ }
104
+
105
+ // `readEntries` yields children in batches of ~100 — must be called repeatedly
106
+ // until it returns an empty array, otherwise large directories silently
107
+ // truncate.
108
+ async function* readDirectoryEntries(
109
+ dir: FileSystemDirectoryEntry,
110
+ ): AsyncGenerator<FileSystemEntry> {
111
+ const reader = dir.createReader();
112
+ while (true) {
113
+ const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => {
114
+ reader.readEntries(resolve, reject);
115
+ });
116
+ if (batch.length === 0) return;
117
+ for (const e of batch) yield e;
118
+ }
119
+ }
@@ -0,0 +1,23 @@
1
+ export interface PersistedTabState {
2
+ paths: string[];
3
+ activePath: string | null;
4
+ }
5
+
6
+ export function tabsKey(workspaceId: string, branch: string): string {
7
+ return `bevel.tabs.${workspaceId}.${branch}`;
8
+ }
9
+
10
+ export function readPersistedTabs(workspaceId: string, branch: string): PersistedTabState {
11
+ try {
12
+ const raw = localStorage.getItem(tabsKey(workspaceId, branch));
13
+ if (!raw) return { paths: [], activePath: null };
14
+ const parsed = JSON.parse(raw) as Partial<PersistedTabState>;
15
+ const paths = Array.isArray(parsed.paths)
16
+ ? parsed.paths.filter((p): p is string => typeof p === 'string')
17
+ : [];
18
+ const activePath = typeof parsed.activePath === 'string' ? parsed.activePath : null;
19
+ return { paths, activePath };
20
+ } catch {
21
+ return { paths: [], activePath: null };
22
+ }
23
+ }
@@ -0,0 +1,198 @@
1
+ import {
2
+ type ReactNode,
3
+ useEffect,
4
+ useId,
5
+ useRef,
6
+ } from 'react';
7
+ import { X } from 'lucide-react';
8
+ import { useModalLayer } from './useModalLayer';
9
+
10
+ /**
11
+ * The one centered-modal primitive for the app. Before this existed every
12
+ * dialog hand-rolled the same `fixed inset-0` overlay, focus trap, Escape
13
+ * handler and header — so they drifted (three different backdrop tints, subtly
14
+ * different a11y). Route everything through here instead.
15
+ *
16
+ * Backdrop is a dark 40%-opacity scrim (`bg-slate-950/40`) — the standard the
17
+ * gear-menu dialogs share. The panel is capped at 90vh and lays out as a flex
18
+ * column: `header` and `footer` stay pinned while `children` scroll, so a long
19
+ * body never pushes the dialog past the top/bottom of the viewport.
20
+ *
21
+ * Sizing: `size` maps to a Tailwind max-width. Use `sm`/`md` for short forms,
22
+ * `2xl`/`4xl`/`5xl` for data-heavy panels (routines, roles).
23
+ */
24
+
25
+ const SIZE_CLASS = {
26
+ sm: 'max-w-sm',
27
+ md: 'max-w-md',
28
+ lg: 'max-w-lg',
29
+ xl: 'max-w-xl',
30
+ '2xl': 'max-w-2xl',
31
+ '4xl': 'max-w-4xl',
32
+ '5xl': 'max-w-5xl',
33
+ } as const;
34
+
35
+ export type DialogSize = keyof typeof SIZE_CLASS;
36
+
37
+ interface DialogProps {
38
+ open: boolean;
39
+ onClose(): void;
40
+ /** Rendered in the header bar next to the close button. */
41
+ title: ReactNode;
42
+ children: ReactNode;
43
+ /** Pinned footer (e.g. action buttons). Omit for a bodyless dialog. */
44
+ footer?: ReactNode;
45
+ /** Extra controls in the header, left of the close button. */
46
+ headerActions?: ReactNode;
47
+ size?: DialogSize;
48
+ /**
49
+ * When true, clicking the backdrop, pressing Escape, and the X button are all
50
+ * inert — for dialogs that must not be dismissed mid-operation (submitting,
51
+ * a one-time key still being shown, etc.).
52
+ */
53
+ busy?: boolean;
54
+ /**
55
+ * Drop the default padded/scrolling body wrapper and render `children`
56
+ * flush against the panel. For panels that own their own internal layout
57
+ * (their own scroll regions, toolbars, split panes).
58
+ */
59
+ bare?: boolean;
60
+ /** Extra classes for the body wrapper (ignored when `bare`). */
61
+ bodyClassName?: string;
62
+ }
63
+
64
+ export function Dialog({
65
+ open,
66
+ onClose,
67
+ title,
68
+ children,
69
+ footer,
70
+ headerActions,
71
+ size = '2xl',
72
+ busy = false,
73
+ bare = false,
74
+ bodyClassName = '',
75
+ }: DialogProps) {
76
+ const titleId = useId();
77
+ const panelRef = useRef<HTMLDivElement>(null);
78
+
79
+ // Callers pass a fresh `onClose` arrow each render; mirror it into a ref so
80
+ // the trap effect below doesn't re-fire (and re-snapshot focus) every render.
81
+ const onCloseRef = useRef(onClose);
82
+ useEffect(() => {
83
+ onCloseRef.current = onClose;
84
+ }, [onClose]);
85
+
86
+ const busyRef = useRef(busy);
87
+ useEffect(() => {
88
+ busyRef.current = busy;
89
+ }, [busy]);
90
+
91
+ // Only the topmost open modal layer reacts to Escape / backdrop clicks, so a
92
+ // nested modal (its own or a hand-rolled one that opts in) can be dismissed
93
+ // without also closing this dialog behind it.
94
+ const isTopLayer = useModalLayer(open);
95
+
96
+ // Dialog a11y: move focus into the panel on open, trap focus + Escape closes
97
+ // + restore focus on close.
98
+ useEffect(() => {
99
+ if (!open) return;
100
+ const previouslyFocused = document.activeElement as HTMLElement | null;
101
+
102
+ // Pull focus into the dialog so keyboard users can't tab straight into the
103
+ // background behind the modal. Prefer the first focusable control; fall back
104
+ // to the panel itself (which carries tabIndex={-1}) when the body is empty.
105
+ const panel = panelRef.current;
106
+ const firstFocusable = panel?.querySelector<HTMLElement>(
107
+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
108
+ );
109
+ (firstFocusable ?? panel)?.focus?.();
110
+
111
+ function onKeyDown(e: KeyboardEvent) {
112
+ if (e.key === 'Escape') {
113
+ if (busyRef.current || !isTopLayer()) return;
114
+ e.stopPropagation();
115
+ onCloseRef.current();
116
+ return;
117
+ }
118
+ if (e.key !== 'Tab') return;
119
+ const panel = panelRef.current;
120
+ if (!panel) return;
121
+ const focusable = panel.querySelectorAll<HTMLElement>(
122
+ 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
123
+ );
124
+ const enabled = Array.from(focusable).filter((el) => !el.hasAttribute('disabled'));
125
+ if (enabled.length === 0) return;
126
+ const first = enabled[0];
127
+ const last = enabled[enabled.length - 1];
128
+ const active = document.activeElement as HTMLElement | null;
129
+ if (e.shiftKey && active === first) {
130
+ e.preventDefault();
131
+ last.focus();
132
+ } else if (!e.shiftKey && active === last) {
133
+ e.preventDefault();
134
+ first.focus();
135
+ }
136
+ }
137
+
138
+ document.addEventListener('keydown', onKeyDown);
139
+ return () => {
140
+ document.removeEventListener('keydown', onKeyDown);
141
+ previouslyFocused?.focus?.();
142
+ };
143
+ }, [open, isTopLayer]);
144
+
145
+ if (!open) return null;
146
+
147
+ return (
148
+ <div
149
+ className="fixed inset-0 z-50 bg-slate-950/40 flex items-center justify-center p-4"
150
+ onClick={() => {
151
+ if (busy || !isTopLayer()) return;
152
+ onClose();
153
+ }}
154
+ >
155
+ <div
156
+ ref={panelRef}
157
+ role="dialog"
158
+ aria-modal="true"
159
+ aria-labelledby={titleId}
160
+ tabIndex={-1}
161
+ className={`bg-white border border-slate-200 rounded-lg shadow-xl w-full ${SIZE_CLASS[size]} max-h-[90vh] flex flex-col`}
162
+ onClick={(e) => e.stopPropagation()}
163
+ >
164
+ <div className="flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-200 shrink-0">
165
+ <h2 id={titleId} className="text-sm font-semibold">
166
+ {title}
167
+ </h2>
168
+ <div className="flex items-center gap-2">
169
+ {headerActions}
170
+ <button
171
+ onClick={() => {
172
+ if (busy) return;
173
+ onClose();
174
+ }}
175
+ disabled={busy}
176
+ className="p-1 rounded hover:bg-slate-100 text-slate-600 hover:text-slate-900 disabled:opacity-50"
177
+ aria-label="Close"
178
+ >
179
+ <X size={16} />
180
+ </button>
181
+ </div>
182
+ </div>
183
+
184
+ {bare ? (
185
+ children
186
+ ) : (
187
+ <div className={`px-4 py-3 overflow-y-auto ${bodyClassName}`}>{children}</div>
188
+ )}
189
+
190
+ {footer && (
191
+ <div className="flex justify-end gap-2 px-4 py-3 border-t border-slate-200 shrink-0">
192
+ {footer}
193
+ </div>
194
+ )}
195
+ </div>
196
+ </div>
197
+ );
198
+ }
@@ -0,0 +1,51 @@
1
+ import type { ReactNode } from 'react';
2
+
3
+ const WIDTH_CLASS = {
4
+ '3xl': 'max-w-3xl',
5
+ '4xl': 'max-w-4xl',
6
+ } as const;
7
+
8
+ export type PageShellWidth = keyof typeof WIDTH_CLASS;
9
+
10
+ /**
11
+ * Minimal shared chrome for the shell's standalone routed pages (Secrets,
12
+ * External agent access, Roles & Members): a full-height scrolling canvas
13
+ * with a centered max-width column, a page-title row and a white content
14
+ * card. Deliberately tiny — it mirrors the Tailwind idioms the tools
15
+ * explorer page already uses; it is not a design system.
16
+ *
17
+ * `padded` drops the card's default padding for pages that own their inner
18
+ * layout (e.g. a tab strip flush against the card's top edge).
19
+ */
20
+ export function PageShell({
21
+ title,
22
+ actions,
23
+ width = '3xl',
24
+ padded = true,
25
+ children,
26
+ }: {
27
+ title: string;
28
+ /** Rendered right-aligned in the title row (e.g. a refresh button). */
29
+ actions?: ReactNode;
30
+ width?: PageShellWidth;
31
+ padded?: boolean;
32
+ children: ReactNode;
33
+ }) {
34
+ return (
35
+ <div className="h-full overflow-y-auto bg-slate-50">
36
+ <div className={`${WIDTH_CLASS[width]} mx-auto px-6 py-8`}>
37
+ <header className="mb-4 flex items-center justify-between gap-3">
38
+ <h1 className="text-lg font-semibold text-slate-800">{title}</h1>
39
+ {actions && <div className="flex items-center gap-2">{actions}</div>}
40
+ </header>
41
+ <section
42
+ className={`bg-white border border-slate-200 rounded-lg ${
43
+ padded ? 'p-4' : 'overflow-hidden'
44
+ }`}
45
+ >
46
+ {children}
47
+ </section>
48
+ </div>
49
+ </div>
50
+ );
51
+ }
@@ -0,0 +1,35 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+
3
+ // LIFO stack of open modal layers (a <Dialog> + any hand-rolled modal that
4
+ // opts in via useModalLayer). Escape-to-close should only ever dismiss the
5
+ // TOPMOST layer — without this, a nested modal and its parent both listen on
6
+ // `document` and one Escape closes both. Each open layer registers a token;
7
+ // `isTopModalLayer(token)` tells a keydown handler whether it owns this Escape.
8
+ const modalLayerStack: symbol[] = [];
9
+
10
+ /**
11
+ * Register this component as a modal layer while `active` is true, and return
12
+ * a checker for whether it is currently the topmost layer. Hand-rolled modals
13
+ * (that don't use <Dialog>) call this and guard their Escape/backdrop close on
14
+ * `isTop()` so nesting them under a <Dialog> doesn't close both at once.
15
+ *
16
+ * The returned checker is a stable reference (memoized with `useCallback`), so
17
+ * callers can list it in a `useEffect` dependency array without re-subscribing
18
+ * every render.
19
+ */
20
+ export function useModalLayer(active: boolean): () => boolean {
21
+ const tokenRef = useRef<symbol>(Symbol('modal-layer'));
22
+ useEffect(() => {
23
+ if (!active) return;
24
+ const token = tokenRef.current;
25
+ modalLayerStack.push(token);
26
+ return () => {
27
+ const i = modalLayerStack.lastIndexOf(token);
28
+ if (i !== -1) modalLayerStack.splice(i, 1);
29
+ };
30
+ }, [active]);
31
+ return useCallback(
32
+ () => modalLayerStack[modalLayerStack.length - 1] === tokenRef.current,
33
+ [],
34
+ );
35
+ }
@@ -0,0 +1,62 @@
1
+ import { memo, useMemo, type ComponentProps } from 'react';
2
+ import Md from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+
5
+ type RemarkPlugins = ComponentProps<typeof Md>['remarkPlugins'];
6
+ type MdComponents = ComponentProps<typeof Md>['components'];
7
+
8
+ // Module-level constant so the plugins prop identity is stable across renders.
9
+ // react-markdown reuses its internal pipeline only when the plugins array is
10
+ // referentially equal — a fresh array per render forces a full re-parse.
11
+ const DEFAULT_PLUGINS: RemarkPlugins = [remarkGfm];
12
+
13
+ // CommonMark rejects unescaped spaces in link destinations, which means
14
+ // `[Foo](knowledge-base/0. Current Truth/x.md)` parses as plain text — the
15
+ // agent emits paths like this routinely (KB filenames contain spaces). Wrap
16
+ // any unwrapped destination that contains a space in `<...>`, which CommonMark
17
+ // accepts. Skips destinations that already start with `<` so we don't
18
+ // double-wrap.
19
+ const LINK_WITH_SPACE_RE = /(\[[^\]\n]*\])\(([^<\s)][^)\n]*)\)/g;
20
+
21
+ export function escapeSpacesInLinkDestinations(markdown: string): string {
22
+ return markdown.replace(LINK_WITH_SPACE_RE, (match, label, destination) => {
23
+ if (!destination.includes(' ')) return match;
24
+ return `${label}(<${destination}>)`;
25
+ });
26
+ }
27
+
28
+ interface Props {
29
+ children: string;
30
+ extraPlugins?: RemarkPlugins;
31
+ /** Component overrides merged on top of react-markdown defaults. */
32
+ components?: MdComponents;
33
+ className?: string;
34
+ }
35
+
36
+ function MarkdownImpl({ children, extraPlugins, components, className }: Props) {
37
+ // Memoize the merged plugins array so its identity is stable across renders
38
+ // when extraPlugins is referentially stable. A fresh array each render forces
39
+ // react-markdown to rebuild its pipeline and re-parse the entire document.
40
+ const plugins = useMemo<RemarkPlugins>(
41
+ () => (extraPlugins ? [remarkGfm, ...extraPlugins] : DEFAULT_PLUGINS),
42
+ [extraPlugins],
43
+ );
44
+
45
+ const normalized = useMemo(
46
+ () => escapeSpacesInLinkDestinations(children),
47
+ [children],
48
+ );
49
+
50
+ return (
51
+ <div className={`prose prose-sm max-w-none ${className ?? ''}`}>
52
+ <Md remarkPlugins={plugins} components={components}>
53
+ {normalized}
54
+ </Md>
55
+ </div>
56
+ );
57
+ }
58
+
59
+ // Default shallow memo: skip re-render when (children, extraPlugins, components,
60
+ // className) are referentially equal. Callers must keep `components` stable
61
+ // (typically via useMemo); see AssistantTurn.
62
+ export const Markdown = memo(MarkdownImpl);
@@ -0,0 +1,59 @@
1
+ import '@testing-library/jest-dom/vitest';
2
+ import { cleanup } from '@testing-library/react';
3
+ import { afterEach, beforeEach } from 'vitest';
4
+
5
+ function createInMemoryStorage(): Storage {
6
+ const store = new Map<string, string>();
7
+ return {
8
+ get length() {
9
+ return store.size;
10
+ },
11
+ clear() {
12
+ store.clear();
13
+ },
14
+ getItem(key: string) {
15
+ return store.has(key) ? store.get(key)! : null;
16
+ },
17
+ key(index: number) {
18
+ return Array.from(store.keys())[index] ?? null;
19
+ },
20
+ removeItem(key: string) {
21
+ store.delete(key);
22
+ },
23
+ setItem(key: string, value: string) {
24
+ store.set(String(key), String(value));
25
+ },
26
+ } as Storage;
27
+ }
28
+
29
+ const maybeStorage = globalThis.localStorage as Partial<Storage> | undefined;
30
+ if (
31
+ !maybeStorage
32
+ || typeof maybeStorage.clear !== 'function'
33
+ || typeof maybeStorage.getItem !== 'function'
34
+ || typeof maybeStorage.setItem !== 'function'
35
+ || typeof maybeStorage.removeItem !== 'function'
36
+ ) {
37
+ Object.defineProperty(globalThis, 'localStorage', {
38
+ value: createInMemoryStorage(),
39
+ writable: true,
40
+ configurable: true,
41
+ });
42
+ }
43
+
44
+ // Mirror the storage onto `window` as well so code that reads via `window.localStorage`
45
+ // (instead of the bare global) sees the same in-memory shim in tests.
46
+ if (typeof window !== 'undefined' && window.localStorage !== globalThis.localStorage) {
47
+ Object.defineProperty(window, 'localStorage', {
48
+ configurable: true,
49
+ value: globalThis.localStorage,
50
+ });
51
+ }
52
+
53
+ beforeEach(() => {
54
+ globalThis.localStorage?.clear?.();
55
+ });
56
+
57
+ afterEach(() => {
58
+ cleanup();
59
+ });