@bevel-software/platform-core-frontend 0.33.0 → 0.35.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 (67) hide show
  1. package/package.json +2 -2
  2. package/src/lib/__tests__/api.test.ts +28 -1
  3. package/src/lib/api.ts +4 -2
  4. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  5. package/src/modules/access/api.ts +27 -8
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/access/index.ts +1 -1
  8. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  9. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  10. package/src/modules/admin/index.ts +1 -1
  11. package/src/modules/admin/services/groups.api.ts +11 -1
  12. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  13. package/src/modules/agents/components/ConnectAsChoice.tsx +88 -0
  14. package/src/modules/agents/connect-as.ts +15 -0
  15. package/src/modules/agents/index.ts +5 -0
  16. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  17. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  18. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +16 -2
  19. package/src/modules/audit/components/AuditLogPage.tsx +11 -0
  20. package/src/modules/audit/services/audit.api.ts +5 -0
  21. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  22. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  23. package/src/modules/auth/components/AccountPage.tsx +8 -2
  24. package/src/modules/auth/index.ts +1 -1
  25. package/src/modules/auth/services/account.api.ts +18 -2
  26. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  27. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  28. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  29. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  30. package/src/modules/library/__tests__/ToolVarRow.test.tsx +51 -5
  31. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  32. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  33. package/src/modules/library/components/tool-page/ToolVarRow.tsx +22 -14
  34. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  35. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  36. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  37. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  38. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +122 -2
  39. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  40. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +45 -4
  41. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +127 -12
  42. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  43. package/src/modules/workspace/components/FileViewer.tsx +1 -1
  44. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +58 -8
  45. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  46. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  47. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  48. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  49. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  50. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  51. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  52. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  53. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  54. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  55. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  56. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  57. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  58. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  59. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  60. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  61. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  62. package/src/modules/workspace/index.ts +21 -2
  63. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  64. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  65. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +32 -48
  66. package/src/modules/workspace/utils/fileTree.ts +1 -1
  67. package/src/modules/workspace/utils/treeConfirm.ts +24 -28
@@ -1,4 +1,4 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
1
+ import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
2
2
  import { useContext } from 'react';
3
3
  import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
4
4
  import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
