@bevel-software/platform-core-frontend 0.13.6 → 0.15.1

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 (102) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +18 -17
  3. package/src/core/__tests__/bootstrap.test.ts +33 -1
  4. package/src/core/bootstrap.ts +30 -1
  5. package/src/lib/__tests__/api.test.ts +38 -0
  6. package/src/lib/__tests__/utils.test.ts +43 -0
  7. package/src/lib/api.ts +19 -2
  8. package/src/lib/utils.ts +17 -7
  9. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +111 -1
  10. package/src/modules/access/__tests__/plugin-token.test.ts +21 -0
  11. package/src/modules/access/api.ts +52 -4
  12. package/src/modules/access/components/ManageAccessDialog.tsx +112 -83
  13. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +65 -1
  14. package/src/modules/git/components/GitSyncFailedBanner.tsx +68 -5
  15. package/src/modules/layout/components/SidebarFrame.tsx +1 -1
  16. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +2 -1
  17. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +1 -1
  18. package/src/modules/library/__tests__/LinkSkillPanel.test.tsx +121 -0
  19. package/src/modules/library/__tests__/LockedPluginView.test.tsx +6 -0
  20. package/src/modules/library/__tests__/McpServerSection.test.tsx +7 -1
  21. package/src/modules/library/__tests__/NewPluginDialog.test.tsx +5 -4
  22. package/src/modules/library/__tests__/PluginExtras.test.tsx +15 -0
  23. package/src/modules/library/__tests__/PluginPage.test.tsx +195 -1
  24. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +1 -1
  25. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +1 -1
  26. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +64 -3
  27. package/src/modules/library/__tests__/SkillPage.test.tsx +9 -2
  28. package/src/modules/library/__tests__/SkillsTree.test.tsx +172 -0
  29. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +216 -8
  30. package/src/modules/library/__tests__/ToolPage.test.tsx +23 -3
  31. package/src/modules/library/__tests__/ToolVarRow.test.tsx +7 -7
  32. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +115 -4
  33. package/src/modules/library/__tests__/library-data.stale.test.tsx +90 -0
  34. package/src/modules/library/__tests__/library-paths.test.ts +32 -0
  35. package/src/modules/library/__tests__/link-membership.test.ts +120 -0
  36. package/src/modules/library/__tests__/plugin-summary.test.ts +32 -0
  37. package/src/modules/library/__tests__/status.test.ts +84 -0
  38. package/src/modules/library/__tests__/useJoinRequests.test.tsx +46 -0
  39. package/src/modules/library/components/AddToPluginDialog.tsx +33 -0
  40. package/src/modules/library/components/LibraryCard.tsx +21 -1
  41. package/src/modules/library/components/LibraryLayout.tsx +24 -14
  42. package/src/modules/library/components/LinkSkillPanel.tsx +171 -0
  43. package/src/modules/library/components/LockedPluginView.tsx +2 -2
  44. package/src/modules/library/components/NewPluginDialog.tsx +4 -4
  45. package/src/modules/library/components/PageActions.tsx +21 -1
  46. package/src/modules/library/components/PersonalPluginPage.tsx +2 -1
  47. package/src/modules/library/components/PluginExtras.tsx +3 -1
  48. package/src/modules/library/components/PluginPage.tsx +92 -12
  49. package/src/modules/library/components/PluginsIndexPage.tsx +11 -6
  50. package/src/modules/library/components/PluginsSidebar.tsx +110 -53
  51. package/src/modules/library/components/RenamePluginDialog.tsx +136 -0
  52. package/src/modules/library/components/SkillsTree.tsx +91 -0
  53. package/src/modules/library/components/StatusDot.tsx +1 -0
  54. package/src/modules/library/components/plugin-page-parts.tsx +32 -9
  55. package/src/modules/library/components/skill-page/SharedViaPlugins.tsx +218 -0
  56. package/src/modules/library/components/skill-page/SkillPage.tsx +75 -7
  57. package/src/modules/library/components/tool-page/McpServerSection.tsx +9 -1
  58. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +223 -8
  59. package/src/modules/library/components/tool-page/ToolPage.tsx +30 -2
  60. package/src/modules/library/components/tool-page/ToolVarRow.tsx +30 -8
  61. package/src/modules/library/hooks/useJoinRequests.ts +48 -18
  62. package/src/modules/library/hooks/useToolPage.ts +28 -11
  63. package/src/modules/library/routes/WorkspaceItemRoute.tsx +180 -83
  64. package/src/modules/library/routes/library-paths.ts +21 -8
  65. package/src/modules/library/services/library.api.ts +55 -1
  66. package/src/modules/library/services/plugins.api.ts +94 -3
  67. package/src/modules/library/state/library-data.tsx +115 -22
  68. package/src/modules/library/utils/plugin-summary.ts +36 -0
  69. package/src/modules/library/utils/status.ts +173 -17
  70. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +3 -2
  71. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +29 -14
  72. package/src/modules/secrets-vault/components/SecretsPage.tsx +4 -1
  73. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +4 -1
  74. package/src/modules/secrets-vault/services/tool-secrets.api.ts +36 -0
  75. package/src/modules/settings/components/ClaudeConnectionCard.tsx +169 -0
  76. package/src/modules/settings/components/DeploymentPage.tsx +15 -1
  77. package/src/modules/settings/components/__tests__/ClaudeConnectionCard.test.tsx +63 -0
  78. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +10 -0
  79. package/src/modules/settings/services/github-facade.api.ts +43 -0
  80. package/src/modules/setup/__tests__/setup.test.tsx +118 -0
  81. package/src/modules/setup/components/SetupGate.tsx +1 -1
  82. package/src/modules/setup/components/SetupScreen.tsx +195 -2
  83. package/src/modules/setup/services/setup.api.ts +78 -0
  84. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +301 -93
  85. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +129 -6
  86. package/src/modules/toolbar/services/external-api-keys.api.ts +2 -0
  87. package/src/modules/workspace/__tests__/testFixtures.ts +1 -0
  88. package/src/modules/workspace/components/FileExplorer.tsx +292 -236
  89. package/src/modules/workspace/components/FileRoute.tsx +37 -0
  90. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +39 -0
  91. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +1 -0
  92. package/src/modules/workspace/hooks/useMergedWorkspaceTree.ts +70 -0
  93. package/src/modules/workspace/hooks/useWorkspaceState.ts +17 -3
  94. package/src/modules/workspace/routing/kb-routes.ts +1 -1
  95. package/src/modules/workspace/state/workspace.context.ts +8 -0
  96. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +15 -0
  97. package/src/modules/workspace/utils/fileTree.ts +14 -16
  98. package/src/shared/__tests__/marketplace-url.test.ts +54 -0
  99. package/src/shared/components/Badge.tsx +3 -1
  100. package/src/shared/components/Banner.tsx +5 -1
  101. package/src/shared/marketplace-url.ts +90 -0
  102. package/src/shared/theme/tokens.css +9 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.13.6",
