@bevel-software/platform-core-frontend 0.28.1 → 0.29.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 (59) hide show
  1. package/package.json +11 -4
  2. package/src/core/CoreAppShell.tsx +29 -11
  3. package/src/core/__tests__/ShellRoutes.test.tsx +43 -1
  4. package/src/core/events.ts +4 -2
  5. package/src/core/registry.ts +25 -3
  6. package/src/modules/embed/__tests__/EmbedView.test.tsx +560 -17
  7. package/src/modules/embed/__tests__/embed-config.test.ts +77 -1
  8. package/src/modules/embed/__tests__/mcp-app-view.test.ts +203 -1
  9. package/src/modules/embed/components/EmbedView.tsx +233 -47
  10. package/src/modules/embed/embed-config.ts +126 -2
  11. package/src/modules/embed/embed-host.ts +11 -2
  12. package/src/modules/embed/mount.tsx +1 -0
  13. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +213 -4
  14. package/src/modules/library/__tests__/PluginPage.test.tsx +1 -1
  15. package/src/modules/library/__tests__/SkillPage.test.tsx +10 -0
  16. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  17. package/src/modules/library/components/PluginPage.tsx +2 -1
  18. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  19. package/src/modules/library/components/tool-page/ToolPage.tsx +1 -1
  20. package/src/modules/library/index.ts +18 -0
  21. package/src/modules/library/routes/LibraryRoutes.tsx +17 -1
  22. package/src/modules/library/routes/library-paths.ts +16 -2
  23. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +3 -3
  24. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +39 -32
  25. package/src/modules/secrets-vault/components/SecretsPage.tsx +9 -24
  26. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +111 -8
  27. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +1 -1
  28. package/src/modules/secrets-vault/index.ts +7 -0
  29. package/src/modules/settings/settings-nav-items.tsx +3 -3
  30. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -37
  31. package/src/modules/toolbar/commands/actions.tsx +62 -50
  32. package/src/modules/toolbar/commands/command-menu.ts +37 -3
  33. package/src/modules/toolbar/commands/useCommandShortcuts.ts +29 -76
  34. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +4 -2
  35. package/src/modules/toolbar/components/SearchPalette.tsx +20 -21
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +5 -2
  37. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +242 -103
  38. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +51 -1
  39. package/src/modules/toolbar/search/__tests__/rank.test.ts +7 -3
  40. package/src/modules/workflow/hooks/__tests__/useFileLock.test.tsx +475 -0
  41. package/src/modules/workflow/hooks/__tests__/useFileLock.wire.test.tsx +115 -0
  42. package/src/modules/workflow/hooks/useFileLock.ts +321 -57
  43. package/src/modules/workflow/index.ts +8 -0
  44. package/src/modules/workflow/services/__tests__/lock.api.test.ts +4 -0
  45. package/src/modules/workflow/services/lock.api.ts +28 -9
  46. package/src/modules/workspace/components/FileViewer.tsx +30 -16
  47. package/src/modules/workspace/components/KbPageHeader.tsx +8 -1
  48. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +107 -4
  49. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +12 -0
  50. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +118 -13
  51. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +189 -0
  52. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +9 -0
  53. package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +60 -0
  54. package/src/modules/workspace/components/renderers/frameResizeHandle.ts +116 -0
  55. package/src/modules/workspace/components/renderers/index.ts +6 -0
  56. package/src/modules/workspace/components/renderers/kbGraphLoader.ts +27 -0
  57. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +1 -1
  58. package/src/modules/workspace/components/renderers/rendererSurface.ts +19 -0
  59. package/src/modules/workspace/index.ts +33 -0
@@ -2,8 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { Link } from 'react-router-dom';
3
3
  import { Badge, Banner, Button, Surface, TextField } from '../../../shared/components';
4
4
  import { PageShell } from '../../../shared/components/PageShell';
