@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
@@ -49,6 +49,7 @@ export function mountEmbed(root: HTMLElement, options: MountEmbedOptions): Embed
49
49
  baseUrl: options.baseUrl,
50
50
  token: options.token,
51
51
  openLink: options.openLink ?? null,
52
+ renew: options.renew ?? null,
52
53
  });
53
54
  const reactRoot: Root = createRoot(root);
54
55
  reactRoot.render(
@@ -1,15 +1,14 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
  import { DEFAULT_BRANCH } from '@bevel-software/platform-shared';
3
3
  import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
4
4
  import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
5
- import type { ReactNode } from 'react';
5
+ import { useState, type ReactNode } from 'react';
6
6
  import {
7
7
  WorkspaceContext,
8
8
  type WorkspaceContextValue,
9
9
  } from '../../workspace/state/workspace.context';
10
10
  import { AdminContext } from '../../admin/state/admin.context';
11
11
  import type { LibraryData } from '../hooks/useLibraryData';
12
- import type { ToolSecrets } from '../../secrets-vault/services/tool-secrets.api';
13
12
  import type { PluginSummary } from '../services/plugins.api';
14
13
  import type { ToolPageState } from '../hooks/useToolPage';
15
14
  import { PAGE_HEADER_TESTID } from '../../../shared/theme/header';
@@ -68,7 +67,10 @@ vi.mock('../../access/api', async (importOriginal) => {
68
67
  import { LibraryRoutes } from '../routes/LibraryRoutes';
69
68
  import { withAuth, TEST_PERSONAL_GROUP } from './auth-harness';
70
69
 
71
- const tool = (over: Partial<ToolSecrets>): ToolSecrets => ({
70
+ /** A tool as the catalog carries it — the shape the stubbed data hook answers with, nothing another module exports. */
71
+ type CatalogTool = LibraryData['tools'][number];
72
+
73
+ const tool = (over: Partial<CatalogTool>): CatalogTool => ({
72
74
  slug: 'heyreach',
73
75
  name: 'heyreach',
74
76
  path: 'Plugins/GTM/heyreach.tool',
@@ -579,3 +581,210 @@ describe('LibraryRoutes', () => {
579
581
  expect(screen.queryByTestId('library-card-integration-heyreach')).toBeNull();
580
582
  });
581
583
  });
584
+
585
+ /**
586
+ * "Connect your tools" is a Skills & Tools page: inside the layout, so the
587
+ * sidebar (and, in the shell, the toggle and the selected tab) are on screen
588
+ * with it. The shell's `/connect` redirects here; see `ShellRoutes.test`.
589
+ */
590
+ /**
591
+ * The secrets endpoints "Connect your tools" talks to, answered at the HTTP
592
+ * seam — the page's own services and the shared `authFetch` stay real, so
593
+ * what is pinned is the page as it talks to the server. Anything else that
594
+ * reaches `fetch` here is a mistake, and says so.
595
+ */
596
+ /** What `/api/connect/pending` answers, as JSON on the wire: three lists, shaped by the fixtures below. */
597
+ type ConnectListing = { tools: object[]; oauth: object[]; toolOAuth: object[] };
598
+
599
+ interface SecretsServer {
600
+ /** What `/api/connect/pending` answers. */
601
+ listing: ConnectListing;
602
+ /** Who is asking in agent-connect mode; null answers the lookup with 404. */
603
+ oauthRequest: { clientName: string; scope: null; resource: null } | null;
604
+ /** Every request, in order: method, path and the parsed JSON body. */
605
+ calls: { method: string; path: string; body: unknown }[];
606
+ }
607
+
608
+ function serveSecrets(listing: ConnectListing): SecretsServer {
609
+ const server: SecretsServer = { listing, oauthRequest: null, calls: [] };
610
+ const json = (body: unknown, status = 200) =>
611
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
612
+ vi.stubGlobal(
613
+ 'fetch',
614
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
615
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, 'http://test');
616
+ const method = (init?.method ?? 'GET').toUpperCase();
617
+ const path = url.pathname;
618
+ server.calls.push({ method, path, body: init?.body ? JSON.parse(String(init.body)) : null });
619
+ if (method === 'GET' && path === '/api/connect/pending') return json(server.listing);
620
+ if (method === 'GET' && path === '/api/mcp/oauth/request') {
621
+ return server.oauthRequest ? json(server.oauthRequest) : json({ error: 'Unknown request' }, 404);
622
+ }
623
+ if (method === 'POST' && /^\/api\/secrets\/tools\/[^/]+\/check$/.test(path)) {
624
+ return json({ verdict: { status: 'ok', detail: null, checkedAt: new Date().toISOString() } });
625
+ }
626
+ if ((method === 'PUT' || method === 'DELETE') && /^\/api\/secrets\/tools\/[^/]+\/vars\/[^/]+\/user$/.test(path)) {
627
+ return json({ ok: true });
628
+ }
629
+ throw new Error(`the test server has no answer for ${method} ${path}`);
630
+ }),
631
+ );
632
+ return server;
633
+ }
634
+
635
+ describe('LibraryRoutes — Connect your tools', () => {
636
+ /** heyreach, holding one per-person key that is or is not saved. */
637
+ const keyedTool = (saved: boolean) =>
638
+ tool({
639
+ variables: [
640
+ { name: 'API_KEY', scope: 'user', label: null, key: 'heyreach_API_KEY', adminConfigured: false, userConfigured: saved },
641
+ ],
642
+ });
643
+
644
+ let server: SecretsServer;
645
+
646
+ beforeEach(() => {
647
+ dataMock.useLibraryData.mockReturnValue(CATALOG);
648
+ pluginsMock.listPlugins.mockResolvedValue(PLUGINS);
649
+ teamsMock.listTeams.mockResolvedValue(TEAMS);
650
+ pluginsMock.listJoinRequests.mockResolvedValue([]);
651
+ window.history.replaceState(null, '', '/skills-and-tools/connect');
652
+ sessionStorage.clear();
653
+ server = serveSecrets({
654
+ tools: [
655
+ {
656
+ slug: 'heyreach',
657
+ name: 'heyreach',
658
+ path: 'Plugins/GTM/heyreach.tool',
659
+ type: 'inline',
660
+ canWrite: false,
661
+ variables: [
662
+ { name: 'API_KEY', label: null, key: 'heyreach_API_KEY', scope: 'user', configured: false, ownerOnly: false },
663
+ ],
664
+ },
665
+ ],
666
+ oauth: [],
667
+ toolOAuth: [],
668
+ });
669
+ });
670
+
671
+ afterEach(() => {
672
+ vi.unstubAllGlobals();
673
+ });
674
+
675
+ it('renders the page inside the Skills & Tools layout, with no sidebar row selected', async () => {
676
+ renderAt('/skills-and-tools/connect');
677
+ expect(await screen.findByRole('heading', { name: 'Connect your tools' })).toBeInTheDocument();
678
+ expect(within(main()).getByRole('heading', { name: 'Connect your tools' })).toBeInTheDocument();
679
+ expect(nav()).toBeInTheDocument();
680
+ // The page has no row of its own, so nothing is lit — not even Everything.
681
+ await within(nav()).findByRole('button', { name: /^GTM Team/ });
682
+ for (const row of within(nav()).getAllByRole('button')) {
683
+ expect(row).not.toHaveAttribute('aria-current', 'true');
684
+ }
685
+ expect(pathname()).toBe('/skills-and-tools/connect');
686
+ // The way back is the sidebar now, not a link of its own.
687
+ expect(screen.queryByRole('link', { name: /Skills & tools/i })).toBeNull();
688
+ });
689
+
690
+ it('keeps agent-connect mode, with the same sidebar beside it', async () => {
691
+ server.oauthRequest = { clientName: 'Claude', scope: null, resource: null };
692
+ // The page reads the browser's own address, as the BrowserRouter keeps it.
693
+ window.history.replaceState(null, '', '/skills-and-tools/connect?oauth=signed-state');
694
+ renderAt('/skills-and-tools/connect?oauth=signed-state');
695
+ expect(
696
+ await screen.findByRole('button', { name: 'Finish & return to your agent' }),
697
+ ).toBeInTheDocument();
698
+ expect(nav()).toBeInTheDocument();
699
+ const asked = (vi.mocked(fetch).mock.calls as [RequestInfo | URL, RequestInit?][]).map(([input]) => String(input));
700
+ expect(asked).toContain('/api/mcp/oauth/request?state=signed-state');
701
+ });
702
+
703
+ it("the sidebar's setup reminder opens the page at its own address", async () => {
704
+ dataMock.useLibraryData.mockReturnValue({ ...CATALOG, tools: [keyedTool(false)] });
705
+ renderAt('/skills-and-tools');
706
+ fireEvent.click(await screen.findByRole('button', { name: /1 integration needs setup/ }));
707
+ expect(pathname()).toBe('/skills-and-tools/connect');
708
+ expect(await screen.findByRole('heading', { name: 'Connect your tools' })).toBeInTheDocument();
709
+ });
710
+
711
+ // The sidebar now sits beside the page, so a count that lagged a save
712
+ // would read as a bug. The page's announcement reaches the provider the
713
+ // sidebar reads from; the mock stands in for the real hook's refetch.
714
+ it('a key saved on the page updates the setup reminder without a reload', async () => {
715
+ dataMock.useLibraryData.mockImplementation(() => {
716
+ const [saved, setSaved] = useState(false);
717
+ return { ...CATALOG, tools: [keyedTool(saved)], reload: () => setSaved(true) };
718
+ });
719
+ renderAt('/skills-and-tools/connect');
720
+ expect(await screen.findByRole('button', { name: /1 integration needs setup/ })).toBeInTheDocument();
721
+
722
+ fireEvent.change(await screen.findByLabelText('API_KEY value'), { target: { value: 'k' } });
723
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
724
+
725
+ await waitFor(() => expect(screen.queryByRole('button', { name: /integrations? needs? setup/ })).toBeNull());
726
+ expect(server.calls).toContainEqual({
727
+ method: 'PUT',
728
+ path: '/api/secrets/tools/heyreach/vars/API_KEY/user',
729
+ body: { value: 'k', label: null },
730
+ });
731
+ });
732
+
733
+ // The other direction: unticking a signed-in tool deletes the sign-in, and
734
+ // the reminder has to come back for it — counted, not left at "all set".
735
+ it('a sign-in removed on the page updates the setup reminder without a reload', async () => {
736
+ const signedInTool = (authorized: boolean) =>
737
+ tool({
738
+ variables: [
739
+ {
740
+ name: 'TOKEN',
741
+ scope: 'user',
742
+ label: null,
743
+ key: 'heyreach_TOKEN',
744
+ adminConfigured: true,
745
+ userConfigured: authorized,
746
+ oauth: true,
747
+ authorized,
748
+ },
749
+ ],
750
+ });
751
+ dataMock.useLibraryData.mockImplementation(() => {
752
+ const [signedIn, setSignedIn] = useState(true);
753
+ return { ...CATALOG, tools: [signedInTool(signedIn)], reload: () => setSignedIn(false) };
754
+ });
755
+ server.listing = {
756
+ tools: [],
757
+ oauth: [],
758
+ toolOAuth: [
759
+ {
760
+ slug: 'heyreach',
761
+ varName: 'TOKEN',
762
+ toolName: 'heyreach',
763
+ key: 'heyreach_TOKEN',
764
+ label: null,
765
+ authorized: true,
766
+ needsReauth: false,
767
+ ownerConfigured: true,
768
+ ownerOnly: false,
769
+ },
770
+ ],
771
+ };
772
+ renderAt('/skills-and-tools/connect');
773
+
774
+ const skip = await screen.findByRole('checkbox', {
775
+ name: 'Skip this tool (removes your saved keys and sign-ins for it)',
776
+ });
777
+ expect(screen.queryByRole('button', { name: /integrations? needs? setup/ })).toBeNull();
778
+
779
+ fireEvent.click(skip);
780
+
781
+ await waitFor(() =>
782
+ expect(server.calls).toContainEqual({
783
+ method: 'DELETE',
784
+ path: '/api/secrets/tools/heyreach/vars/TOKEN/user',
785
+ body: null,
786
+ }),
787
+ );
788
+ expect(await screen.findByRole('button', { name: /1 integration needs setup/ })).toBeInTheDocument();
789
+ });
790
+ });
@@ -532,7 +532,7 @@ describe('PluginPage', () => {
532
532
  ),
533
533
  ).toBeInTheDocument();
534
534
  fireEvent.click(screen.getByRole('button', { name: 'Finish setup' }));
535
- await waitFor(() => expect(href()).toBe('/connect'));
535
+ await waitFor(() => expect(href()).toBe('/skills-and-tools/connect'));
536
536
  });