3
+ "version": "0.15.1",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -45,7 +45,7 @@
45
45
  "tailwind-merge": "^3.5.0",
46
46
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
47
47
  "yaml": "^2.9.0",
48
- "@bevel-software/platform-shared": "0.13.6"
48
+ "@bevel-software/platform-shared": "0.15.1"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@testing-library/jest-dom": "^6.9.1",
@@ -250,7 +250,13 @@ function CoreSurfaces() {
250
250
  claim('skills-tools');
251
251
  return () => claim(null);
252
252
  }, [claimsSkills, claim]);
253
- return library ? <LibraryRoutes /> : <KnowledgeSurface />;
253
+ // Mounted here, once, above BOTH surfaces: the Knowledge tree, the tab
254
+ // strip, the viewer's banner AND the Library's Skills tree all ask the same
255
+ // question, and a tree rendered outside the provider would read the empty
256
+ // default and never show a proposed file.
257
+ return (
258
+ <OpenChangeRequestsProvider>{library ? <LibraryRoutes /> : <KnowledgeSurface />}</OpenChangeRequestsProvider>
259
+ );
254
260
  }
255
261
 
256
262
  /**
@@ -272,23 +278,18 @@ function KnowledgeSurface() {
272
278
  ),
273
279
  [registry],
274
280
  );
275
- // Mounted here, once, because three separate subtrees ask the same question:
276
- // the tree (per row), the tab strip (per tab) and the viewer's banner. A
277
- // plain hook per consumer would give every tree row its own request.
278
281
  return (
279
- <OpenChangeRequestsProvider>
280
- {/* The connect-your-agent reminder rides Knowledge's sidebar too, and
281
- the shell is where that is decided: `layout` is the app's generic
282
- consistency layer and must not name a domain component, so the pill
283
- is passed IN from the composition root. The Library passes the same
284
- one from `LibraryLayout` — one pill, both surfaces, so a person who
285
- skipped the welcome page and stayed in Knowledge still sees it. */}
286
- <AppLayout
287
- panes={panes}
288
- onController={setController}
289
- sidebarHeader={<ConnectAgentPill />}
290
- />
291
- </OpenChangeRequestsProvider>
282
+ /* The connect-your-agent reminder rides Knowledge's sidebar too, and
283
+ the shell is where that is decided: `layout` is the app's generic
284
+ consistency layer and must not name a domain component, so the pill
285
+ is passed IN from the composition root. The Library passes the same
286
+ one from `LibraryLayout` — one pill, both surfaces, so a person who
287
+ skipped the welcome page and stayed in Knowledge still sees it. */
288
+ <AppLayout
289
+ panes={panes}
290
+ onController={setController}
291
+ sidebarHeader={<ConnectAgentPill />}
292
+ />
292
293
  );