@@ -34,7 +34,9 @@ const apiMock = vi.hoisted(() => ({
34
34
  * callback the pane only reaches through an HTML page's frame (Open in the
35
35
  * platform). The pane itself renders as it always does.
36
36
  */
37
- const paneProps = vi.hoisted(() => ({ last: null as null | { onOpenInPlatform?: () => void } }));
37
+ const paneProps = vi.hoisted(() => ({
38
+ last: null as null | { onOpenInPlatform?: () => void; linkHome?: { path: string; branch: string } },
39
+ }));
38
40
  vi.mock('../components/skill-page/SkillFilePane', async (importOriginal) => {
39
41
  const real = await importOriginal<typeof import('../components/skill-page/SkillFilePane')>();
40
42
  return {
@@ -88,24 +90,53 @@ vi.mock('../../pr/services/pr-detail.api', () => ({ fetchPrDetail: apiMock.fetch
88
90
  vi.mock('../../pr/services/pr-approvals.api', () => ({ approvePrFile: apiMock.approvePrFile }));
89
91
 
90
92
  // Keep the markdown pipeline (mermaid etc.) out of this test — the stub renders
91
- // the raw source so assertions can see the body text, plus two probes for the
92
- // wiring the page hands the view: a click on a percent-encoded link, and what
93
+ // the raw source so assertions can see the body text, plus probes for the
94
+ // wiring the page hands the view: a click on a link (another file, and a
95
+ // section of this one), where the page says such a link leads, and what
93
96
  // the image resolver answers for a picture beside the file.
94
97
  vi.mock('../../workspace/components/renderers/KbMarkdownView', () => ({
95
98
  KbMarkdownView: ({
96
99
  source,
97
100
  onOpenFile,
101
+ fileLinkTarget,
102
+ onOpenNodeId,
103
+ nodeIdLinkTarget,
98
104
  resolveImage,
99
105
  }: {
100
106
  source: string;
101
107
  onOpenFile: (href: string) => void;
108
+ fileLinkTarget?: (href: string) => unknown;
109
+ onOpenNodeId?: (id: string) => void;
110
+ nodeIdLinkTarget?: (id: string) => unknown;
102
111
  resolveImage?: (src: string) => unknown;
103
112
  }) => (
104
113
  <div data-testid="md-view">
105
114
  {source}
115
+ <h2 id="steps">Steps</h2>
106
116
  <button type="button" onClick={() => onOpenFile('Some%20File.md')}>
107
117
  link-probe
108
118
  </button>
119
+ <button type="button" onClick={() => onOpenFile('SKILL.md#steps')}>
120
+ section-probe
121
+ </button>
122
+ <button type="button" onClick={() => onOpenNodeId?.('newsletter#steps')}>
123
+ self-id-probe
124
+ </button>
125
+ <button type="button" onClick={() => onOpenNodeId?.('plan-node#goal')}>
126
+ other-id-probe
127
+ </button>
128
+ <span data-testid="other-id-target-probe">
129
+ {JSON.stringify(nodeIdLinkTarget ? nodeIdLinkTarget('plan-node#goal') : 'no-target')}
130
+ </span>
131
+ <span data-testid="self-id-target-probe">
132
+ {JSON.stringify(nodeIdLinkTarget ? nodeIdLinkTarget('newsletter#steps') : 'no-target')}
133
+ </span>
134
+ <span data-testid="link-target-probe">
135
+ {JSON.stringify(fileLinkTarget ? fileLinkTarget('Some%20File.md') : 'no-target')}
136
+ </span>
137
+ <span data-testid="section-target-probe">
138
+ {JSON.stringify(fileLinkTarget ? fileLinkTarget('SKILL.md#steps') : 'no-target')}
139
+ </span>
109
140
  <span data-testid="image-probe">
110
141
  {JSON.stringify(resolveImage ? resolveImage('./assets/shot.png') : 'no-resolver')}
111
142
  </span>
@@ -385,11 +416,13 @@ function harness(
385
416
  routerState?: Record<string, unknown>,
386
417
  pageProps?: { provisional?: boolean },
387
418
  workspaceValue: WorkspaceContextValue = workspace,
419
+ /** The fragment the page's address arrives with, e.g. `#steps`. */
420
+ hash = '',
388
421
  ) {
389
422
  return (
390
423
  <MemoryRouter
391
424
  initialEntries={[
392
- { pathname: '/skills-and-tools/skills/newsletter', state: routerState ?? null },
425
+ { pathname: '/skills-and-tools/skills/newsletter', hash, state: routerState ?? null },
393
426
  ]}
394
427
  >
395
428
  <AuthContext.Provider value={auth}>
@@ -430,6 +463,27 @@ allowed-tools: [slack_post_message]
430
463
  Collect the news and draft the letter.`;
431
464
  const RAW_BRANCH = RAW_MAIN.replace('draft the letter', 'ship the letter');
432
465
 
466
+ /**
467
+ * The node id of the file in the pane, as the backend answers it for the
468
+ * default branch (`resolve-path`): SKILL.md is the node `newsletter`, and
469
+ * no other file of the skill is a node. Every other request goes to the real
470
+ * fetch, as it always has.
471
+ */
472
+ let resolvePathSpy: MockInstance<typeof fetch>;
473
+ beforeEach(() => {
474
+ const realFetch = globalThis.fetch;
475
+ resolvePathSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
476
+ const url = String(input);
477
+ if (!url.includes('/resolve-path?')) return realFetch(input, init);
478
+ return url.includes(encodeURIComponent('knowledge-base/Skills/newsletter/SKILL.md'))
479
+ ? new Response(JSON.stringify({ id: 'newsletter' }), { status: 200 })
480
+ : new Response('{}', { status: 404 });
481
+ });
482
+ });
483
+ afterEach(() => {
484
+ resolvePathSpy.mockRestore();
485
+ });
486
+
433
487
  beforeEach(() => {
434
488
  apiMock.getSkill.mockReset().mockResolvedValue(skillDetail);
435
489
  apiMock.getSkillFile.mockReset().mockResolvedValue('watchlist:\n - topic: AI');
@@ -476,15 +530,29 @@ describe('SkillPage', () => {
476
530
  expect(await screen.findByTestId('navigated-to')).toHaveTextContent(/^\/skills-and-tools\/connect$/);
477
531
  });
478
532
 
479
- it("opens a page of the skill on the Knowledge file page, not back on this page, for Open in the platform", async () => {
480
- renderPage(true);
481
- await settled();
482
- expect(paneProps.last?.onOpenInPlatform).toBeTypeOf('function');
483
- act(() => paneProps.last!.onOpenInPlatform!());
484
- // The file's own address, with the state that makes the item route show
485
- // the file route rather than this skill page again.
486
- expect(await screen.findByTestId('navigated-to')).toHaveTextContent(/^\/workspace\/[^/]+\/knowledge-base\/Skills\/newsletter\/SKILL\.md$/);
487
- expect(screen.getByTestId('navigated-raw-file')).toHaveTextContent('true');
533
+ it("opens a page of the skill on the Knowledge file page in a new tab, not back on this page, for Open in the platform", async () => {
534
+ const open = vi
535
+ .spyOn(window, 'open')
536
+ .mockImplementation(() => ({ opener: window }) as unknown as Window);
537
+ try {
538
+ renderPage(true);
539
+ await settled();
540
+ expect(paneProps.last?.onOpenInPlatform).toBeTypeOf('function');
541
+ act(() => paneProps.last!.onOpenInPlatform!());
542
+ // The file page's own address on the default branch — the query is what
543
+ // makes the item route show the file route rather than this skill page
544
+ // again, since a new tab carries no router state.
545
+ expect(open).toHaveBeenCalledTimes(1);
546
+ expect(open).toHaveBeenCalledWith(
547
+ `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/SKILL.md?as=file`,
548
+ '_blank',
549
+ );
550
+ // And this tab stayed on the skill page.
551
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
552
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
553
+ } finally {
554
+ open.mockRestore();
555
+ }
488
556
  });
489
557
 
490
558
  /**
@@ -1574,18 +1642,155 @@ describe('SkillPage: deciding on a change', () => {
1574
1642
  * is under test is what the PAGE hands the view.
1575
1643
  */
1576
1644
  describe('SkillPage: links and images in the file', () => {
1577
- it('opens a percent-encoded link as the file it names, on the default branch', async () => {
1578
- // The drift this fixes: the page used to resolve the href undecoded, so a
1579
- // link written `Some File.md` opened `Some%20File.md`, a file that is not there.
1645
+ const SOME_FILE_URL = `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/Some%20File.md`;
1646
+
1647
+ it('opens a link to another file in a new tab, as the file it names, on the default branch', async () => {
1648
+ // Decoded: the page used to resolve the href undecoded, so a link written
1649
+ // `Some File.md` opened `Some%20File.md`, a file that is not there. And a
1650
+ // NEW TAB: a link inside a file never navigates away from it. The git
1651
+ // status names another branch, so the default branch is the page's doing.
1652
+ const open = vi
1653
+ .spyOn(window, 'open')
1654
+ .mockImplementation(() => ({ opener: window }) as unknown as Window);
1655
+ try {
1656
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1657
+ ...git,
1658
+ status: { ...git.status!, branch: 'alice/draft' },
1659
+ });
1660
+ await settled();
1661
+ fireEvent.click(screen.getByRole('button', { name: 'link-probe' }));
1662
+ expect(open).toHaveBeenCalledTimes(1);
1663
+ expect(open).toHaveBeenCalledWith(SOME_FILE_URL, '_blank');
1664
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1665
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1666
+ } finally {
1667
+ open.mockRestore();
1668
+ }
1669
+ });
1670
+
1671
+ it("hands the view each link's target: another file a new tab, this file's section this tab", async () => {
1580
1672
  renderPage(false);
1581
1673
  await settled();
1582
- fireEvent.click(screen.getByRole('button', { name: 'link-probe' }));
1583
- const target = await screen.findByTestId('navigated-to');
1584
- expect(target.textContent).toMatch(
1585
- new RegExp(
1586
- `^/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/Some(%20| )File\\.md$`,
1587
- ),
1588
- );
1674
+ // The same answer the click follows, so the anchor's href, target and rel
1675
+ // agree with it (a middle-click goes where the click goes).
1676
+ expect(JSON.parse(screen.getByTestId('link-target-probe').textContent ?? 'null')).toEqual({
1677
+ href: SOME_FILE_URL,
1678
+ newTab: true,
1679
+ });
1680
+ expect(JSON.parse(screen.getByTestId('section-target-probe').textContent ?? 'null')).toEqual({
1681
+ href: '/skills-and-tools/skills/newsletter#steps',
1682
+ newTab: false,
1683
+ });
1684
+ });
1685
+
1686
+ it('follows a link to a section of the file on screen by scrolling to its heading, in this tab', async () => {
1687
+ const open = vi.spyOn(window, 'open');
1688
+ // The page's address has no heading scroll of its own, so the click is
1689
+ // what scrolls: the heading the fragment names comes into view, and the
1690
+ // page neither opens a tab nor navigates.
1691
+ const original = Element.prototype.scrollIntoView;
1692
+ const scrolled: string[] = [];
1693
+ Element.prototype.scrollIntoView = function (this: Element) {
1694
+ scrolled.push(this.id);
1695
+ };
1696
+ try {
1697
+ renderPage(false);
1698
+ await settled();
1699
+ fireEvent.click(screen.getByRole('button', { name: 'section-probe' }));
1700
+ expect(scrolled).toEqual(['steps']);
1701
+ expect(open).not.toHaveBeenCalled();
1702
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1703
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1704
+ } finally {
1705
+ open.mockRestore();
1706
+ Element.prototype.scrollIntoView = original;
1707
+ }
1708
+ });
1709
+
1710
+ it("follows an id-link to this skill's own heading by scrolling the pane, in this tab", async () => {
1711
+ const open = vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
1712
+ const original = Element.prototype.scrollIntoView;
1713
+ const scrolled: string[] = [];
1714
+ Element.prototype.scrollIntoView = function (this: Element) {
1715
+ scrolled.push(this.id);
1716
+ };
1717
+ try {
1718
+ renderPage(false);
1719
+ await settled();
1720
+ // The anchor's own answer agrees: a section of this page, not a new tab.
1721
+ await waitFor(() =>
1722
+ expect(JSON.parse(screen.getByTestId('self-id-target-probe').textContent ?? 'null')).toEqual({
1723
+ href: '/skills-and-tools/skills/newsletter#steps',
1724
+ newTab: false,
1725
+ }),
1726
+ );
1727
+ fireEvent.click(screen.getByRole('button', { name: 'self-id-probe' }));
1728
+ expect(scrolled).toEqual(['steps']);
1729
+ expect(open).not.toHaveBeenCalled();
1730
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1731
+ // Another node is still a new tab.
1732
+ fireEvent.click(screen.getByRole('button', { name: 'other-id-probe' }));
1733
+ expect(open).toHaveBeenCalledWith(`/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`, '_blank');
1734
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1735
+ } finally {
1736
+ open.mockRestore();
1737
+ Element.prototype.scrollIntoView = original;
1738
+ }
1739
+ });
1740
+
1741
+ // The pane renders the default branch's file whatever is checked out, so
1742
+ // an id in it names a node there: with a draft checked out, the click and
1743
+ // the anchor both open the default branch's node, not the draft's.
1744
+ it("opens another node on the default branch, where the file was read, while a draft is checked out", async () => {
1745
+ const open = vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
1746
+ try {
1747
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1748
+ ...git,
1749
+ status: { ...git.status!, branch: 'alice/draft' },
1750
+ });
1751
+ await settled();
1752
+ fireEvent.click(screen.getByRole('button', { name: 'other-id-probe' }));
1753
+ expect(open).toHaveBeenCalledTimes(1);
1754
+ expect(open).toHaveBeenCalledWith(`/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`, '_blank');
1755
+ expect(JSON.parse(screen.getByTestId('other-id-target-probe').textContent ?? 'null')).toEqual({
1756
+ href: `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`,
1757
+ newTab: true,
1758
+ });
1759
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1760
+ } finally {
1761
+ open.mockRestore();
1762
+ }
1763
+ });
1764
+
1765
+ // A section link's own address — where a middle-click or a modified click
1766
+ // on it goes — is this page plus the heading. Arriving there scrolls to it,
1767
+ // so the new tab lands where the plain click does.
1768
+ it('scrolls to the heading its address names when it arrives with a fragment', async () => {
1769
+ const original = Element.prototype.scrollIntoView;
1770
+ const scrolled: string[] = [];
1771
+ Element.prototype.scrollIntoView = function (this: Element) {
1772
+ scrolled.push(this.id);
1773
+ };
1774
+ try {
1775
+ libraryMock.value = libraryValue(false, [], []);
1776
+ render(harness(makeFakeBus(), git, undefined, undefined, workspace, '#steps'));
1777
+ await settled();
1778
+ await waitFor(() => expect(scrolled).toContain('steps'));
1779
+ } finally {
1780
+ Element.prototype.scrollIntoView = original;
1781
+ }
1782
+ });
1783
+
1784
+ it("names the file's real home for an HTML page's links: its workspace path, on the default branch", async () => {
1785
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1786
+ ...git,
1787
+ status: { ...git.status!, branch: 'alice/draft' },
1788
+ });
1789
+ await settled();
1790
+ expect(paneProps.last?.linkHome).toEqual({
1791
+ path: 'knowledge-base/Skills/newsletter/SKILL.md',
1792
+ branch: DEFAULT_BRANCH,
1793
+ });
1589
1794
  });
1590
1795
 
1591
1796
  it("serves a relative image from the default branch's workspace, under the skill folder", async () => {
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen, fireEvent, waitFor } from '@testing-library/react';
3
- import type { ToolVarStatus } from '../../secrets-vault/services/tool-secrets.api';
2
+ import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
3
+ import type { ToolVarStatus } from '../../secrets-vault';
4
4
 
5
5
  /**
6
6
  * The per-variable state matrix, one case per row of the spec table.
@@ -12,16 +12,21 @@ import type { ToolVarStatus } from '../../secrets-vault/services/tool-secrets.ap
12
12
  * clobber the discovered provider).
13
13
  */
14
14
 
15
+ // The row reaches Secrets & connections through that module's entry, so the
16
+ // mock sits on the entry too — the same surface, with the rest of the module
17
+ // left as it is — never on the files behind it.
15
18
  const secretsMock = vi.hoisted(() => ({
16
19
  setAdminVar: vi.fn(),
17
20
  setUserVar: vi.fn(),
18
21
  deleteAdminVar: vi.fn(),
19
22
  setOAuthClientSecret: vi.fn(),
20
23
  }));
21
- vi.mock('../../secrets-vault/services/tool-secrets.api', () => secretsMock);
22
-
23
24
  const connectMock = vi.hoisted(() => ({ startToolOAuth: vi.fn() }));
24
- vi.mock('../../secrets-vault/services/connect.api', () => connectMock);
25
+ vi.mock('../../secrets-vault', async (importOriginal) => ({
26
+ ...(await importOriginal<typeof import('../../secrets-vault')>()),
27
+ ...secretsMock,
28
+ ...connectMock,
29
+ }));
25
30
 
26
31
  // External navigation behind a spy-able module — never assign
27
32
  // window.location.href in a test.
@@ -236,7 +241,48 @@ describe('ToolVarRow: oauth', () => {
236
241
  expect(screen.getByRole('button', { name: 'Replace client secret' })).toBeInTheDocument();
237
242
  });
238
243
 
244
+ it('offers a writer Replace client secret while not signed in, and it opens the client-secret editor', async () => {
245
+ const { onChanged } = renderRow(signin({ authorized: false }), { canWrite: true, setupKind: 'oauth-manual' });
246
+ expect(screen.getByRole('button', { name: 'Sign in' })).toBeInTheDocument();
247
+ expect(screen.queryByRole('button', { name: 'Set client secret' })).toBeNull();
248
+ fireEvent.click(screen.getByRole('button', { name: 'Replace client secret' }));
249
+
250
+ const input = screen.getByLabelText('Client secret for SIGNIN');
251
+ expect(input).toHaveAttribute('type', 'password');
252
+ fireEvent.change(input, { target: { value: 'cs_new' } });
253
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
254
+ await waitFor(() =>
255
+ expect(secretsMock.setOAuthClientSecret).toHaveBeenCalledWith('github', 'SIGNIN', 'cs_new'),
256
+ );
257
+ await waitFor(() => expect(onChanged).toHaveBeenCalled());
258
+ });
259
+
260
+ it('offers a writer Replace client secret beside Sign in again', () => {
261
+ renderRow(signin({ authorized: true, needsReauth: true }), { canWrite: true, setupKind: 'oauth-manual' });
262
+ expect(screen.getByRole('button', { name: 'Sign in again' })).toBeInTheDocument();
263
+ expect(screen.getByRole('button', { name: 'Replace client secret' })).toBeInTheDocument();
264
+ });
265
+
266
+ it('shows a reader who cannot write the tool Sign in only, in every state', () => {
267
+ renderRow(signin({ authorized: false }), { canWrite: false, setupKind: 'oauth-manual' });
268
+ expect(screen.getByRole('button', { name: 'Sign in' })).toBeInTheDocument();
269
+ expect(screen.queryByRole('button', { name: /client secret/ })).toBeNull();
270
+ cleanup();
271
+ renderRow(signin({ authorized: true }), { canWrite: false, setupKind: 'oauth-manual' });
272
+ expect(screen.queryByRole('button', { name: /client secret/ })).toBeNull();
273
+ cleanup();
274
+ renderRow(signin({ authorized: true, needsReauth: true }), { canWrite: false, setupKind: 'oauth-manual' });
275
+ expect(screen.queryByRole('button', { name: /client secret/ })).toBeNull();
276
+ });
277
+
239
278
  it('never shows a client-secret affordance for oauth-auto, even to a writer', () => {
279
+ renderRow(signin({ authorized: false }), { canWrite: true, setupKind: 'oauth-auto' });
280
+ expect(screen.queryByRole('button', { name: /client secret/ })).toBeNull();
281
+ cleanup();
282
+ renderRow(signin({ authorized: true, needsReauth: true }), { canWrite: true, setupKind: 'oauth-auto' });
283
+ expect(screen.queryByRole('button', { name: /client secret/ })).toBeNull();
284
+ cleanup();
285
+
240
286
  renderRow(signin({ authorized: true }), { canWrite: true, setupKind: 'oauth-auto' });
241
287
  expect(screen.queryByRole('button', { name: 'Replace client secret' })).toBeNull();
242
288
 
@@ -1,10 +1,16 @@
1
- import type { ReactNode } from 'react';
1
+ import { useEffect, useRef, type ReactNode } from 'react';
2
2
  import '../../../change-requests/change-requests.css';
3
3
  import { FilePaneCard } from '../../../workspace/components/FilePaneCard';
4
4
  import { KbMarkdownView } from '../../../workspace/components/renderers/KbMarkdownView';
5
5
  import type { KbImageResolver } from '../../../workspace/components/renderers/kbMarkdownPipeline';
6
6
  import { HtmlRenderer } from '../../../workspace/components/renderers/HtmlRenderer';
7
- import { OpenPageInPlatformContext, PageToolsContext } from '../../../workspace';
7
+ import {
8
+ OpenPageInPlatformContext,
9
+ PageLinkHomeContext,
10
+ PageToolsContext,
11
+ scrollToHeading,
12
+ type KbLinkTarget,
13
+ } from '../../../workspace';
8
14
  import type { DiffLine } from '../../../change-requests';
9
15
 
10
16
  /** The pane never writes — editing goes through the page's Edit / Propose. */
@@ -25,12 +31,31 @@ interface SkillFilePaneProps {
25
31
  actions?: ReactNode;
26
32
  /** Sits between the bar and the body: the "your suggestions are inline" strip. */
27
33
  notice?: ReactNode;
28
- /** Follow a relative link out of rendered markdown. */
29
- onOpenLink?(href: string): void;
30
- /** Resolve a bare `[text](node-id)` link — same contract as `KbMarkdownView`. */
31
- onOpenNodeId?(id: string): void;
34
+ /**
35
+ * Follow a link out of rendered markdown. `scrollToSection` takes this
36
+ * file to one of its own headings (`#steps`), for a link to a section of
37
+ * the file on screen: the page's address has no heading scroll of its own.
38
+ */
39
+ onOpenLink?(href: string, scrollToSection: (hash: string) => void): void;
40
+ /** Where a file link leads, for its anchor — same contract as `KbMarkdownView`. */
41
+ fileLinkTarget?(href: string): KbLinkTarget | null;
42
+ /**
43
+ * Resolve a bare `[text](node-id)` link — same contract as `KbMarkdownView`,
44
+ * plus `scrollToSection` as for `onOpenLink`, for a link to this file's node.
45
+ */
46
+ onOpenNodeId?(id: string, scrollToSection: (hash: string) => void): void;
47
+ /** Where an id-link leads, for its anchor — same contract as `KbMarkdownView`. */
48
+ nodeIdLinkTarget?(id: string): KbLinkTarget | null;
32
49
  /** Heading deep-link builder; present ⇒ headings get the copy-anchor button. */
33
50
  headingLink?(slug: string): string;
51
+ /**
52
+ * The fragment the page's address arrived with (`#steps`), or empty. The
53
+ * page's address has no heading scroll of its own, so the pane scrolls a
54
+ * rendered markdown file to the heading it names — which is what makes a
55
+ * section link's own address (a middle-click on it, a copied heading link)
56
+ * land where the click does.
57
+ */
58
+ sectionHash?: string;
34
59
  /** Image source resolver, same contract as `KbMarkdownView`; absent ⇒ plain `<img>` tags. */
35
60
  resolveImage?: KbImageResolver;
36
61
  /**
@@ -47,6 +72,11 @@ interface SkillFilePaneProps {
47
72
  * i.e. while `pagePath` is absent.
48
73
  */
49
74
  onOpenInPlatform?(): void;
75
+ /**
76
+ * The file an HTML page's links resolve against — its workspace path and
77
+ * the branch it was read from — since `file` is relative to the skill.
78
+ */
79
+ linkHome?: { path: string; branch: string };
50
80
  }
51
81
 
52
82
  /**
@@ -67,12 +97,21 @@ export function SkillFilePane({
67
97
  actions,
68
98
  notice,
69
99
  onOpenLink,
100
+ fileLinkTarget,
70
101
  onOpenNodeId,
102
+ nodeIdLinkTarget,
71
103
  headingLink,
104
+ sectionHash,
72
105
  resolveImage,
73
106
  pagePath,
74
107
  onOpenInPlatform,
108
+ linkHome,
75
109
  }: SkillFilePaneProps) {
110
+ const markdownRef = useRef<HTMLDivElement | null>(null);
111
+ const showsMarkdown = raw !== null && !suggestion && file.endsWith('.md');
112
+ useEffect(() => {
113
+ if (showsMarkdown && sectionHash) scrollToHeading(markdownRef.current, sectionHash);
114
+ }, [showsMarkdown, sectionHash, file]);
76
115
  return (
77
116
  <FilePaneCard file={file} actions={actions} notice={notice} className="mt-4">
78
117
  {raw === null ? (
@@ -85,14 +124,21 @@ export function SkillFilePane({
85
124
  // id-link resolution, heading copy-anchors. `scroll={false}`
86
125
  // because the library page is the scroller — a nested scrollbox
87
126
  // here would trap the wheel inside the pane.
127
+ <div ref={markdownRef}>
88
128
  <KbMarkdownView
89
129
  source={raw}
90
- onOpenFile={(href) => onOpenLink?.(href)}
91
- onOpenNodeId={onOpenNodeId}
130
+ onOpenFile={(href) => onOpenLink?.(href, (hash) => scrollToHeading(markdownRef.current, hash))}
131
+ fileLinkTarget={fileLinkTarget}
132
+ onOpenNodeId={
133
+ onOpenNodeId &&
134
+ ((id) => onOpenNodeId(id, (hash) => scrollToHeading(markdownRef.current, hash)))
135
+ }
136
+ nodeIdLinkTarget={nodeIdLinkTarget}
92
137
  headingLink={headingLink}
93
138
  resolveImage={resolveImage}
94
139
  scroll={false}
95
140
  />
141
+ </div>
96
142
  ) : /\.html?$/i.test(file) ? (
97
143
  // The same sandboxed preview the Knowledge viewer gives `.html` — a
98
144
  // skill's bundled template (a deck, a report shell) is meant to be
@@ -103,7 +149,9 @@ export function SkillFilePane({
103
149
  <div className="h-[70vh]">
104
150
  <PageToolsContext.Provider value={pagePath ? { pagePath } : null}>
105
151
  <OpenPageInPlatformContext.Provider value={onOpenInPlatform ?? null}>
106
- <HtmlRenderer content={raw} filePath={file} readOnly onSave={NOOP_SAVE} />
152
+ <PageLinkHomeContext.Provider value={linkHome ?? null}>
153
+ <HtmlRenderer content={raw} filePath={file} readOnly onSave={NOOP_SAVE} />
154
+ </PageLinkHomeContext.Provider>
107
155
  </OpenPageInPlatformContext.Provider>
108
156
  </PageToolsContext.Provider>
109
157
  </div>
@@ -18,7 +18,7 @@ import {
18
18
  useFocusHandoff,
19
19
  } from '../../../../shared/components';
20
20
  import { useAuth } from '../../../auth';
21
- import { useWorkspace, kbFileUrl, resolveKbHref, openExternalHref, useNodeIdNav, useWorkspaceImageResolver } from '../../../workspace';
21
+ import { useWorkspace, kbFileUrl, useFileNav, useFileNodeId, useNodeIdNav, useWorkspaceImageResolver } from '../../../workspace';
22
22
  import { useGit } from '../../../git';
23
23
  import { FileHistoryPanel } from '../../../git/components/FileHistoryPanel';
24
24
  import { cancelPullRequest } from '../../../pr';
@@ -106,7 +106,8 @@ export function SkillPage({
106
106
  const detail = useSkillDetail(name);
107
107
  // The same id-link resolver the Knowledge renderer uses — a `[text](node-id)`
108
108
  // link inside a skill file navigates to that node, not to a dead span.
109
- const { openNodeId } = useNodeIdNav();
109
+ const { openNodeId, nodeIdTarget } = useNodeIdNav();
110
+ const { openLink, linkTarget, openFilePage } = useFileNav();
110
111
 
111
112
  const [selectedState, setSelected] = useState('SKILL.md');
112
113
  const selected = activeFile ?? selectedState;
@@ -477,26 +478,59 @@ export function SkillPage({
477
478
  const editorBase = !canEditDirectly && ownCr ? ownBranchBase : rawOnMain;
478
479
 
479
480
  /**
480
- * Follow a link out of the rendered file. The same grammar as the Knowledge
481
- * view (`resolveKbHref`): the destination is decoded, so a link to
482
- * `Some File.md` opens `Some File.md` and not `Some%20File.md`; an absolute
483
- * app URL keeps its own branch; anything else opens on the default branch,
484
- * where skills live.
481
+ * Follow a link out of the rendered file — the Knowledge view's rule, from
482
+ * the same hook (`useFileNav().openLink`): the destination is decoded, an
483
+ * absolute app URL keeps its own branch, an external one opens in a new
484
+ * tab, another file of the knowledge base opens in a NEW TAB and this page
485
+ * stays where it is, and a link to this file's own sections moves only the
486
+ * fragment. A relative link resolves on the default branch, where skills
487
+ * live, whatever is checked out. `fileLinkTarget` is the same answer for the
488
+ * anchor to carry, so a middle-click goes where the click does.
489
+ *
490
+ * A link to a section of this file scrolls the pane to that heading
491
+ * (`scrollToSection`, from the pane) and leaves this page's address alone:
492
+ * the skill page has no heading scroll on its address, so moving the
493
+ * fragment there would change the URL and nothing on screen.
485
494
  */
486
495
  const openLinkInEditor = useCallback(
487
- (href: string) => {
488
- if (!fileWorkspacePath) return;
489
- const target = resolveKbHref(href, { basePath: fileWorkspacePath, kbDirName });
490
- // Same rule as `openLink`: the anchor's default was cancelled to get
491
- // here, so an external destination has nobody left to open it.
492
- if (target?.kind === 'external') {
493
- openExternalHref(href);
494
- return;
496
+ (href: string, scrollToSection: (hash: string) => void) => {
497
+ if (fileWorkspacePath) {
498
+ openLink(href, fileWorkspacePath, { homeBranch: DEFAULT_BRANCH, onSection: scrollToSection });
495
499
  }
496
- if (target?.kind !== 'workspace') return;
497
- navigate(kbFileUrl(target.branch ?? DEFAULT_BRANCH, target.path) + target.hash);
498
500
  },
499
- [fileWorkspacePath, kbDirName, navigate],
501
+ [fileWorkspacePath, openLink],
502
+ );
503
+ /**
504
+ * An HTML page's links resolve against its real home — the workspace path
505
+ * and the default branch — not `active`, which names the file relative to
506
+ * the skill.
507
+ */
508
+ const pageLinkHome = useMemo(
509
+ () => (fileWorkspacePath ? { path: fileWorkspacePath, branch: DEFAULT_BRANCH } : undefined),
510
+ [fileWorkspacePath],
511
+ );
512
+ const fileLinkTarget = useCallback(
513
+ (href: string) => (fileWorkspacePath ? linkTarget(href, fileWorkspacePath, DEFAULT_BRANCH) : null),
514
+ [fileWorkspacePath, linkTarget],
515
+ );
516
+ /**
517
+ * An id-link follows the same rule, told which node is on screen — the id
518
+ * of the file in the pane, on the default branch it was read from — so a
519
+ * link to this node's own heading (`[Steps](newsletter#steps)`) scrolls
520
+ * the pane like a section link, instead of opening this skill again in a
521
+ * new tab. This page's address is not the node's id URL, so the hook could
522
+ * not tell from the address. Any other id names a node on the default
523
+ * branch too, where this file was read from, whatever is checked out.
524
+ */
525
+ const ownNodeId = useFileNodeId(fileWorkspacePath, DEFAULT_BRANCH);
526
+ const openNodeIdInFile = useCallback(
527
+ (idOrLink: string, scrollToSection: (hash: string) => void) =>
528
+ openNodeId(idOrLink, ownNodeId, { homeBranch: DEFAULT_BRANCH, onSection: scrollToSection }),
529
+ [openNodeId, ownNodeId],
530
+ );
531
+ const nodeIdLinkTarget = useCallback(
532
+ (idOrLink: string) => nodeIdTarget(idOrLink, ownNodeId, DEFAULT_BRANCH),
533
+ [nodeIdTarget, ownNodeId],
500
534
  );
501
535
 
502
536
  /**
@@ -836,7 +870,13 @@ export function SkillPage({
836
870
  raw={raw}
837
871
  suggestion={null}
838
872
  onOpenLink={openLinkInEditor}
839
- onOpenNodeId={openNodeId}
873
+ fileLinkTarget={fileLinkTarget}
874
+ onOpenNodeId={openNodeIdInFile}
875
+ nodeIdLinkTarget={nodeIdLinkTarget}
876
+ // A section link's own address (a modified click on it, a copied
877
+ // heading link) carries the heading as its fragment: arriving with
878
+ // one scrolls the pane to it.
879
+ sectionHash={location.hash}
840
880
  headingLink={headingLink}
841
881
  // No workspace yet means no base to resolve against: images render
842
882
  // as plain tags, exactly as before the resolver existed.
@@ -847,15 +887,15 @@ export function SkillPage({
847
887
  // consent card, never the skill-relative tab name.
848
888
  pagePath={fileWorkspacePath ? fileRepoPath : undefined}
849
889
  // The renderer's own target for Open in the platform, which it
850
- // offers only to a page mounted without tools. The URL alone would
890
+ // offers only to a page mounted without tools: the Knowledge file
891
+ // page, in a new tab, as the page asked from inside itself
892
+ // (`openFilePage`, the Knowledge view's own). The plain URL would
851
893
  // route straight back here (every file under a skill's folder IS
852
- // the skill page); `rawFile` asks the item route for the file route
853
- // itself, as the plugin page's file links do.
894
+ // the skill page); the file-page URL asks for the file route.
854
895
  onOpenInPlatform={
855
- fileWorkspacePath
856
- ? () => navigate(kbFileUrl(DEFAULT_BRANCH, fileWorkspacePath), { state: { rawFile: true } })
857
- : undefined
896
+ fileWorkspacePath ? () => openFilePage(fileWorkspacePath, DEFAULT_BRANCH) : undefined
858
897
  }
898
+ linkHome={pageLinkHome}
859
899
  /*
860
900
  * ONE action, decided by the ACL. An `Edit` used to sit beside
861
901
  * `Propose changes` for EVERYONE and jump to the Knowledge editor —