537
537
 
538
538
  it('names a linked skill the members cannot read, above the integrations banner', async () => {
@@ -359,6 +359,7 @@ function harness(
359
359
  element={<SkillPage {...(pageProps ?? {})} />}
360
360
  />
361
361
  <Route path="/workspace/*" element={<NavigatedTo />} />
362
+ <Route path="/skills-and-tools/connect" element={<NavigatedTo />} />
362
363
  </Routes>
363
364
  </LibraryToastProvider>
364
365
  </EventBusContext.Provider>
@@ -419,6 +420,15 @@ beforeEach(() => {
419
420
  });
420
421
 
421
422
  describe('SkillPage', () => {
423
+ // Straight to the page's address inside Skills & Tools — `/connect` is only
424
+ // the redirect kept for links the server hands out.
425
+ it('opens Connect your tools at its own address from the integrations section', async () => {
426
+ renderPage(false);
427
+ expect(await screen.findByText('slack')).toBeInTheDocument();
428
+ fireEvent.click(screen.getByRole('button', { name: /Connect/ }));
429
+ expect(await screen.findByTestId('navigated-to')).toHaveTextContent(/^\/skills-and-tools\/connect$/);
430
+ });
431
+
422
432
  it('loads the skill and shows its name, needed integrations and files', async () => {
423
433
  renderPage(false);
424
434
 
@@ -7,7 +7,7 @@ import { HEADER_COLUMN_TOP } from '../../../shared/theme/header';
7
7
  import { useAdmin } from '../../admin/state/admin.context';
8
8
  import { attentionOf, useLibrary, workspaceHasNoPlugins } from '../state/library-data';
9
9
  import { personalPluginName } from '../utils/personal-plugin';
10
- import { libraryFilterForPath, pathForLibraryFilter } from '../routes/library-paths';
10
+ import { CONNECT_TOOLS_PATH, libraryFilterForPath, pathForLibraryFilter } from '../routes/library-paths';
11
11
  import { EVERYONE_TEAM, filterLibraryItems, pluginsOfItem, type LibraryFilter } from '../utils/status';
12
12
  import { pathForGroupMembers } from '../../admin/components/group-members-path';
13
13
  import { ownedLensOf, pluginEntriesFor } from '../utils/plugin-entries';
@@ -134,7 +134,7 @@ export function LibraryLayout() {
134
134
  <>
135
135
  <IntegrationsSetupReminder
136
136
  count={attentionCount}
137
- onFinishSetup={() => navigate('/connect')}
137
+ onFinishSetup={() => navigate(CONNECT_TOOLS_PATH)}
138
138
  />
139
139
  <PullRequestsForMe />
140
140
  </>
@@ -8,6 +8,7 @@ import { attentionOf, useLibrary, type LibraryItem } from '../state/library-data
8
8
  import { useLibraryToast } from '../state/toast.context';
9
9
  import { isInPlugin, withLinkHealth } from '../utils/status';
10
10
  import {
11
+ CONNECT_TOOLS_PATH,
11
12
  decodePluginSegment,
12
13
  pathForPlugin,
13
14
  pathForPluginsIndex,
@@ -492,7 +493,7 @@ export function PluginPage() {
492
493
  : 'integrations need setup: connect them'
493
494
  } to unblock this plugin's skills.`}
494
495
  </span>{' '}
495
- <Button variant="outline" size="tiny" onClick={() => navigate('/connect')}>
496
+ <Button variant="outline" size="tiny" onClick={() => navigate(CONNECT_TOOLS_PATH)}>
496
497
  Finish setup
497
498
  </Button>
498
499
  </Banner>
@@ -45,7 +45,7 @@ import { useCrFileDiffs } from '../../../change-requests/hooks/useCrFileDiffs';
45
45
  import { useDefaultBranchFile, useFileOnBranch } from '../../../change-requests/hooks/useFileOnBranch';
46
46
  import { useLibrary } from '../../state/library-data';
47
47
  import { useLibraryToast } from '../../state/toast.context';
48
- import { libraryHomeForItemPath, urlForSkillFile } from '../../routes/library-paths';
48
+ import { CONNECT_TOOLS_PATH, libraryHomeForItemPath, urlForSkillFile } from '../../routes/library-paths';
49
49
  import { changeAuthorName, formatWhen } from '../../../change-requests/utils/author';
50
50
  import { ownersTextOf, pluginLabel } from '../../utils/plugin-summary';
51
51
  import { neededToolsFor, toolStatus } from '../../utils/status';
@@ -737,7 +737,7 @@ export function SkillPage({
737
737
  />
738
738
  )}
739
739
 
740
- <IntegrationsSection needed={needed} onConnect={() => navigate('/connect')} />
740
+ <IntegrationsSection needed={needed} onConnect={() => navigate(CONNECT_TOOLS_PATH)} />
741
741
 
742
742
  {skill && (
743
743
  <SharedViaPlugins
@@ -29,7 +29,7 @@ import { NameWithBadges } from '../NameWithBadges';
29
29
  * ROUTE and not a bigger dialog is the OAuth round-trip: signing in leaves the
30
30
  * app entirely and comes back through the provider and our callback, which can
31
31
  * only return the browser to a URL. A dialog has no URL, so the old flow could
32
- * only ever land you back on `/connect`, away from what you were doing.
32
+ * only ever land you back on Connect your tools, away from what you were doing.
33
33
  *
34
34
  * Three signals gate what renders, and roles are none of them:
35
35
  * - read access to the `.tool` — implied by the tool appearing in the secrets
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Skills & Tools' public surface: what other modules may link to or call
3
+ * without reaching into the Library's files.
4
+ */
5
+
6
+ /** Where "Connect your tools" lives; every in-app link to it uses this. */
7
+ export { CONNECT_TOOLS_PATH } from './routes/library-paths';
8
+ /**
9
+ * A tool's page, by slug — where a tool sign-in started from a tool page
10
+ * returns to. The server accepts any same-origin path as a return target
11
+ * (`isSafeReturnPath`); this is the one the pages that start a sign-in hand
12
+ * it, so the person lands back on the tool they were looking at.
13
+ */
14
+ export { pathForTool } from './routes/library-paths';
15
+ /** A tool's mark, as the gallery draws it, for any surface that lists tools. */
16
+ export { ToolLogo, type ToolLogoProps } from './components/ToolLogo';
17
+ /** The outcome a tool sign-in carries back in the fragment, read once on arrival. */
18
+ export { readOAuthFragment, type OAuthFragmentOutcome } from './utils/oauth-fragment';
@@ -9,7 +9,15 @@ import { PersonalPluginPage } from '../components/PersonalPluginPage';
9
9
  import { TeamRoute } from '../components/TeamRoute';
10
10
  import { WelcomePage } from '../../onboarding/components/WelcomePage';
11
11
  import { WorkspaceItemRoute } from './WorkspaceItemRoute';
12
- import { decodePluginSegment, LIBRARY_ROOT, pathForPlugin, urlForLibraryItem, urlForSkillFile } from './library-paths';
12
+ import { ConnectToolsPage } from '../../secrets-vault';
13
+ import {
14
+ CONNECT_TOOLS_SEGMENT,
15
+ decodePluginSegment,
16
+ LIBRARY_ROOT,
17
+ pathForPlugin,
18
+ urlForLibraryItem,
19
+ urlForSkillFile,
20
+ } from './library-paths';
13
21
 
14
22
  /**
15
23
  * The Skills & Tools surface — everything under `/skills-and-tools/*`.
@@ -51,6 +59,14 @@ export function LibraryRoutes() {
51
59
  the pill, the Get set up list and by URL. */}
52
60
  <Route path="welcome" element={<WelcomePage />} />
53
61
 
62
+ {/* Connect your tools — inside the layout for the same reason as
63
+ the welcome page: the sidebar, its toggle and the selected tab
64
+ come with it. It has no sidebar row, so none is lit. Both of
65
+ its modes live here, agent-connect (`?oauth=`) included; the
66
+ shell's `/connect` redirects here for every link the server
67
+ hands out. */}
68
+ <Route path={CONNECT_TOOLS_SEGMENT} element={<ConnectToolsPage />} />
69
+
54
70
  <Route path="owned" element={<LibraryPage filter={{ kind: 'owned' }} />} />
55
71
 
56
72
  {/* `yours` is a PLUGIN page, not a gallery filter — the items in no
@@ -23,6 +23,16 @@ import { PERSONAL_PLUGIN_NAME } from '../utils/personal-plugin';
23
23
  /** The Library's mount point inside the shell (`CORE_APPS` `skills-tools`). */
24
24
  export const LIBRARY_ROOT = '/skills-and-tools';
25
25
 
26
+ /**
27
+ * "Connect your tools" — a Skills & Tools page, inside `LibraryLayout` like the
28
+ * welcome page, so it gets the sidebar, its toggle and the selected tab. The
29
+ * route (`LibraryRoutes`) is the segment, the shell's `/connect` redirect and
30
+ * every in-app link use the full path — both from here. The server keeps
31
+ * handing out `/connect`, which redirects here.
32
+ */
33
+ export const CONNECT_TOOLS_SEGMENT = 'connect';
34
+ export const CONNECT_TOOLS_PATH = `${LIBRARY_ROOT}/${CONNECT_TOOLS_SEGMENT}`;
35
+
26
36
  /**
27
37
  * What the sidebar should show as selected for a path. `null` on the pages that
28
38
  * are not a filtered view of the catalog — the item pages and the plugin
@@ -173,8 +183,12 @@ export function isLibraryLocation(pathname: string): boolean {
173
183
  * The LEGACY route for one tool — now a redirect to the canonical workspace
174
184
  * URL (`urlForItemFile`), preserving any `#…` the OAuth callback appended.
175
185
  * Still built in three places, deliberately: the Secrets and Connect pages
176
- * link it by slug (they don't carry the repo path), and the tool page's own
177
- * OAuth `returnTo` MUST stay this shape — the server validates it.
186
+ * link it by slug (they don't carry the repo path), and the tool page hands
187
+ * it to the OAuth start as its `returnTo`, so a sign-in started from a tool
188
+ * page lands back on that tool. The server accepts any safe same-origin path
189
+ * there (`isSafeReturnPath`: one leading `/`, no `#`, no backslash or line
190
+ * break, at most 512 characters) — this shape is the one these pages choose,
191
+ * not the one the server requires.
178
192
  *
179
193
  * Returns the BARE path: never append `#…` to it. The OAuth start route rejects
180
194
  * a `returnTo` containing `#`, and the callback is what puts the fragment on.
@@ -871,7 +871,7 @@ describe('GetStartedColumn: where New page writes', () => {
871
871
  expect(ask).toHaveAttribute('href', claudePromptUrl(FIRST_PAGE_PROMPT));
872
872
  });
873
873
 
874
- it('offers no New page in the command menu, and C does nothing, when there is nowhere to write', async () => {
874
+ it('offers no Create new page in the command menu, and C does nothing, when there is nowhere to write', async () => {
875
875
  access.writable = new Set();
876
876
  const createFile = vi.fn(async () => {});
877
877
  const user = userEvent.setup();
@@ -879,7 +879,7 @@ describe('GetStartedColumn: where New page writes', () => {
879
879
  await user.keyboard('c');
880
880
  expect(createFile).not.toHaveBeenCalled();
881
881
  await user.keyboard('{Control>}k{/Control}');
882
- expect(screen.queryByRole('option', { name: /^New page/ })).not.toBeInTheDocument();
882
+ expect(screen.queryByRole('option', { name: /^Create new page/ })).not.toBeInTheDocument();
883
883
  expect(screen.getByRole('option', { name: 'Connect your agent' })).toBeInTheDocument();
884
884
  await user.keyboard('{Escape}');
885
885
 
@@ -888,7 +888,7 @@ describe('GetStartedColumn: where New page writes', () => {
888
888
  rerender(columnUi({ withPalette: true, createFile, files: [...STARTER_TREE, `${SALES}/.gitkeep`] }));
889
889
  await settleRecheck();
890
890
  await user.keyboard('{Control>}k{/Control}');
891
- expect(screen.getByRole('option', { name: /^New page/ })).toBeInTheDocument();
891
+ expect(screen.getByRole('option', { name: /^Create new page/ })).toBeInTheDocument();
892
892
  await user.keyboard('{Escape}');
893
893
  await user.keyboard('c');
894
894
  await waitFor(() =>
@@ -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 { cn } from '../../../lib/utils';
5
- import { LIBRARY_ROOT, pathForTool } from '../../library/routes/library-paths';
6
- import { ToolLogo } from '../../library/components/ToolLogo';
5
+ import { pathForTool, readOAuthFragment, ToolLogo } from '../../library';
7
6
  import { startOAuth } from '../services/secrets.api';
8
7
  import { setUserVar, setAdminVar, deleteUserVar, setOAuthClientSecret } from '../services/tool-secrets.api';
9
8
  import { SavedKeyProbeResult } from '../probe/SavedKeyProbeResult';
@@ -84,7 +83,19 @@ export function ConnectToolsPage() {
84
83
  /** A refetch is in flight over a list that is already on screen. */
85
84
  const [refreshing, setRefreshing] = useState(false);
86
85
  const [error, setError] = useState<string | null>(null);
87
- const [notice, setNotice] = useState<string | null>(null);
86
+ // The outcome of a sign-in that came back to this page, read ONCE from the
87
+ // fragment on arrival with the Library's reader (the contract the tool page
88
+ // follows: synchronously, before the effect below strips it).
89
+ const [outcome] = useState(readOAuthFragment);
90
+ // "Signed in", not "Connected": the sign-in landing here proves a token was
91
+ // issued, not that a call with it will succeed.
92
+ const [notice] = useState<string | null>(
93
+ outcome?.kind === 'authorized' ? 'Signed in. You can go back to your agent and try again.' : null,
94
+ );
95
+ // A sign-in's refusal. Its own state, like `notice`, because the first load
96
+ // answers moments later and a successful load clears `error` — which used to
97
+ // wipe this before anyone saw it.
98
+ const [returnError] = useState<string | null>(outcome?.kind === 'error' ? outcome.message : null);
88
99
  // Agent-connect mode: the signed authorization state + who is asking.
89
100
  const [agentState, setAgentState] = useState<string | null>(null);
90
101
  const [agentName, setAgentName] = useState<string | null>(null);
@@ -140,6 +151,7 @@ export function ConnectToolsPage() {
140
151
  }, []);
141
152
 
142
153
  useEffect(() => {
154
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the first load; refresh sets state once it answers
143
155
  void refresh();
144
156
  }, [refresh]);
145
157
 
@@ -148,6 +160,7 @@ export function ConnectToolsPage() {
148
160
  const fromUrl = new URLSearchParams(window.location.search).get('oauth');
149
161
  if (fromUrl) {
150
162
  sessionStorage.setItem(MCP_OAUTH_STATE_KEY, fromUrl);
163
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the query is read once, on arrival
151
164
  setAgentState(fromUrl);
152
165
  } else {
153
166
  setAgentState(sessionStorage.getItem(MCP_OAUTH_STATE_KEY));
@@ -174,28 +187,22 @@ export function ConnectToolsPage() {
174
187
  };
175
188
  }, [agentState]);
176
189
 
177
- // Surface the OAuth-callback outcome carried in the URL fragment (same contract
178
- // the Secrets page uses — the callback lands on whichever page started it).
190
+ // A sign-in came back to this page (the callback lands on whichever page
191
+ // started it): the fragment it carried is stripped, now that it has been
192
+ // read, and the Library is told. Whichever way the round-trip went, a
193
+ // provider has just had its say about a sign-in this page did not perform
194
+ // itself — so the Library's view of the tool is from before the browser
195
+ // left.
179
196
  useEffect(() => {
180
- const hash = window.location.hash.replace(/^#/, '');
181
- if (!hash) return;
182
- const params = new URLSearchParams(hash);
183
- // "Signed in", not "Connected": the sign-in landing here proves a token was
184
- // issued, not that a call with it will succeed.
185
- if (params.has('authorized')) setNotice('Signed in. You can go back to your agent and try again.');
186
- else if (params.has('error')) setError(params.get('error') || 'Authorization failed.');
187
- if (params.has('authorized') || params.has('error')) {
188
- window.history.replaceState(null, '', window.location.pathname + window.location.search);
189
- // Whichever way the round-trip went, a provider has just had its say
190
- // about a sign-in this page did not perform itself — so the Library's
191
- // view of the tool is from before the browser left.
192
- announceToolCredentialsChanged();
193
- }
194
- }, []);
197
+ if (!outcome) return;
198
+ window.history.replaceState(null, '', window.location.pathname + window.location.search);
199
+ announceToolCredentialsChanged();
200
+ }, [outcome]);
195
201
 
196
202
  const onAuthorize = async (id: string) => {
197
203
  try {
198
204
  const url = await startOAuth(id);
205
+ // eslint-disable-next-line react-hooks/immutability -- leaving for the provider is the point
199
206
  window.location.href = url;
200
207
  } catch (err) {
201
208
  setError(err instanceof Error ? err.message : String(err));
@@ -205,6 +212,7 @@ export function ConnectToolsPage() {
205
212
  const onAuthorizeTool = async (slug: string, varName: string) => {
206
213
  try {
207
214
  const url = await startToolOAuth(slug, varName);
215
+ // eslint-disable-next-line react-hooks/immutability -- leaving for the provider is the point
208
216
  window.location.href = url;
209
217
  } catch (err) {
210
218
  setError(err instanceof Error ? err.message : String(err));
@@ -297,18 +305,12 @@ export function ConnectToolsPage() {
297
305
  const nothingToDo =
298
306
  !loading && tools.length === 0 && oauth.length === 0 && toolOAuth.length === 0;
299
307
 
308
+ // A document, like every Skills & Tools page: `LibraryLayout`'s pane is the
309
+ // scroller. The header sticks to the top of that pane, so the title and
310
+ // Refresh stay in reach down a long list instead of scrolling away with it.
300
311
  return (
301
- <div className="flex h-full flex-col bg-canvas text-ink">
302
- <header className="flex shrink-0 items-center gap-3 border-b border-line px-8 py-4">
303
- {/* The one page that had NO way back: it is reached from the library's
304
- "Finish setup" and from tool pages, and stranded everyone it
305
- helped. The Library is where every one of those journeys starts. */}
306
- <Link
307
- to={LIBRARY_ROOT}
308
- className="rounded-xs text-detail text-ink-muted hover:text-ink"
309
- >
310
- {'‹ Skills & tools'}
311
- </Link>
312
+ <div className="flex flex-col bg-canvas text-ink">
313
+ <header className="sticky top-0 z-10 flex shrink-0 items-center gap-3 border-b border-line bg-canvas px-8 py-4">
312
314
  <h1 className="text-strong font-semibold text-ink">Connect your tools</h1>
313
315
  {/* Quiet, like the refetch a save triggers. A loud one drops the page
314
316
  to "Loading…", which unmounts the row holding the verdict of the
@@ -326,7 +328,7 @@ export function ConnectToolsPage() {
326
328
  </Button>
327
329
  </header>
328
330
 
329
- <div className="flex-1 overflow-y-auto px-8 py-6">
331
+ <div className="px-8 py-6">
330
332
  <div className="max-w-2xl">
331
333
  {agentMode && (
332
334
  <Surface tone="surface" radius="xl" elevation="card" padded className="mb-4">
@@ -360,6 +362,11 @@ export function ConnectToolsPage() {
360
362
  {error}
361
363
  </Banner>
362
364
  )}
365
+ {returnError && (
366
+ <Banner role="alert" tone="danger" className="mb-3">
367
+ {returnError}
368
+ </Banner>
369
+ )}
363
370
  {notice && (
364
371
  <Banner role="status" tone="ok" className="mb-3">
365
372
  {notice}