293
294
  }
294
295
 
@@ -1,5 +1,12 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { configureBranchModel, DEFAULT_BRANCH } from '@bevel-software/platform-shared';
2
+ import {
3
+ configureBranchModel,
4
+ configureKbLayout,
5
+ DEFAULT_BRANCH,
6
+ DEFAULT_KB_LAYOUT,
7
+ PLUGINS_DIR,
8
+ SKILLS_DIR,
9
+ } from '@bevel-software/platform-shared';
3
10
  import { loadServerConfig } from '../bootstrap';
4
11
  import { mcpEndpointUrl } from '../../shared/mcp';
5
12
 
@@ -26,6 +33,7 @@ afterEach(() => {
26
33
  // The model is module-global; restore what the shared test setup applied so
27
34
  // a later suite is not left with whatever a case here configured.
28
35
  configureBranchModel(CONFIGURED);
36
+ configureKbLayout({ ...DEFAULT_KB_LAYOUT });
29
37
  });
30
38
 
31
39
  const respond = (branchModel: unknown, rest: Record<string, unknown> = {}) =>
@@ -70,6 +78,30 @@ describe('loadServerConfig', () => {
70
78
  * one the OAuth metadata publishes, and that is the one that decides
71
79
  * whether a connector works.
72
80
  */
81
+ describe('the KB layout', () => {
82
+ it('applies the root names the server runs with', async () => {
83
+ respond(CONFIGURED, {
84
+ kbLayout: { knowledgeBaseDir: 'docs', skillsDir: 'skills', pluginsDir: 'plugins' },
85
+ });
86
+ await loadServerConfig();
87
+ expect(SKILLS_DIR).toBe('skills');
88
+ expect(PLUGINS_DIR).toBe('plugins');
89
+ });
90
+
91
+ it('keeps the defaults when an older server sends none', async () => {
92
+ respond(CONFIGURED);
93
+ await loadServerConfig();
94
+ expect(SKILLS_DIR).toBe('Skills');
95
+ expect(PLUGINS_DIR).toBe('Plugins');
96
+ });
97
+
98
+ it('keeps the defaults rather than applying a layout that cannot be valid', async () => {
99
+ respond(CONFIGURED, { kbLayout: { knowledgeBaseDir: 'x', skillsDir: 'x', pluginsDir: 'x' } });
100
+ await loadServerConfig();
101
+ expect(SKILLS_DIR).toBe('Skills');
102
+ });
103
+ });
104
+
73
105
  describe('the MCP endpoint', () => {
74
106
  it('applies what the server said', async () => {
75
107
  respond(CONFIGURED, { mcpUrl: 'https://kb.acme.com/api/mcp' });
@@ -1,8 +1,15 @@
1
- import { configureBranchModel, validateBranchModel } from '@bevel-software/platform-shared';
1
+ import {
2
+ configureBranchModel,
3
+ configureKbLayout,
4
+ validateBranchModel,
5
+ validateKbLayout,
6
+ type KbLayout,
7
+ } from '@bevel-software/platform-shared';
2
8
  // The pure module, NOT the `shared/mcp` barrel — the same reason `test-setup.ts`
3
9
  // avoids it. This runs BEFORE React renders, and the barrel would drag the
4
10
  // components and their icon imports into the boot path to set one string.
5
11
  import { configureMcpUrl } from '../shared/mcp/connect-snippets';
12
+ import { configureMarketplaceGitUrl } from '../shared/marketplace-url';
6
13
 
7
14
  /** What `GET /api/config` serves. Unauthenticated — see the route's comment. */
8
15
  interface ServerConfig {
@@ -14,6 +21,13 @@ interface ServerConfig {
14
21
  * is what every connect surface did before this existed.
15
22
  */
16
23
  mcpUrl?: string;
24
+ /**
25
+ * Optional for the same version-skew reason: a server that predates the
26
+ * field leaves the defaults in place, which is what it was running with.
27
+ */
28
+ kbLayout?: KbLayout;
29
+ /** The per-user marketplace git remote; absent from an older server. */
30
+ marketplaceGitUrl?: string;
17
31
  }
18
32
 
19
33
  /**
@@ -53,6 +67,20 @@ export async function loadServerConfig(): Promise<void> {
53
67
  const problem = validateBranchModel(config.branchModel);
54
68
  if (!problem) configureBranchModel(config.branchModel);
55
69
 
70
+ // The KB layout has defaults, so an absent or invalid one is not a boot
71
+ // failure either: the module keeps its defaults, which is exactly what an
72
+ // older server that omits the field is running with.
73
+ const layout = config.kbLayout;
74
+ if (
75
+ layout &&
76
+ typeof layout.knowledgeBaseDir === 'string' &&
77
+ typeof layout.skillsDir === 'string' &&
78
+ typeof layout.pluginsDir === 'string' &&
79
+ !validateKbLayout(layout)
80
+ ) {
81
+ configureKbLayout(layout);
82
+ }
83
+
56
84
  /**
57
85
  * Unconditional, and deliberately not guarded by the branch-model check
58
86
  * above: an unconfigured deployment still has a real address, and the
@@ -61,6 +89,7 @@ export async function loadServerConfig(): Promise<void> {
61
89
  * origin rather than taking down the boot for a snippet.
62
90
  */
63
91
  configureMcpUrl(config.mcpUrl);
92
+ configureMarketplaceGitUrl(config.marketplaceGitUrl);
64
93
  }
65
94
 
66
95
  /**
@@ -93,3 +93,41 @@ describe('authFetch transport-failure signalling', () => {
93
93
  expect(watcher.seen()).toBe(1);
94
94
  });
95
95
  });
96
+
97
+ describe('authFetch application-level responses', () => {
98
+ let watcher: ReturnType<typeof watchUnreachable>;
99
+ beforeEach(() => {
100
+ vi.restoreAllMocks();
101
+ watcher = watchUnreachable();
102
+ });
103
+ afterEach(() => {
104
+ watcher.stop();
105
+ });
106
+
107
+ it('a 503 the endpoint marked as its own does not signal; an unmarked 503 and a 502 still do', async () => {
108
+ // `POST /api/sync` answers 503 when a branch could not be pulled and stamps
109
+ // the response; a reverse proxy answering for a dead backend never does.
110
+ const marked = (r: Response) => r.headers.get('x-hexis-sync') === 'result';
111
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
112
+ new Response('{}', { status: 503, headers: { 'x-hexis-sync': 'result' } }),
113
+ );
114
+ await authFetch('/api/sync', { method: 'POST' }, { isApplicationResponse: marked });
115
+ expect(watcher.seen()).toBe(0);
116
+
117
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response('<html>503</html>', { status: 503 }));
118
+ await authFetch('/api/sync', { method: 'POST' }, { isApplicationResponse: marked });
119
+ expect(watcher.seen()).toBe(1);
120
+
121
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response('', { status: 502 }));
122
+ await authFetch('/api/sync', { method: 'POST' }, { isApplicationResponse: marked });
123
+ expect(watcher.seen()).toBe(2);
124
+ });
125
+
126
+ it('a network failure on such a call still signals', async () => {
127
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new TypeError('Failed to fetch'));
128
+ await expect(
129
+ authFetch('/api/sync', { method: 'POST' }, { isApplicationResponse: () => true }),
130
+ ).rejects.toThrow('Failed to fetch');
131
+ expect(watcher.seen()).toBe(1);
132
+ });
133
+ });
@@ -0,0 +1,43 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { formatRelativeTime } from '../utils';
3
+
4
+ /**
5
+ * One relative-time formatter for the whole app, so the same instant cannot
6
+ * render as "2h ago" in one place and "2 hr ago" in another. These pin the
7
+ * parts the callers rely on: the input shapes they actually hold, and the ''
8
+ * that lets each surface supply its own word for "no timestamp" ("never" for an
9
+ * unused API key, "just now" for a connection verdict) without forking the
10
+ * dialect for every timestamp that DOES exist.
11
+ */
12
+ describe('formatRelativeTime', () => {
13
+ const agoMs = (ms: number) => Date.now() - ms;
14
+
15
+ it.each([
16
+ [30_000, 'just now'],
17
+ [5 * 60_000, '5m ago'],
18
+ [3 * 3_600_000, '3h ago'],
19
+ [2 * 86_400_000, '2d ago'],
20
+ [10 * 86_400_000, '1w ago'],
21
+ ])('formats %i ms ago as %s', (ms, expected) => {
22
+ expect(formatRelativeTime(agoMs(ms))).toBe(expected);
23
+ });
24
+
25
+ it('accepts an ISO string, epoch milliseconds and a Date alike', () => {
26
+ const then = new Date(agoMs(5 * 60_000));
27
+ expect(formatRelativeTime(then.toISOString())).toBe('5m ago');
28
+ expect(formatRelativeTime(then.getTime())).toBe('5m ago');
29
+ expect(formatRelativeTime(then)).toBe('5m ago');
30
+ });
31
+
32
+ it.each([[null], [undefined], [''], ['not-a-date'], [Number.NaN]])(
33
+ 'formats %j as the empty string, leaving the word to the caller',
34
+ (value) => {
35
+ expect(formatRelativeTime(value as string | number | null | undefined)).toBe('');
36
+ },
37
+ );
38
+
39
+ it('falls back to an absolute date past ~a month', () => {
40
+ const old = new Date(agoMs(200 * 86_400_000));
41
+ expect(formatRelativeTime(old)).toBe(old.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }));
42
+ });
43
+ });
package/src/lib/api.ts CHANGED
@@ -52,11 +52,28 @@ export function clearToken(): void {
52
52
  localStorage.removeItem(TOKEN_KEY);
53
53
  }
54
54
 
55
+ export interface AuthFetchOptions {
56
+ /**
57
+ * Recognise a response that carries one of the proxy-down statuses but is
58
+ * in fact the BACKEND answering — an ordinary result of this endpoint, not
59
+ * the proxy standing in for a dead upstream. `POST /api/sync` says 503 when
60
+ * a branch could not be pulled, and marks every response it writes with a
61
+ * header a proxy never sets; the caller checks for that marker here. A
62
+ * status alone is never enough: a proxy 503 looks identical by status.
63
+ * Network failures always signal, whatever this returns.
64
+ */
65
+ isApplicationResponse?: (response: Response) => boolean;
66
+ }
67
+
55
68
  /**
56
69
  * Fetch wrapper that injects the Authorization header from localStorage.
57
70
  * On 401 responses, clears the stored token.
58
71
  */
59
- export async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
72
+ export async function authFetch(
73
+ input: RequestInfo | URL,
74
+ init?: RequestInit,
75
+ opts: AuthFetchOptions = {},
76
+ ): Promise<Response> {
60
77
  const token = getToken();
61
78
  const headers = new Headers(init?.headers);
62
79
  if (token) headers.set('Authorization', `Bearer ${token}`);
@@ -73,7 +90,7 @@ export async function authFetch(input: RequestInfo | URL, init?: RequestInit): P
73
90
  throw err;
74
91
  }
75
92
 
76
- if (PROXY_DOWN_STATUSES.has(response.status)) {
93
+ if (PROXY_DOWN_STATUSES.has(response.status) && !opts.isApplicationResponse?.(response)) {
77
94
  signalUnreachable();
78
95
  }
79
96
 
package/src/lib/utils.ts CHANGED
@@ -55,6 +55,8 @@ const twMerge = extendTailwindMerge({
55
55
  'wait',
56
56
  'wait-soft',
57
57
  'wait-dot',
58
+ 'urgent',
59
+ 'urgent-soft',
58
60
  'danger',
59
61
  'danger-soft',
60
62
  'mark-del',
@@ -88,14 +90,22 @@ export function getFileExtension(filename: string): string {
88
90
  * Human-readable relative time ("2h ago", "3d ago"). Falls back to an absolute
89
91
  * date past ~a month, where "5w ago" stops meaning anything.
90
92
  *
91
- * Shared rather than per-surface: the file-history timeline and the document
92
- * rail both say when a file was last touched, and two formatters would
93
- * eventually disagree about the same commit on the same screen.
93
+ * THE relative-time formatter, not one of several: a file-history entry, a
94
+ * document rail, an API key's last use and a connection check all answer the
95
+ * same question, and per-surface copies drift — "2h ago" beside "2 hr ago" for
96
+ * the same instant, one flooring where the other rounds. Anything that needs a
97
+ * different WORD for a missing timestamp supplies its own around this ('' comes
98
+ * back for nothing to format), rather than a second dialect for the times it
99
+ * can format.
100
+ *
101
+ * Accepts what the surfaces actually hold: an ISO string from the API, epoch
102
+ * milliseconds from a browser-side record, or a `Date`. Anything unparseable
103
+ * formats as '' — a caller's fallback word beats echoing a malformed value.
94
104
  */
95
- export function formatRelativeTime(iso: string): string {
96
- if (!iso) return '';
97
- const d = new Date(iso);
98
- if (Number.isNaN(d.getTime())) return iso;
105
+ export function formatRelativeTime(at: string | number | Date | null | undefined): string {
106
+ if (at === null || at === undefined || at === '') return '';
107
+ const d = at instanceof Date ? at : new Date(at);
108
+ if (Number.isNaN(d.getTime())) return '';
99
109
  const diffMs = Date.now() - d.getTime();
100
110
  const absolute = () =>
101
111
  d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen, waitFor } from '@testing-library/react';
2
+ import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
4
  import type { FileTreeEntry } from '@bevel-software/platform-shared';
5
5
  import type { AccessResponse } from '../api';
@@ -129,6 +129,116 @@ describe('ManageAccessDialog: unchecking an inherited verb on a mixed row', () =
129
129
  });
130
130
  });
131
131
 
132
+ /**
133
+ * A public node. The "Anyone can read" band is a STATEMENT — it says the node
134
+ * is public and why — and never a control: every reason it names is a grant
135
+ * with a row below (the Everyone row for a literal line, the plugin's row for
136
+ * a public plugin principal), and the row is the one place any grant is
137
+ * removed, through the same flow as every other principal.
138
+ */
139
+ describe('ManageAccessDialog: a public node', () => {
140
+ const PUBLIC_VIEW = {
141
+ canRead: true,
142
+ canWrite: true,
143
+ canDownload: false,
144
+ canOwner: true,
145
+ eligible: { roles: [], users: [] },
146
+ owners: { roles: [], users: [] },
147
+ downloaders: { roles: [], users: [] },
148
+ };
149
+ const readers = (publicVia: string[], withPlugin: boolean) => ({
150
+ restricted: false,
151
+ principals: [
152
+ { name: 'everyone', kind: 'role' as const },
153
+ ...(withPlugin ? [{ name: 'plugin/open/read', kind: 'plugin' as const }] : []),
154
+ ],
155
+ roles: ['everyone', ...(withPlugin ? ['plugin/open/read'] : [])],
156
+ users: [],
157
+ publicVia,
158
+ });
159
+
160
+ beforeEach(() => {
161
+ vi.clearAllMocks();
162
+ api.suggestPrincipals.mockResolvedValue({ roles: [], groups: [], people: [], peopleWithheld: false });
163
+ });
164
+
165
+ it('a literal grant here: the band says so, and the Everyone row removes it like any other row', async () => {
166
+ const user = userEvent.setup();
167
+ api.fetchFileAccess.mockResolvedValue({
168
+ ...PUBLIC_VIEW,
169
+ readers: readers([], false),
170
+ sources: { 'r:everyone': { read: [{ kind: 'direct' }] } },
171
+ } as AccessResponse);
172
+ api.revokeAccess.mockResolvedValue({ ...PUBLIC_VIEW, readers: { restricted: true, roles: [], users: [] }, sources: {} });
173
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
174
+ const band = (await screen.findByText('Anyone can read')).closest('div.flex.items-center') as HTMLElement;
175
+ expect(screen.getByText(/granted here/)).toBeInTheDocument();
176
+ // The band itself has nothing to click.
177
+ expect(within(band).queryByRole('button')).toBeNull();
178
+
179
+ // The row: opens to exactly the verb Everyone can hold, and Remove access.
180
+ expect(screen.getByText('Everyone')).toBeInTheDocument();
181
+ await user.click(screen.getByRole('button', { name: /^can read$/i }));
182
+ const removeItem = screen.getByRole('button', { name: /remove access/i });
183
+ const menu = removeItem.parentElement as HTMLElement;
184
+ expect(within(menu).getAllByRole('button').map((b) => b.textContent?.trim())).toEqual(['Can read', 'Remove access']);
185
+ await user.click(removeItem);
186
+ await waitFor(() => expect(api.revokeAccess).toHaveBeenCalledTimes(1));
187
+ expect(api.revokeAccess).toHaveBeenCalledWith(
188
+ 'ws-1',
189
+ expect.objectContaining({ principal: { kind: 'role', role: 'everyone' } }),
190
+ );
191
+ });
192
+
193
+ it('public through a plugin only: the band names the plugin, whose row is the grant — no Everyone row', async () => {
194
+ api.fetchFileAccess.mockResolvedValue({
195
+ ...PUBLIC_VIEW,
196
+ readers: readers(['plugin/open/read'], true),
197
+ sources: { 'r:everyone': {}, 'p:plugin/open/read': { read: [{ kind: 'direct' }] } },
198
+ } as AccessResponse);
199
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
200
+ const band = (await screen.findByText('Anyone can read')).closest('div.flex.items-center') as HTMLElement;
201
+ expect(screen.getByText(/through open · readers/)).toBeInTheDocument();
202
+ expect(screen.getByText('open · readers')).toBeInTheDocument();
203
+ // A derived everyone has no line of its own — no row to remove nothing by,
204
+ // not even a collapsed "through a role" one.
205
+ expect(screen.queryByText('Everyone')).toBeNull();
206
+ expect(screen.queryByRole('button', { name: /People with access through a role/ })).toBeNull();
207
+ expect(within(band).queryByRole('button')).toBeNull();
208
+ });
209
+
210
+ it('both a literal line and a public plugin: the band lists both reasons, and both rows are there', async () => {
211
+ api.fetchFileAccess.mockResolvedValue({
212
+ ...PUBLIC_VIEW,
213
+ readers: readers(['plugin/open/read'], true),
214
+ sources: {
215
+ 'r:everyone': { read: [{ kind: 'direct' }] },
216
+ 'p:plugin/open/read': { read: [{ kind: 'direct' }] },
217
+ },
218
+ } as AccessResponse);
219
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
220
+ await screen.findByText('Anyone can read');
221
+ expect(screen.getByText(/granted here, through open · readers/)).toBeInTheDocument();
222
+ expect(screen.getByText('Everyone')).toBeInTheDocument();
223
+ expect(screen.getByText('open · readers')).toBeInTheDocument();
224
+ });
225
+
226
+ it('a literal line in a parent: the band says where, and the Everyone row is inherited from there', async () => {
227
+ api.fetchFileAccess.mockResolvedValue({
228
+ ...PUBLIC_VIEW,
229
+ readers: readers([], false),
230
+ sources: { 'r:everyone': { read: [{ kind: 'ancestor', path: 'Sales/access.md' }] } },
231
+ } as AccessResponse);
232
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
233
+ await screen.findByText('Anyone can read');
234
+ expect(screen.getByText(/inherited from Sales/)).toBeInTheDocument();
235
+ // The row files under the folder that grants it, like every inherited grant.
236
+ fireEvent.click(screen.getByRole('button', { name: /People invited to Sales/ }));
237
+ expect(screen.getByText('Everyone')).toBeInTheDocument();
238
+ expect(screen.getByText(/via Sales/)).toBeInTheDocument();
239
+ });
240
+ });
241
+
132
242
  /**
133
243
  * Which BRANCH an access edit lands on.
134
244
  *
@@ -0,0 +1,21 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { parsePluginPrincipalToken, pluginPrincipalToken } from '../api';
3
+
4
+ /**
5
+ * The client's reading of a plugin token matches the grammar's: one name,
6
+ * one verb. A nested name is not a plugin, and must not be shown as one and
7
+ * then re-submitted as a different canonical principal.
8
+ */
9
+ describe('parsePluginPrincipalToken', () => {
10
+ it('round-trips a token the client itself spells', () => {
11
+ expect(parsePluginPrincipalToken(pluginPrincipalToken('GTM', 'read'))).toEqual({ plugin: 'GTM', verb: 'read' });
12
+ expect(parsePluginPrincipalToken('Plugin/Sales Team/WRITE')).toEqual({ plugin: 'Sales Team', verb: 'write' });
13
+ });
14
+
15
+ it('rejects a nested name, a missing name, and an unknown verb', () => {
16
+ expect(parsePluginPrincipalToken('plugin/foo/bar/read')).toBeNull();
17
+ expect(parsePluginPrincipalToken('plugin//read')).toBeNull();
18
+ expect(parsePluginPrincipalToken('plugin/GTM/delete')).toBeNull();
19
+ expect(parsePluginPrincipalToken('role/GTM')).toBeNull();
20
+ });
21
+ });
@@ -1,10 +1,44 @@
1
1
  import { authFetch } from '../../lib/api';
2
2
  import { GitApiError, handleApiResponse } from '../git/services/git.api';
3
3
 
4
- /** A collective grantee with WHAT it is — role (capability) or group (audience). */
4
+ /**
5
+ * A collective grantee with WHAT it is — role (capability), group (audience),
6
+ * or plugin (everyone holding a verb on a plugin folder: the name is the
7
+ * `plugin/<Name>/<verb>` token).
8
+ */
5
9
  export interface ResolvedPrincipal {
6
10
  name: string;
7
- kind: 'role' | 'group';
11
+ kind: 'role' | 'group' | 'plugin';
12
+ }
13
+
14
+ /** The verbs a plugin principal can stand for — each is its own grantee. */
15
+ export type PluginPrincipalVerb = 'read' | 'write' | 'owner';
16
+ export const PLUGIN_PRINCIPAL_VERBS: readonly PluginPrincipalVerb[] = ['read', 'write', 'owner'];
17
+
18
+ /** How a plugin principal is spelled in access rules and resolver output. */
19
+ export function pluginPrincipalToken(plugin: string, verb: PluginPrincipalVerb): string {
20
+ return `plugin/${plugin}/${verb}`;
21
+ }
22
+
23
+ /** The parts of a `plugin/<Name>/<verb>` token, or null when it is not one. */
24
+ export function parsePluginPrincipalToken(
25
+ token: string,
26
+ ): { plugin: string; verb: PluginPrincipalVerb } | null {
27
+ if (!token.toLowerCase().startsWith('plugin/')) return null;
28
+ const rest = token.slice('plugin/'.length);
29
+ const cut = rest.lastIndexOf('/');
30
+ // Exactly one separator, as the access grammar has it: a nested name is
31
+ // not a plugin, and showing one would let it be re-submitted as if it were.
32
+ if (cut <= 0 || rest.slice(0, cut).includes('/')) return null;
33
+ const verb = rest.slice(cut + 1).toLowerCase();
34
+ if (!(PLUGIN_PRINCIPAL_VERBS as readonly string[]).includes(verb)) return null;
35
+ return { plugin: rest.slice(0, cut), verb: verb as PluginPrincipalVerb };
36
+ }
37
+
38
+ /** "GTM · readers" — the human spelling of a plugin principal. */
39
+ export function pluginPrincipalLabel(plugin: string, verb: PluginPrincipalVerb): string {
40
+ const who = verb === 'read' ? 'readers' : verb === 'write' ? 'writers' : 'owners';
41
+ return `${plugin} · ${who}`;
8
42
  }
9
43
 
10
44
  export interface AccessEligible {
@@ -20,8 +54,14 @@ export interface AccessEligible {
20
54
  }
21
55
 
22
56
  export interface AccessReaders extends AccessEligible {
23
- /** False when `read: everyone` applies cleanly (the lists are then empty). */
57
+ /** False when `read: everyone` applies cleanly — the node is public. */
24
58
  restricted: boolean;
59
+ /**
60
+ * The PUBLIC plugin principals (`plugin/<name>/read` tokens whose plugin
61
+ * anyone can read) granted read here — why the node is public besides any
62
+ * literal `everyone` line. Optional for version skew.
63
+ */
64
+ publicVia?: string[];
25
65
  }
26
66
 
27
67
  /**
@@ -113,7 +153,9 @@ export function asInheritedError(err: unknown): InheritedRevokeError | null {
113
153
  export type Principal =
114
154
  | { kind: 'user'; email: string; displayName: string }
115
155
  | { kind: 'role'; role: string }
116
- | { kind: 'group'; group: string };
156
+ | { kind: 'group'; group: string }
157
+ /** Everyone holding `verb` on the plugin folder — written as `plugin/<Name>/<verb>`. */
158
+ | { kind: 'plugin'; plugin: string; verb: PluginPrincipalVerb };
117
159
 
118
160
  /** Verbs the share dialog can grant. */
119
161
  export type GrantVerb = 'read' | 'write' | 'owner' | 'download';
@@ -129,6 +171,12 @@ export interface SuggestResponse {
129
171
  roles?: string[];
130
172
  /** Active-source groups. A name shared with a role is offered as BOTH. */
131
173
  groups?: string[];
174
+ /**
175
+ * Plugin FOLDER names the caller can discover; each stands for three
176
+ * grantable principals (`plugin/<Name>/read|write|owner`). Not `plugins`,
177
+ * which was the retired alias of `roles`.
178
+ */
179
+ pluginPrincipals?: string[];
132
180
  people?: { name: string; email: string }[];
133
181
  /** True when the query was too short to return people (roles/groups still shown). */
134
182
  peopleWithheld?: boolean;