5
- import { pathForTool } from '../../library/routes/library-paths';
6
- import { ToolLogo } from '../../library/components/ToolLogo';
5
+ import { pathForTool, readOAuthFragment, ToolLogo } from '../../library';
7
6
  import {
8
7
  listSecrets,
9
8
  createOAuthSecret,
@@ -29,22 +28,6 @@ import { ToolSecretsPanel } from './ToolSecretsPanel';
29
28
  * say `Connected` / `Set` / `Needs …` in the same grammar, and everything sits
30
29
  * on the shared components rather than hand-rolled borders.
31
30
  */
32
- /**
33
- * The OAuth-callback outcome carried in the URL fragment
34
- * (`#authorized` / `#error=<message>`), or null when there is none.
35
- * `URLSearchParams` already percent-decodes, so the value is used as-is (a
36
- * second `decodeURIComponent` would corrupt messages containing `%`).
37
- */
38
- function readHashOutcome(): { kind: 'authorized' | 'error'; text: string } | null {
39
- const hash = window.location.hash.replace(/^#/, '');
40
- if (!hash) return null;
41
- const params = new URLSearchParams(hash);
42
- if (params.has('authorized')) return { kind: 'authorized', text: 'Authorization complete.' };
43
- if (params.has('error'))
44
- return { kind: 'error', text: params.get('error') || 'Authorization failed.' };
45
- return null;
46
- }
47
-
48
31
  export function SecretsPage() {
49
32
  const [tools, setTools] = useState<ToolSecrets[]>([]);
50
33
  const [secrets, setSecrets] = useState<SecretSummary[]>([]);
@@ -52,10 +35,12 @@ export function SecretsPage() {
52
35
  /** A refetch is in flight over a list that is already on screen. */
53
36
  const [refreshing, setRefreshing] = useState(false);
54
37
  const [error, setError] = useState<string | null>(null);
55
- // Read ONCE, synchronously, before the fragment is stripped below. Kept in
56
- // its own slot (not the API `error` above) so the initial refresh() — whose
57
- // success path clears the API error — can't race the outcome away.
58
- const [oauthOutcome] = useState(readHashOutcome);
38
+ // The OAuth-callback outcome carried in the fragment (`#authorized` /
39
+ // `#error=<message>`), read ONCE, synchronously, with the Library's reader
40
+ // before the fragment is stripped below. Kept in its own slot (not the API
41
+ // `error` above) so the initial refresh() — whose success path clears the
42
+ // API error — can't race the outcome away.
43
+ const [oauthOutcome] = useState(readOAuthFragment);
59
44
 
60
45
  /**
61
46
  * Which load is allowed to publish. Saving two rows in quick succession
@@ -111,8 +96,8 @@ export function SecretsPage() {
111
96
 
112
97
  // A live API error wins over the (historical) callback outcome; otherwise
113
98
  // the callback error stays visible even after the list load succeeds.
114
- const shownError = error ?? (oauthOutcome?.kind === 'error' ? oauthOutcome.text : null);
115
- const notice = oauthOutcome?.kind === 'authorized' ? oauthOutcome.text : null;
99
+ const shownError = error ?? (oauthOutcome?.kind === 'error' ? oauthOutcome.message : null);
100
+ const notice = oauthOutcome?.kind === 'authorized' ? 'Authorization complete.' : null;
116
101
 
117
102
  const oauthSecrets = secrets.filter((s) => s.kind === 'oauth');
118
103
 
@@ -8,11 +8,12 @@ import { TOOL_CREDENTIALS_STALE_EVENT } from '../../../../core/events';
8
8
  /**
9
9
  * What this page owes the Library.
10
10
  *
11
- * `/connect` is a shell route of its own — no Library is mounted under it — so
12
- * a key entered here has no provider to call. It ANNOUNCES instead, the one
13
- * rule every writing surface in the app follows, and whichever surface is
14
- * holding a catalog picks it up. The rest of the page's behaviour (the agent
15
- * -connect mode, the Finish button) is not what these tests are about.
11
+ * The page sits inside Skills & Tools (`/skills-and-tools/connect`), under the
12
+ * Library's provider, yet it does not call that provider: a key entered here
13
+ * is ANNOUNCED, the one rule every writing surface in the app follows, and the
14
+ * provider — the one behind the sidebar's setup reminder — picks it up. The
15
+ * rest of the page's behaviour (the agent-connect mode, the Finish button) is
16
+ * not what these tests are about.
16
17
  */
17
18
 
18
19
  const connectMock = vi.hoisted(() => ({
@@ -79,7 +80,7 @@ function renderPage() {
79
80
 
80
81
  describe('ConnectToolsPage: telling the Library a credential landed', () => {
81
82
  beforeEach(() => {
82
- window.history.replaceState(null, '', '/connect');
83
+ window.history.replaceState(null, '', '/skills-and-tools/connect');
83
84
  sessionStorage.clear();
84
85
  heard.mockReset();
85
86
  connectMock.getConnectPending.mockReset().mockResolvedValue(pending(false));
@@ -122,7 +123,7 @@ describe('ConnectToolsPage: telling the Library a credential landed', () => {
122
123
  });
123
124
 
124
125
  it('announces an OAuth return, and consumes the fragment', async () => {
125
- window.history.replaceState(null, '', '/connect#authorized');
126
+ window.history.replaceState(null, '', '/skills-and-tools/connect#authorized');
126
127
  renderPage();
127
128
 
128
129
  await waitFor(() => expect(heard).toHaveBeenCalledTimes(1));
@@ -132,7 +133,7 @@ describe('ConnectToolsPage: telling the Library a credential landed', () => {
132
133
  it('announces a failed OAuth return too, and consumes that fragment', async () => {
133
134
  // A refused sign-in is still news: the provider may have revoked what was
134
135
  // there, and the Library's copy predates the browser leaving either way.
135
- window.history.replaceState(null, '', '/connect#error=Nope.');
136
+ window.history.replaceState(null, '', '/skills-and-tools/connect#error=Nope.');
136
137
  renderPage();
137
138
 
138
139
  await waitFor(() => expect(heard).toHaveBeenCalledTimes(1));
@@ -423,3 +424,105 @@ describe('ConnectToolsPage: telling the Library a credential landed', () => {
423
424
  });
424
425
  });
425
426
  });
427
+
428
+ describe('ConnectToolsPage: inside Skills & Tools', () => {
429
+ beforeEach(() => {
430
+ window.history.replaceState(null, '', '/skills-and-tools/connect');
431
+ sessionStorage.clear();
432
+ connectMock.getConnectPending.mockReset().mockResolvedValue(pending(false));
433
+ connectMock.getMcpOAuthRequest.mockReset();
434
+ connectMock.completeMcpOAuth.mockReset();
435
+ });
436
+
437
+ // The link existed because the page had no other way back. The sidebar and
438
+ // the selected tab are that way now, as on every Skills & Tools page.
439
+ it('carries no back link of its own', async () => {
440
+ renderPage();
441
+ expect(await screen.findByRole('heading', { name: 'Connect your tools' })).toBeInTheDocument();
442
+ expect(screen.getByRole('button', { name: /Refresh/ })).toBeInTheDocument();
443
+ expect(screen.queryByRole('link', { name: /Skills & tools/i })).toBeNull();
444
+ expect(screen.queryByText(/‹/)).toBeNull();
445
+ });
446
+
447
+ // The page scrolls as a document inside the Skills & Tools pane, so the
448
+ // title and Refresh would leave the screen on a long list — unless the
449
+ // header sticks to the top of that pane, which it does. jsdom lays nothing
450
+ // out, so what is pinned here is the mechanism: the header is sticky at
451
+ // the top, and the page keeps no scroller of its own that would take the
452
+ // header away from the pane's.
453
+ it('keeps its title and Refresh in reach on a long list: the header sticks to the top of the pane', async () => {
454
+ renderPage();
455
+ const heading = await screen.findByRole('heading', { name: 'Connect your tools' });
456
+ const header = heading.closest('header')!;
457
+ expect(header).toHaveClass('sticky', 'top-0');
458
+ expect(within(header).getByRole('button', { name: /Refresh/ })).toBeInTheDocument();
459
+ // Neither the page's root nor its content carries a scroll region: the
460
+ // layout's pane scrolls, and the sticky header sticks to it.
461
+ const root = header.parentElement!;
462
+ expect(root.className).not.toMatch(/overflow-y-auto|h-full/);
463
+ for (const el of root.querySelectorAll('div')) {
464
+ expect(el.className).not.toMatch(/overflow-y-auto/);
465
+ }
466
+ });
467
+
468
+ it('shows a sign-in that came back to it', async () => {
469
+ window.history.replaceState(null, '', '/skills-and-tools/connect?from=agent#authorized=1');
470
+ renderPage();
471
+ await screen.findByLabelText('API_KEY value');
472
+ expect(
473
+ screen.getByText('Signed in. You can go back to your agent and try again.'),
474
+ ).toBeInTheDocument();
475
+ // The fragment is consumed; the address and its query stay.
476
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe(
477
+ '/skills-and-tools/connect?from=agent',
478
+ );
479
+ });
480
+
481
+ // The page's first load answers right after the fragment is read, and a
482
+ // successful load clears the page's error — which used to wipe a refusal
483
+ // before anyone saw it. Waiting for the list proves the load has landed.
484
+ it('shows a refused sign-in that came back to it, after the list has loaded', async () => {
485
+ window.history.replaceState(null, '', '/skills-and-tools/connect#error=The%20provider%20said%20no.');
486
+ renderPage();
487
+ await screen.findByLabelText('API_KEY value');
488
+ expect(screen.getByRole('alert')).toHaveTextContent('The provider said no.');
489
+ expect(window.location.hash).toBe('');
490
+ });
491
+
492
+ it('says the sign-in failed when the refusal carries no reason', async () => {
493
+ window.history.replaceState(null, '', '/skills-and-tools/connect#error=');
494
+ renderPage();
495
+ await screen.findByLabelText('API_KEY value');
496
+ expect(screen.getByRole('alert')).toHaveTextContent('Authorization failed.');
497
+ });
498
+
499
+ it('keeps agent-connect mode: the per-tool include/skip control, and Finish back to the agent', async () => {
500
+ window.history.replaceState(null, '', '/skills-and-tools/connect?oauth=signed-state');
501
+ connectMock.getMcpOAuthRequest.mockResolvedValue({ clientName: 'Claude', scope: null, resource: null });
502
+ connectMock.completeMcpOAuth.mockResolvedValue('/agent-callback?code=abc');
503
+ renderPage();
504
+
505
+ expect(
506
+ await screen.findByRole('checkbox', {
507
+ name: 'Skip this tool (removes your saved keys and sign-ins for it)',
508
+ }),
509
+ ).toBeInTheDocument();
510
+ const finish = await screen.findByRole('button', { name: 'Finish & return to your agent' });
511
+
512
+ // jsdom does not navigate, so hold the address in a plain object for the
513
+ // click: what Finish writes to it is where the browser would have gone.
514
+ const realLocation = window.location;
515
+ Object.defineProperty(window, 'location', {
516
+ configurable: true,
517
+ value: { ...realLocation, href: realLocation.href },
518
+ });
519
+ try {
520
+ fireEvent.click(finish);
521
+ await waitFor(() => expect(window.location.href).toBe('/agent-callback?code=abc'));
522
+ } finally {
523
+ Object.defineProperty(window, 'location', { configurable: true, value: realLocation });
524
+ }
525
+ expect(connectMock.completeMcpOAuth).toHaveBeenCalledWith('signed-state');
526
+ expect(connectMock.getMcpOAuthRequest).toHaveBeenCalledWith('signed-state');
527
+ });
528
+ });
@@ -191,7 +191,7 @@ async function rowFor(name: string): Promise<HTMLElement> {
191
191
  }
192
192
 
193
193
  beforeEach(() => {
194
- window.history.replaceState(null, '', '/connect');
194
+ window.history.replaceState(null, '', '/skills-and-tools/connect');
195
195
  sessionStorage.clear();
196
196
  // The page is always handed what the server would build FOR THIS READER:
197
197
  // the full catalog, pruned by their read grant. It comes out equal to
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Secrets & connections' public surface: what other modules may mount or call
3
+ * without reaching into this module's files.
4
+ */
5
+
6
+ /** "Connect your tools", mounted by Skills & Tools at `/skills-and-tools/connect`. */
7
+ export { ConnectToolsPage } from './components/ConnectToolsPage';
@@ -124,9 +124,9 @@ export const CORE_MENU_ITEMS: AdminMenuItem[] = [
124
124
  *
125
125
  * The consequence is a rule worth having: a settings page reaches the nav by
126
126
  * having a row, and a settings page with no way to navigate to it is the
127
- * original bug. `/connect` is outside this set for that reason — it is a flow
128
- * page with no row, an OAuth landing target whose agent-connect mode has
129
- * somebody else blocked on a Finish button.
127
+ * original bug. "Connect your tools" is outside this set for that reason — it
128
+ * is a flow page with no row, an OAuth landing target whose agent-connect mode
129
+ * has somebody else blocked on a Finish button — and lives in Skills & Tools.
130
130
  */
131
131
  export const SETTINGS_NAV_PATHS: readonly string[] = CORE_MENU_ITEMS.map(
132
132
  (item) => item.path,
@@ -56,7 +56,7 @@ describe('coreCommandActions', () => {
56
56
 
57
57
  it('offers a member the page verbs, the apps and their own settings', () => {
58
58
  expect(labels(visibleActions(all, ctx()))).toEqual([
59
- 'New page',
59
+ 'Create new page',
60
60
  'Connect your agent',
61
61
  'Go to Knowledge',
62
62
  'Go to Skills & Tools',
@@ -66,7 +66,7 @@ describe('coreCommandActions', () => {
66
66
 
67
67
  it('adds Invite people and the admin settings for an admin', () => {
68
68
  expect(labels(visibleActions(all, ctx({ isAdmin: true })))).toEqual([
69
- 'New page',
69
+ 'Create new page',
70
70
  'Invite people',
71
71
  'Connect your agent',
72
72
  'Go to Knowledge',
@@ -76,9 +76,9 @@ describe('coreCommandActions', () => {
76
76
  ]);
77
77
  });
78
78
 
79
- it('leaves out New page before the workspace knows its folder, and Invite with no dialog to open', () => {
79
+ it('leaves out Create new page before the workspace knows its folder, and Invite with no dialog to open', () => {
80
80
  const shown = labels(visibleActions(all, ctx({ isAdmin: true, createPage: null, invite: null })));
81
- expect(shown).not.toContain('New page');
81
+ expect(shown).not.toContain('Create new page');
82
82
  expect(shown).not.toContain('Invite people');
83
83
  });
84
84
 
@@ -127,12 +127,20 @@ describe('shortcut hints', () => {
127
127
  it('come from the table the shortcuts are bound by, and only for bound commands', () => {
128
128
  const all = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [] } });
129
129
  const hint = (id: string) => all.find((a) => a.id === id)?.shortcut;
130
- expect(hint('new-page')).toEqual(['C']);
131
- expect(hint('go-to:knowledge')).toEqual(['G', 'K']);
132
- expect(hint('go-to:skills-tools')).toEqual(['G', 'S']);
133
- expect(hint('invite')).toBeUndefined();
134
- expect(Object.keys(COMMAND_SHORTCUTS).sort()).toEqual(['go-to:knowledge', 'go-to:skills-tools', 'new-page']);
130
+ expect(hint('new-page')).toEqual({ key: 'c' });
131
+ expect(hint('invite')).toEqual({ key: 'i', shift: true });
132
+ expect(hint('go-to:knowledge')).toEqual({ key: 'k', shift: true });
133
+ expect(hint('go-to:skills-tools')).toEqual({ key: 's', shift: true });
134
+ expect(hint('edit-page')).toBeUndefined();
135
+ expect(hint('connect-agent')).toBeUndefined();
136
+ expect(Object.keys(COMMAND_SHORTCUTS).sort()).toEqual([
137
+ 'go-to:knowledge',
138
+ 'go-to:skills-tools',
139
+ 'invite',
140
+ 'new-page',
141
+ ]);
135
142
  });
143
+
136
144
  });
137
145
 
138
146
  describe('suggestedActions', () => {
@@ -141,12 +149,12 @@ describe('suggestedActions', () => {
141
149
 
142
150
  it('suggests the commonest verbs and the way to the other app', () => {
143
151
  expect(suggest(ctx({ isAdmin: true, onboardingPending: true }))).toEqual([
144
- 'New page',
152
+ 'Create new page',
145
153
  'Invite people',
146
154
  'Connect your agent',
147
155
  'Go to Skills & Tools',
148
156
  ]);
149
- expect(suggest(ctx({ activeAppId: 'skills-tools' }))).toEqual(['New page', 'Go to Knowledge']);
157
+ expect(suggest(ctx({ activeAppId: 'skills-tools' }))).toEqual(['Create new page', 'Go to Knowledge']);
150
158
  });
151
159
  });
152
160
 
@@ -166,31 +174,6 @@ describe('mergeCommandActions / visibleActions', () => {
166
174
  error.mockRestore();
167
175
  });
168
176
 
169
- it('keeps a registry command whose keys collide with bound ones, but drops its shortcut', () => {
170
- const error = vi.spyOn(console, 'error').mockImplementation(() => {});
171
- const withKeys = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [] } });
172
- const extra: CommandAction[] = [
173
- { id: 'clash', label: 'Clash', shortcut: ['c'], visible: () => true, run: vi.fn() },
174
- { id: 'prefix', label: 'Prefix', shortcut: ['G'], visible: () => true, run: vi.fn() },
175
- { id: 'longer', label: 'Longer', shortcut: ['g', 'k', 'x'], visible: () => true, run: vi.fn() },
176
- // Three keys that collide with nothing: still unbindable, so still dropped.
177
- { id: 'too-long', label: 'Too long', shortcut: ['x', 'y', 'z'], visible: () => true, run: vi.fn() },
178
- { id: 'fine', label: 'Fine', shortcut: ['O'], visible: () => true, run: vi.fn() },
179
- { id: 'also-fine', label: 'Also fine', shortcut: ['g', 'o'], visible: () => true, run: vi.fn() },
180
- ];
181
- const merged = mergeCommandActions(withKeys, extra);
182
- const shortcutOf = (id: string) => merged.find((a) => a.id === id)?.shortcut;
183
- expect(merged.map((a) => a.id).slice(-6)).toEqual(['clash', 'prefix', 'longer', 'too-long', 'fine', 'also-fine']);
184
- expect(shortcutOf('clash')).toBeUndefined();
185
- expect(shortcutOf('prefix')).toBeUndefined();
186
- expect(shortcutOf('longer')).toBeUndefined();
187
- expect(shortcutOf('too-long')).toBeUndefined();
188
- expect(shortcutOf('fine')).toEqual(['O']);
189
- expect(shortcutOf('also-fine')).toEqual(['g', 'o']);
190
- expect(error).toHaveBeenCalledTimes(4);
191
- error.mockRestore();
192
- });
193
-
194
177
  it('drops a command whose visible() throws, and keeps the rest', () => {
195
178
  const error = vi.spyOn(console, 'error').mockImplementation(() => {});
196
179
  const broken: CommandAction = {
@@ -202,7 +185,7 @@ describe('mergeCommandActions / visibleActions', () => {
202
185
  run: vi.fn(),
203
186
  };
204
187
  expect(labels(visibleActions(mergeCommandActions(core, [broken]), ctx()))).toEqual([
205
- 'New page',
188
+ 'Create new page',
206
189
  'Connect your agent',
207
190
  ]);
208
191
  error.mockRestore();
@@ -8,7 +8,7 @@ import { WELCOME_PATH } from '../../onboarding/paths';
8
8
 
9
9
  /**
10
10
  * The commands the toolbar's menu can run, beside the pages and items it
11
- * finds: "New page", "Invite people", "Settings: Secrets".
11
+ * finds: "Create new page", "Invite people", "Settings: Secrets".
12
12
  *
13
13
  * A command is DATA plus two functions of a {@link CommandContext}, never a
14
14
  * hook or a component of its own: whether it is offered right now
@@ -52,6 +52,14 @@ export interface CommandContext {
52
52
  onboardingPending: boolean;
53
53
  }
54
54
 
55
+ /** One letter, with or without Shift (see {@link CommandAction.shortcut}). */
56
+ export interface CommandShortcut {
57
+ /** The letter, `a` to `z`; matched without regard to case. */
58
+ key: string;
59
+ /** Held: ⇧K. Not held: K on its own. */
60
+ shift?: boolean;
61
+ }
62
+
55
63
  export interface CommandAction {
56
64
  /** Stable and unique among all commands — it keys the row and the suggestions. */
57
65
  id: string;
@@ -62,16 +70,16 @@ export interface CommandAction {
62
70
  /** Faint text after the label, naming where the command belongs (a distribution's area, say). */
63
71
  group?: string;
64
72
  /**
65
- * The keys that run it outside the menu: `['C']`, or `['G', 'K']` for a
66
- * sequence of two. Shown on the row as its hint AND bound by
67
- * `useCommandShortcuts`, under the same guards as core's, so a hint is
68
- * never a key that does nothing. Core's are filled in from
69
- * {@link COMMAND_SHORTCUTS}. A registry command's shortcut is dropped at
70
- * merge time, hint and all, and said so in the console, when it is longer
71
- * than two keys or would collide with keys already bound — the same keys,
72
- * or a sequence one of them begins: give it other keys.
73
+ * The key that runs it outside the menu: one letter, `a` to `z`, with or
74
+ * without Shift — `{ key: 'c' }`, or `{ key: 'k', shift: true }` for ⇧K.
75
+ * Shown on the row as its hint AND bound by `useCommandShortcuts`, under
76
+ * the same guards as core's, so a hint is never a key that does nothing.
77
+ * Core's are filled in from {@link COMMAND_SHORTCUTS}. A registry
78
+ * command's shortcut is dropped at merge time, hint and all, and said so in
79
+ * the console, when its key is not one letter or is already bound: give it
80
+ * another.
73
81
  */
74
- shortcut?: string[];
82
+ shortcut?: CommandShortcut;
75
83
  /** The row's icon; a generic arrow when absent. */
76
84
  icon?: ReactNode;
77
85
  /** Whether to offer it now. Called on every render of the menu, so keep it cheap. */
@@ -87,8 +95,8 @@ const ICON_SIZE = 15;
87
95
 
88
96
  const NEW_PAGE: CommandAction = {
89
97
  id: 'new-page',
90
- label: 'New page',
91
- keywords: ['create page', 'add page', 'write', 'document', 'note', 'untitled'],
98
+ label: 'Create new page',
99
+ keywords: ['new page', 'create page', 'add page', 'write', 'document', 'note', 'untitled'],
92
100
  icon: <FilePlus size={ICON_SIZE} />,
93
101
  visible: (ctx) => ctx.createPage !== null,
94
102
  run: async (ctx) => {
@@ -143,22 +151,24 @@ export function goToAppActionId(appId: string): string {
143
151
  }
144
152
 
145
153
  /**
146
- * The single-key shortcuts, keyed by the command they run: `C` for New page,
147
- * `G` then `K` for Knowledge, `G` then `S` for Skills & Tools. ONE table,
148
- * read both by `useCommandShortcuts` (which binds the keys) and by the list
149
- * below (which shows them as hints), so a row never advertises a key that
150
- * does nothing. Lower-case is what is matched; the hints upper-case it.
154
+ * The shortcuts, keyed by the command they run: `C` for Create new page, ⇧I
155
+ * for Invite people, ⇧K for Knowledge and ⇧S for Skills & Tools — the two
156
+ * apps of the top bar's toggle. No other command has one. ONE table, read
157
+ * both by `useCommandShortcuts` (which binds the keys) and by the list below
158
+ * (which shows them as hints), so a row never advertises a key that does
159
+ * nothing.
151
160
  */
152
- export const COMMAND_SHORTCUTS: Readonly<Record<string, readonly string[]>> = {
153
- 'new-page': ['c'],
154
- [goToAppActionId('knowledge')]: ['g', 'k'],
155
- [goToAppActionId('skills-tools')]: ['g', 's'],
161
+ export const COMMAND_SHORTCUTS: Readonly<Record<string, CommandShortcut>> = {
162
+ 'new-page': { key: 'c' },
163
+ invite: { key: 'i', shift: true },
164
+ [goToAppActionId('knowledge')]: { key: 'k', shift: true },
165
+ [goToAppActionId('skills-tools')]: { key: 's', shift: true },
156
166
  };
157
167
 
158
168
  /** A core command with its hint from {@link COMMAND_SHORTCUTS}, if it has one. */
159
169
  function withShortcutHint(action: CommandAction): CommandAction {
160
- const keys = COMMAND_SHORTCUTS[action.id];
161
- return keys ? { ...action, shortcut: keys.map((k) => k.toUpperCase()) } : action;
170
+ const shortcut = COMMAND_SHORTCUTS[action.id];
171
+ return shortcut ? { ...action, shortcut } : action;
162
172
  }
163
173
 
164
174
  /**
@@ -233,21 +243,18 @@ export function coreCommandActions({
233
243
  );
234
244
  }
235
245
 
236
- /** A command's keys as `useCommandShortcuts` matches them: lower-cased, space-joined (`g k`); null without a shortcut. */
237
- export function shortcutSequence(action: Pick<CommandAction, 'shortcut'>): string | null {
238
- return action.shortcut && action.shortcut.length > 0 ? action.shortcut.map((k) => k.toLowerCase()).join(' ') : null;
239
- }
240
-
241
246
  /**
242
- * Whether `seq` could not be bound beside `bound`: the same keys, or a
243
- * sequence one of them begins (a bare `g` would swallow `g k`, and `c x`
244
- * would never be reached past `c`).
247
+ * A shortcut as `useCommandShortcuts` matches it: the letter lower-cased,
248
+ * after `shift+` when Shift is held (`c`, `shift+k`). Null without one.
245
249
  */
246
- function shortcutCollides(seq: string, bound: Iterable<string>): boolean {
247
- for (const b of bound) {
248
- if (b === seq || b.startsWith(`${seq} `) || seq.startsWith(`${b} `)) return true;
249
- }
250
- return false;
250
+ export function shortcutId(shortcut: CommandShortcut | undefined): string | null {
251
+ if (!shortcut) return null;
252
+ return `${shortcut.shift ? 'shift+' : ''}${shortcut.key.toLowerCase()}`;
253
+ }
254
+
255
+ /** Whether a shortcut is one a person can press as drawn: one letter, `a` to `z`. */
256
+ function isOneLetter(shortcut: CommandShortcut): boolean {
257
+ return typeof shortcut.key === 'string' && /^[a-z]$/i.test(shortcut.key);
251
258
  }
252
259
 
253
260
  /**
@@ -255,16 +262,16 @@ function shortcutCollides(seq: string, bound: Iterable<string>): boolean {
255
262
  * rather than reordering it. A registry command reusing an id core already
256
263
  * has is dropped (and said so in the console): two rows with one id would
257
264
  * share a DOM id, and the suggestions could not tell them apart. A registry
258
- * command whose keys collide with ones already bound keeps its row and loses
259
- * its shortcut, hint included, so the menu never shows a key that does
260
- * nothing.
265
+ * command whose shortcut is not one letter, or takes a key already bound,
266
+ * keeps its row and loses its shortcut, hint included, so the menu never
267
+ * shows a key that does nothing.
261
268
  */
262
269
  export function mergeCommandActions(
263
270
  core: readonly CommandAction[],
264
271
  extra: readonly CommandAction[],
265
272
  ): CommandAction[] {
266
273
  const ids = new Set(core.map((a) => a.id));
267
- const bound = new Set(core.map(shortcutSequence).filter((s): s is string => s !== null));
274
+ const bound = new Set(core.map((a) => shortcutId(a.shortcut)).filter((s): s is string => s !== null));
268
275
  const merged = [...core];
269
276
  for (const action of extra) {
270
277
  if (ids.has(action.id)) {
@@ -272,21 +279,26 @@ export function mergeCommandActions(
272
279
  continue;
273
280
  }
274
281
  ids.add(action.id);
275
- const seq = shortcutSequence(action);
276
- // Only what `useCommandShortcuts` can bind is kept: one key, or two in
277
- // sequence. A longer one would be drawn as "x then y then z" and never
278
- // fire.
279
- if (seq !== null && seq.split(' ').length > 2) {
280
- console.error(`[commands] the shortcut "${seq}" of ${action.id} is longer than two keys; it is not bound`);
282
+ if (!action.shortcut) {
283
+ merged.push(action);
284
+ continue;
285
+ }
286
+ // Only what `useCommandShortcuts` can bind is kept: one letter, with or
287
+ // without Shift. Anything else would be drawn and never fire.
288
+ if (!isOneLetter(action.shortcut)) {
289
+ console.error(
290
+ `[commands] the shortcut ${JSON.stringify(action.shortcut)} of ${action.id} is not one letter; it is not bound`,
291
+ );
281
292
  merged.push({ ...action, shortcut: undefined });
282
293
  continue;
283
294
  }
284
- if (seq !== null && shortcutCollides(seq, bound)) {
285
- console.error(`[commands] the shortcut "${seq}" of ${action.id} collides with keys already bound; it is not bound`);
295
+ const id = shortcutId(action.shortcut)!;
296
+ if (bound.has(id)) {
297
+ console.error(`[commands] the shortcut "${id}" of ${action.id} is already bound; it is not bound`);
286
298
  merged.push({ ...action, shortcut: undefined });
287
299
  continue;
288
300
  }
289
- if (seq !== null) bound.add(seq);
301
+ bound.add(id);
290
302
  merged.push(action);
291
303
  }
292
304
  return merged;
@@ -310,7 +322,7 @@ export function visibleActions(actions: readonly CommandAction[], ctx: CommandCo
310
322
 
311
323
  /**
312
324
  * What an empty menu offers before anything is typed: a handful of the
313
- * commonest verbs, not the whole list — New page, Invite people (for an
325
+ * commonest verbs, not the whole list — Create new page, Invite people (for an
314
326
  * admin), Connect your agent while that onboarding is open, and a way to the
315
327
  * other app. Drawn from `visible`, so nothing is suggested that is not
316
328
  * offered.
@@ -1,7 +1,8 @@
1
1
  /**
2
- * The command menu's two public facts, for anything outside the toolbar that
2
+ * The command menu's public facts, for anything outside the toolbar that
3
3
  * talks about it or opens it — the Get set up list does both: which keys open
4
- * it on this platform, and a way to open it from a button.
4
+ * it on this platform, and a way to open it from a button. Beside them, how
5
+ * the menu draws its commands' shortcuts on this platform.
5
6
  *
6
7
  * A plain module rather than a context: the palette lives in the toolbar and
7
8
  * the people asking for it (the setup column) sit beside it, not under it, so
@@ -13,7 +14,8 @@
13
14
  * and ONLY to that one. Ctrl+K on a Mac is the text fields' "delete to end of
14
15
  * line", which nobody pressing it there means as "search".
15
16
  */
16
- const APPLE = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
17
+ const isApple = (): boolean => typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
18
+ const APPLE = isApple();
17
19
 
18
20
  /** The keys as drawn: `⌘K` on Apple platforms, `Ctrl K` elsewhere. */
19
21
  export const COMMAND_MENU_SHORTCUT_LABEL = APPLE ? '⌘K' : 'Ctrl K';
@@ -27,6 +29,38 @@ export function isCommandMenuShortcut(e: KeyboardEvent): boolean {
27
29
  return APPLE ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
28
30
  }
29
31
 
32
+ /** A command's shortcut as the menu draws it and says it. */
33
+ export interface ShortcutHint {
34
+ /** The one keycap: `C`; `⇧K` on Apple platforms, `Shift K` elsewhere. */
35
+ label: string;
36
+ /**
37
+ * What a screen reader hears after the row: `C`, `Shift K`. Spoken, not
38
+ * declared with `aria-keyshortcuts`: the row is read while the menu is
39
+ * open, where the key types into the search rather than running it.
40
+ */
41
+ spoken: string;
42
+ }
43
+
44
+ /**
45
+ * How a command's shortcut is shown on the platform the app runs on, read
46
+ * when the menu draws (a suite renders the menu under one user agent, then
47
+ * another), as {@link COMMAND_MENU_SHORTCUT_LABEL} is read once.
48
+ */
49
+ export function shortcutHint(shortcut: { key: string; shift?: boolean }): ShortcutHint {
50
+ const key = shortcut.key.toUpperCase();
51
+ if (!shortcut.shift) return { label: key, spoken: key };
52
+ return { label: isApple() ? `⇧${key}` : `Shift ${key}`, spoken: `Shift ${key}` };
53
+ }
54
+
55
+ /**
56
+ * Every keycap's width on this platform: wide enough for the widest one —
57
+ * `⇧K` on Apple platforms, `Shift K` elsewhere — so the keys line up down the
58
+ * menu, each centred in its cap.
59
+ */
60
+ export function shortcutKeycapWidth(): string {
61
+ return isApple() ? 'w-7' : 'w-14';
62
+ }
63
+
30
64
  const openRequests = new Set<() => void>();
31
65
 
32
66
  /**