@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
@@ -23,6 +23,8 @@ import { AgentInstructionsCard } from './AgentInstructionsCard';
23
23
  import { CONNECT_TOOLS_PATH } from '../../library';
24
24
  import { CoworkSetupSteps } from './CoworkSetupSteps';
25
25
  import { useAdmin } from '../../admin';
26
+ import { connectedAsLabel, listAgentChoices, useConnectAsChoice } from '../../agents';
27
+ import { ConnectAsChoice } from '../../agents/components/ConnectAsChoice';
26
28
  import {
27
29
  type ExternalApiKeySummary,
28
30
  type MintedExternalApiKey,
@@ -96,6 +98,10 @@ export function ExternalAgentAccessPage() {
96
98
  const [loadError, setLoadError] = useState<string | null>(null);
97
99
 
98
100
  const [label, setLabel] = useState('');
101
+ // "Connect as" for a new key: Everything unless an agent is picked. Until
102
+ // the agents answer, a key would be minted as Everything by default; when
103
+ // they could not be loaded, an Everything key waits to be confirmed.
104
+ const connectAs = useConnectAsChoice();
99
105
  const [creating, setCreating] = useState(false);
100
106
  const [createError, setCreateError] = useState<string | null>(null);
101
107
 
@@ -128,15 +134,34 @@ export function ExternalAgentAccessPage() {
128
134
  void refresh();
129
135
  }, [refresh]);
130
136
 
137
+ // The agents a key may be minted as. A failure costs only the choice —
138
+ // Everything is always on offer — and is shown, not passed off as none.
139
+ const settleConnectAs = connectAs.settle;
140
+ useEffect(() => {
141
+ let cancelled = false;
142
+ listAgentChoices().then(
143
+ (agents) => {
144
+ if (!cancelled) settleConnectAs({ agents });
145
+ },
146
+ () => {
147
+ if (!cancelled) settleConnectAs({ agents: [], failed: true });
148
+ },
149
+ );
150
+ return () => {
151
+ cancelled = true;
152
+ };
153
+ }, [settleConnectAs]);
154
+
131
155
  async function handleCreate() {
132
156
  const trimmed = label.trim();
133
- if (trimmed.length === 0 || trimmed.length > MAX_LABEL_LEN || creating) return;
157
+ if (trimmed.length === 0 || trimmed.length > MAX_LABEL_LEN || creating || !connectAs.mayConnect) return;
134
158
  setCreating(true);
135
159
  setCreateError(null);
136
160
  try {
137
- const minted = await createExternalApiKey(trimmed);
161
+ const minted = await createExternalApiKey(trimmed, connectAs.value);
138
162
  setReveal(minted);
139
163
  setLabel('');
164
+ connectAs.setValue(null);
140
165
  // Optimistic-ish: refresh the list so the new row shows up underneath
141
166
  // the reveal modal.
142
167
  void refresh();
@@ -172,7 +197,7 @@ export function ExternalAgentAccessPage() {
172
197
  }
173
198
 
174
199
  const trimmed = label.trim();
175
- const canSubmit = trimmed.length > 0 && trimmed.length <= MAX_LABEL_LEN && !creating;
200
+ const canSubmit = trimmed.length > 0 && trimmed.length <= MAX_LABEL_LEN && !creating && connectAs.mayConnect;
176
201
 
177
202
  // Surface the keys that matter: active keys first (most-recently-used at the
178
203
  // top, never-used ones last among the active), with disconnected keys sunk
@@ -535,6 +560,14 @@ export function ExternalAgentAccessPage() {
535
560
  {creating ? 'Creating…' : 'Create key'}
536
561
  </button>
537
562
  </div>
563
+ <ConnectAsChoice
564
+ agents={connectAs.agents}
565
+ value={connectAs.value}
566
+ disabled={creating}
567
+ hint="What the key loads. An agent narrows it to the tools, skills and plugins its configuration lists, and only those you may read."
568
+ onChange={connectAs.setValue}
569
+ unavailable={connectAs.unavailable}
570
+ />
538
571
  {createError && (
539
572
  <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
540
573
  {createError}
@@ -575,7 +608,15 @@ export function ExternalAgentAccessPage() {
575
608
  <div className="flex-1 min-w-0">
576
609
  <div className="font-medium truncate">{k.label}</div>
577
610
  <div className="text-[11px] text-ink-muted">
578
- Created {formatRelative(k.createdAt)} · Last used {formatRelative(k.lastUsedAt)}
611
+ {/* Only a key made as an agent says so; Everything is what a key
612
+ is unless it says otherwise, and needs no tag. */}
613
+ {k.agentPath && (
614
+ <>
615
+ <span title={k.agentPath}>As {connectedAsLabel(k.agentPath)}</span> ·{' '}
616
+ </>
617
+ )}
618
+ Created{' '}
619
+ {formatRelative(k.createdAt)} · Last used {formatRelative(k.lastUsedAt)}
579
620
  {/* A key an admin took is not one you can reconnect — say so,
580
621
  or people try. Your own disconnect keeps its word. */}
581
622
  {revoked &&
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { fireEvent, render, screen, within } from '@testing-library/react';
2
+ import { act, fireEvent, render, screen, within } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
4
  import { MemoryRouter, Route, Routes } from 'react-router-dom';
5
5
  import { ExternalAgentAccessPage } from '../ExternalAgentAccessPage';
@@ -22,7 +22,8 @@ import { GITHUB_LINK_KIND, configureMarketplaceGitUrl } from '../../../../shared
22
22
  * regression cases below name all six.
23
23
  */
24
24
 
25
- const { listMock, createMock, instructionsMock, facadeMock, registrationMock, adminState } = vi.hoisted(() => ({
25
+ const { listMock, createMock, instructionsMock, facadeMock, registrationMock, adminState, agentChoicesMock } = vi.hoisted(() => ({
26
+ agentChoicesMock: vi.fn(),
26
27
  listMock: vi.fn(),
27
28
  createMock: vi.fn(),
28
29
  instructionsMock: vi.fn(),
@@ -33,22 +34,38 @@ const { listMock, createMock, instructionsMock, facadeMock, registrationMock, ad
33
34
  adminState: { isAdmin: false },
34
35
  }));
35
36
 
36
- // Only the hook is replaced. `AdminContext` itself stays real, because the
37
- // instructions card below reads the context directly rather than through the
38
- // hook; a whole-module mock left it undefined and every case here threw.
39
- vi.mock('../../../admin/state/admin.context', async (importOriginal) => ({
40
- ...(await importOriginal<typeof import('../../../admin/state/admin.context')>()),
37
+ // The other modules this page reaches, replaced at their entries: that is
38
+ // where the page imports them from, and the one surface a mock may stand in
39
+ // for. Only the hook is replaced on `admin`; `AdminContext` itself stays real,
40
+ // because the instructions card below reads the context directly rather than
41
+ // through the hook; a whole-module mock left it undefined and every case here
42
+ // threw.
43
+ vi.mock('../../../admin', async (importOriginal) => ({
44
+ ...(await importOriginal<typeof import('../../../admin')>()),
41
45
  useAdmin: () => ({ isAdmin: adminState.isAdmin }),
42
46
  }));
43
47
 
44
- // The registration state the Cowork drawer reads, and the admin credentials
45
- // endpoint this page must never call. Mocked, or the component reaches for
46
- // the real endpoints over the network.
47
- vi.mock('../../../settings/services/github-facade.api', () => ({
48
- fetchGitHubFacade: facadeMock,
48
+ // The registration state the Cowork drawer reads.
49
+ vi.mock('../../../settings', async (importOriginal) => ({
50
+ ...(await importOriginal<typeof import('../../../settings')>()),
49
51
  fetchMarketplaceRegistration: registrationMock,
50
52
  }));
51
53
 
54
+ // The admin credentials endpoint this page must never call. It is reached
55
+ // inside the settings module, by `ClaudeConnectionCard`, which the toolbar's
56
+ // registration steps import by file rather than through the entry, so the
57
+ // guard sits on the file too until that import moves.
58
+ vi.mock('../../../settings/services/github-facade.api', async (importOriginal) => ({
59
+ ...(await importOriginal<typeof import('../../../settings/services/github-facade.api')>()),
60
+ fetchGitHubFacade: facadeMock,
61
+ }));
62
+
63
+ // The agents a key may be minted as ("Connect as").
64
+ vi.mock('../../../agents', async (importOriginal) => ({
65
+ ...(await importOriginal<typeof import('../../../agents')>()),
66
+ listAgentChoices: agentChoicesMock,
67
+ }));
68
+
52
69
  vi.mock('../../services/external-api-keys.api', () => ({
53
70
  listExternalApiKeys: listMock,
54
71
  createExternalApiKey: createMock,
@@ -91,6 +108,9 @@ beforeEach(() => {
91
108
  registrationMock.mockReset();
92
109
  registrationMock.mockResolvedValue(true);
93
110
  listMock.mockResolvedValue([]);
111
+ agentChoicesMock.mockReset();
112
+ agentChoicesMock.mockResolvedValue([]);
113
+ createMock.mockClear();
94
114
  instructionsMock.mockResolvedValue({
95
115
  instructions: 'Search the knowledge base first.',
96
116
  header: 'Search the knowledge base first.',
@@ -792,6 +812,101 @@ describe('the Marketplaces tab', () => {
792
812
  });
793
813
  });
794
814
 
815
+ describe('minting a key as an agent ("Connect as")', () => {
816
+ const OPS = { path: 'Agents/ops.agent', name: 'ops', description: 'Watches the dashboards.' };
817
+
818
+ it('offers Everything, selected by default, then each agent by name with its description', async () => {
819
+ agentChoicesMock.mockResolvedValue([OPS]);
820
+ const user = userEvent.setup();
821
+ mount(PUBLIC_URL);
822
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
823
+ const group = screen.getByRole('group', { name: 'Connect as' });
824
+ const everything = within(group).getByRole('radio', { name: /Everything/ });
825
+ expect(everything).toBeChecked();
826
+ const ops = await within(group).findByRole('radio', { name: /ops.*Watches the dashboards\./ });
827
+ expect(ops).not.toBeChecked();
828
+ });
829
+
830
+ it('asks nothing when there is no agent to mint as: the key is Everything’s, as it always was', async () => {
831
+ agentChoicesMock.mockResolvedValue([]);
832
+ const user = userEvent.setup();
833
+ mount(PUBLIC_URL);
834
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
835
+ await user.type(screen.getByRole('textbox', { name: /Create an external API key/ }), 'CI');
836
+ // Create key is enabled only once the agents answered, so the choice had its chance to appear.
837
+ const create = screen.getByRole('button', { name: 'Create key' });
838
+ expect(create).toBeEnabled();
839
+ expect(screen.queryByRole('group', { name: 'Connect as' })).toBeNull();
840
+ expect(screen.queryByText(/Connect as/)).toBeNull();
841
+ await user.click(create);
842
+ expect(createMock).toHaveBeenLastCalledWith('CI', null);
843
+ });
844
+
845
+ it('mints as Everything unless an agent is picked, and as the agent when one is', async () => {
846
+ agentChoicesMock.mockResolvedValue([OPS]);
847
+ const user = userEvent.setup();
848
+ mount(PUBLIC_URL);
849
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
850
+ await user.type(screen.getByRole('textbox', { name: /Create an external API key/ }), 'CI');
851
+ await user.click(screen.getByRole('button', { name: 'Create key' }));
852
+ expect(createMock).toHaveBeenLastCalledWith('CI', null);
853
+ });
854
+
855
+ it('records the picked agent on the key', async () => {
856
+ agentChoicesMock.mockResolvedValue([OPS]);
857
+ const user = userEvent.setup();
858
+ mount(PUBLIC_URL);
859
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
860
+ await user.click(await screen.findByRole('radio', { name: /ops/ }));
861
+ await user.type(screen.getByRole('textbox', { name: /Create an external API key/ }), 'Pipeline');
862
+ await user.click(screen.getByRole('button', { name: 'Create key' }));
863
+ expect(createMock).toHaveBeenLastCalledWith('Pipeline', 'Agents/ops.agent');
864
+ });
865
+
866
+ it('says when the agents could not be loaded, and mints Everything only once that is confirmed', async () => {
867
+ agentChoicesMock.mockRejectedValue(new Error('down'));
868
+ const user = userEvent.setup();
869
+ mount(PUBLIC_URL);
870
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
871
+ expect(await screen.findByRole('alert')).toHaveTextContent(/agents couldn't be loaded/);
872
+ await user.type(screen.getByRole('textbox', { name: /Create an external API key/ }), 'CI');
873
+ const create = screen.getByRole('button', { name: 'Create key' });
874
+ expect(create).toBeDisabled();
875
+ await user.click(screen.getByRole('checkbox', { name: 'Connect as Everything anyway' }));
876
+ expect(create).toBeEnabled();
877
+ await user.click(create);
878
+ expect(createMock).toHaveBeenLastCalledWith('CI', null);
879
+ });
880
+
881
+ it('keeps Create key disabled until the agents on offer have answered', async () => {
882
+ let answer!: (agents: (typeof OPS)[]) => void;
883
+ agentChoicesMock.mockReturnValue(new Promise((resolve) => (answer = resolve)));
884
+ const user = userEvent.setup();
885
+ mount(PUBLIC_URL);
886
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
887
+ await user.type(screen.getByRole('textbox', { name: /Create an external API key/ }), 'CI');
888
+ const create = screen.getByRole('button', { name: 'Create key' });
889
+ expect(create).toBeDisabled();
890
+ await act(async () => answer([OPS]));
891
+ expect(create).toBeEnabled();
892
+ });
893
+
894
+ it('shows each key beside what it connects as', async () => {
895
+ listMock.mockResolvedValue([
896
+ { id: 'k1', kind: 'key', label: 'Laptop', createdAt: Date.now(), lastUsedAt: null, revokedAt: null, revokedBy: null, agentPath: null },
897
+ { id: 'k2', kind: 'key', label: 'Pipeline', createdAt: Date.now(), lastUsedAt: null, revokedAt: null, revokedBy: null, agentPath: 'Agents/ops.agent' },
898
+ ]);
899
+ const user = userEvent.setup();
900
+ mount(PUBLIC_URL);
901
+ await user.click(screen.getByRole('tab', { name: 'Autonomous agents' }));
902
+ await screen.findByText('Pipeline');
903
+ const rowOf = (label: string) => screen.getByText(label).closest('li') as HTMLElement;
904
+ // Everything is what a key is unless it says otherwise: no tag.
905
+ expect(rowOf('Laptop')).not.toHaveTextContent('As ');
906
+ expect(rowOf('Pipeline')).toHaveTextContent('As ops');
907
+ });
908
+ });
909
+
795
910
  describe('the one-click install link', () => {
796
911
  it('offers Add to Claude on a reachable deployment', () => {
797
912
  mount(PUBLIC_URL);
@@ -16,6 +16,8 @@ export interface ExternalApiKeySummary {
16
16
  revokedBy: 'owner' | 'admin' | null;
17
17
  /** Never set on a key the owner can see: a deleted key leaves their listings. */
18
18
  deletedAt?: number | null;
19
+ /** The agent configuration the key connects as (a knowledge-base path), or null for Everything. */
20
+ agentPath?: string | null;
19
21
  /** Model-proxy usage for this key today + the daily cap (in tokens). */
20
22
  llmUsage?: { usedTodayTokens: number; dailyTokenCap: number };
21
23
  }
@@ -44,11 +46,12 @@ export async function listExternalApiKeys(): Promise<ExternalApiKeySummary[]> {
44
46
  return res.json() as Promise<ExternalApiKeySummary[]>;
45
47
  }
46
48
 
47
- export async function createExternalApiKey(label: string): Promise<MintedExternalApiKey> {
49
+ /** Mint a key. `agentPath` is its "Connect as" choice; null (the default) is Everything. */
50
+ export async function createExternalApiKey(label: string, agentPath: string | null = null): Promise<MintedExternalApiKey> {
48
51
  const res = await authFetch('/api/mcp/external-api-keys', {
49
52
  method: 'POST',
50
53
  headers: { 'Content-Type': 'application/json' },
51
- body: JSON.stringify({ label }),
54
+ body: JSON.stringify(agentPath ? { label, agentPath } : { label }),
52
55
  });
53
56
  if (!res.ok) await unwrap(res, "Couldn't create external API key.");
54
57
  return res.json() as Promise<MintedExternalApiKey>;
@@ -13,13 +13,13 @@ import { KbPageHeader } from './KbPageHeader';
13
13
  import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
14
14
  import { Banner, Button, IconButton, Surface, useFocusHandoff } from '../../../shared/components';
15
15
  import { displayFileName, fileNameTooltip, isAccessRulesFile } from '../utils/display-file-name';
16
- import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
17
16
  import { useGit } from '../../git';
18
17
  import { LayoutContext } from '../../layout';
19
18
  import { useLocation, useNavigate, useParams } from 'react-router-dom';
20
19
  import { useCanonicalFileUrl, useFileNav } from '../routing/kb-routes';
21
20
  import { PullNeededBanner } from '../../git/components/PullNeededBanner';
22
21
  import { GitSyncFailedBanner } from '../../git/components/GitSyncFailedBanner';
22
+ import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
23
23
  import { useFileAccess, formatEligible } from '../../access';
24
24
  import { FileHistoryPanel } from '../../git/components/FileHistoryPanel';
25
25
  import { FileComparisonPanel } from '../../git/components/FileComparisonPanel';
@@ -13,10 +13,10 @@ import {
13
13
  type WorkspaceContextValue,
14
14
  } from '../../state/workspace.context';
15
15
  import { makeWorkspaceFixture } from '../../__tests__/testFixtures';
16
- import { GitContext, type GitContextValue } from '../../../git/state/git.context';
17
- import { AuthContext, type AuthContextValue } from '../../../auth/state/auth.context';
16
+ import { GitContext, type GitContextValue } from '../../../git';
17
+ import { AuthContext, type AuthContextValue } from '../../../auth';
18
18
  import { OpenChangeRequestsContext } from '../../state/open-change-requests.context';
19
- import { AdminContext, type AdminContextValue } from '../../../admin/state/admin.context';
19
+ import { AdminContext, type AdminContextValue } from '../../../admin';
20
20
  import { PR_STALE_EVENT } from '../../../../core/events';
21
21
  import { EventBusProvider } from '../../../workflow';
22
22
  import type { WorkflowEvent } from '@bevel-software/platform-shared';
@@ -44,10 +44,14 @@ const cancelMocks = vi.hoisted(() => ({
44
44
  cancelPullRequest: vi.fn(),
45
45
  deleteChangeRequest: vi.fn(),
46
46
  }));
47
- vi.mock('../../../pr/services/pr-cancel.api', () => cancelMocks);
47
+ vi.mock('../../../pr', async (importOriginal) => ({ ...(await importOriginal<typeof import('../../../pr')>()), ...cancelMocks }));
48
48
 
49
49
  // The sheet itself is covered by the access module's own tests; here only
50
50
  // WHICH workspace and proposal the tree hands it matters.
51
+ // A component is composed by importing its file, never through a module's
52
+ // index (the Module Map's one allowance for React components), so the
53
+ // component's file is the surface the tree reaches it through, and the one a
54
+ // mock stands in for.
51
55
  vi.mock('../../../access/components/ManageAccessDialog', () => ({
52
56
  ManageAccessDialog: (props: {
53
57
  entry: FileTreeEntry;
@@ -968,6 +972,32 @@ describe('FileExplorer right-click: Download menu (per-path access)', () => {
968
972
  });
969
973
  });
970
974
 
975
+ // A link INSIDE a file opens a new tab; the tree is the app's own navigation
976
+ // and is not one. A click on a file row moves this tab to that file, as it
977
+ // always has, whatever view the tab was in.
978
+ describe('FileExplorer: a file click navigates this tab', () => {
979
+ beforeEach(() => {
980
+ cleanup();
981
+ });
982
+
983
+ it('opens the clicked file in place, with no new tab', async () => {
984
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
985
+ renderExplorer({
986
+ fileTree: {
987
+ name: '.',
988
+ relativePath: '.',
989
+ type: 'directory',
990
+ children: [{ name: 'Plan.md', relativePath: 'Plan.md', type: 'file' }],
991
+ },
992
+ initialEntries: [`/workspace/alice%2Fdraft/${kbPath('Other.md')}?fullscreen=1`],
993
+ });
994
+ await userEvent.setup().click(screen.getByText('Plan.md'));
995
+ expect(screen.getByTestId('location-pathname').textContent).toBe(`/workspace/alice%2Fdraft/${kbPath('Plan.md')}`);
996
+ expect(open).not.toHaveBeenCalled();
997
+ open.mockRestore();
998
+ });
999
+ });
1000
+
971
1001
  // Regression coverage for the FileTreeNode collapse state machine. PR #113
972
1002
  // derived `autoExpanded` reactively without an escape hatch, so clicking the
973
1003
  // chevron on a folder that contained the open file did nothing — the user's
@@ -2030,16 +2060,36 @@ describe('FileExplorer: delete and move ask first', () => {
2030
2060
  const person = (name: string, email: string) => ({ kind: 'person', name, email });
2031
2061
 
2032
2062
  /**
2033
- * Answer the move dialog's access lookup with these before/after holders,
2034
- * and everything else (the destination-writable preflight) with a writable
2035
- * verdict — the warnings suite covers that one on its own.
2063
+ * Answer the move dialog's access lookup with these before/after holders —
2064
+ * and the `changes` the server derives from the resolver, which this stand-in
2065
+ * derives from the two sides, since no rule here denies anyone by name — and
2066
+ * everything else (the destination-writable preflight) with a writable
2067
+ * verdict; the warnings suite covers that one on its own.
2036
2068
  */
2037
2069
  function answerAccess(before: Side, after: Side, opts: { canWrite?: boolean } = {}) {
2038
2070
  const side = (s: Side) => ({ read: s.read ?? [], write: s.write ?? [] });
2071
+ const keyOf = (p: unknown) => {
2072
+ const { kind, name, email } = p as { kind: string; name: string; email?: string };
2073
+ return kind === 'person' ? `person:${(email ?? name).toLowerCase()}` : `${kind}:${name.toLowerCase()}`;
2074
+ };
2075
+ const changesOf = (b: Side, a: Side) => {
2076
+ const lose: unknown[] = [];
2077
+ const gain: unknown[] = [];
2078
+ for (const verb of ['read', 'write'] as const) {
2079
+ const had = new Set((b[verb] ?? []).map(keyOf));
2080
+ const has = new Set((a[verb] ?? []).map(keyOf));
2081
+ for (const p of b[verb] ?? []) if (!has.has(keyOf(p))) lose.push({ ...(p as object), verb });
2082
+ for (const p of a[verb] ?? []) if (!had.has(keyOf(p))) gain.push({ ...(p as object), verb });
2083
+ }
2084
+ return { lose, gain };
2085
+ };
2039
2086
  mockAuthFetch.mockImplementation(async (url: string) => {
2040
2087
  const u = String(url);
2041
2088
  if (u.includes('/access/prospective')) {
2042
- return { ok: true, json: async () => ({ before: side(before), after: side(after) }) };
2089
+ return {
2090
+ ok: true,
2091
+ json: async () => ({ before: side(before), after: side(after), changes: changesOf(before, after) }),
2092
+ };
2043
2093
  }
2044
2094
  if (u.includes('/access?')) {
2045
2095
  return { ok: true, json: async () => ({ canWrite: opts.canWrite ?? true }) };
@@ -1,9 +1,11 @@
1
1
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
2
2
  import { Pencil, Eye, RotateCw } from 'lucide-react';
3
+ import { useLocation } from 'react-router-dom';
3
4
  import { useFileNav } from '../../routing/kb-routes';
4
5
  import type { FileRendererProps, RendererSaveState } from './types';
5
6
  import { buildSandboxedHtml, sanitizeAgentHtml } from './htmlSandbox';
6
7
  import { useRendererSurface } from './rendererSurface';
8
+ import { usePageLinkHome } from './htmlToolBridge';
7
9
  import { useHtmlToolBridge } from './useHtmlToolBridge';
8
10
  import {
9
11
  HTML_FRAME_KEY_STEP,
@@ -49,11 +51,20 @@ export function HtmlRenderer({
49
51
  onSaveStateChange,
50
52
  readOnly = false,
51
53
  }: FileRendererProps) {
52
- const { openLink } = useFileNav();
54
+ const { openLink, branch: tabBranch } = useFileNav();
55
+ // The fragment this tab's address arrived with (`Board.html#totals`, from a
56
+ // section link opened in a new tab or a shared address). It names a place
57
+ // in the PAGE, which lives in the frame, where the app's address never
58
+ // reaches: the frame is handed it as `bevel.jump` once it has loaded, the
59
+ // same message a click on a section link inside the page is answered with.
60
+ const { hash: arrivalHash } = useLocation();
53
61
  const surface = useRendererSurface();
54
62
  // Whether the surface's host grows with the page (an issue panel) rather
55
63
  // than giving it a pane to scroll in (the app, the MCP App's pane).
56
64
  const sizesToContent = surface?.sizesToContent === true;
65
+ // The file this page's links resolve against, where the host's `filePath`
66
+ // is not a workspace path on this tab's branch (a skill page).
67
+ const linkHome = usePageLinkHome();
57
68
  const [mode, setMode] = useState<'preview' | 'edit'>('preview');
58
69
  /**
59
70
  * The frame's height where the host grows with the page: the standard
@@ -133,12 +144,16 @@ export function HtmlRenderer({
133
144
  libModuleSources: [],
134
145
  bodyHtml: sanitizeAgentHtml(savedValue),
135
146
  toolBridge,
147
+ // The branch the page is viewed on — the real home of a page whose
148
+ // host is not a workspace path (a skill page), else the file page's
149
+ // tab: the same branch its links resolve on. Absent on a surface.
150
+ branch: linkHome?.branch ?? tabBranch ?? undefined,
136
151
  });
137
152
  return { srcdoc, error: null };
138
153
  } catch (err) {
139
154
  return { srcdoc: null, error: err instanceof Error ? err.message : 'Failed to build preview' };
140
155
  }
141
- }, [mode, savedValue, filePath, toolBridge]);
156
+ }, [mode, savedValue, filePath, toolBridge, linkHome, tabBranch]);
142
157
  const bundledSrcdoc = preview?.srcdoc ?? null;
143
158
  const previewError = preview?.error ?? null;
144
159
 
@@ -152,21 +167,36 @@ export function HtmlRenderer({
152
167
  // node — both post a `bevel.navigate` message (the iframe sandbox can't
153
168
  // navigate the host window itself). `openLink` resolves the href the same
154
169
  // way the markdown renderer does (absolute `/workspace/…` URLs keep their
155
- // branch; relative paths resolve against this file) and routes it through
156
- // the in-app navigation so the URL reflects what's on screen.
170
+ // branch; relative paths resolve against this file) and follows it by the
171
+ // rule for links inside a file: another file opens in a new tab, and this
172
+ // page — its state, its scroll, its full-screen view — stays as it was.
173
+ // A link to a section of this same page (`Roadmap.html#q3` from inside
174
+ // Roadmap.html) is handed back to the frame as `bevel.jump`, which scrolls
175
+ // it the way the bridge scrolls a bare `#q3`: a fragment on the app's own
176
+ // address would never reach the frame. A host whose `filePath` is not a
177
+ // workspace path on this tab's branch (a skill page) names the page's real
178
+ // home through `PageLinkHomeContext`.
157
179
  useEffect(() => {
158
180
  function onNavMessage(event: MessageEvent) {
159
181
  const iframeWin = iframeRef.current?.contentWindow;
160
182
  if (!iframeWin || event.source !== iframeWin) return;
161
- const msg = event.data as { type?: unknown; href?: unknown } | null;
183
+ const msg = event.data as { type?: unknown; href?: unknown; newTab?: unknown } | null;
162
184
  if (!msg || typeof msg !== 'object' || msg.type !== 'bevel.navigate') return;
163
185
  const href = typeof msg.href === 'string' ? msg.href : null;
164
186
  if (!href) return;
165
- openLink(href, filePath);
187
+ openLink(href, linkHome?.path ?? filePath, {
188
+ homeBranch: linkHome?.branch,
189
+ // A modified or middle click in the page, which the frame cannot
190
+ // open a tab for itself (see the nav bridge in `htmlSandbox.ts`).
191
+ newTab: msg.newTab === true,
192
+ onSection: (hash) => {
193
+ if (hash) iframeWin.postMessage({ type: 'bevel.jump', hash }, '*');
194
+ },
195
+ });
166
196
  }
167
197
  window.addEventListener('message', onNavMessage);
168
198
  return () => window.removeEventListener('message', onNavMessage);
169
- }, [openLink, filePath]);
199
+ }, [openLink, filePath, linkHome]);
170
200
 
171
201
  useEffect(() => {
172
202
  frameHeightRef.current = frameHeight;
@@ -310,6 +340,9 @@ export function HtmlRenderer({
310
340
  // iframe cannot exfiltrate, navigate, popup, or fetch.
311
341
  sandbox="allow-scripts"
312
342
  referrerPolicy="no-referrer"
343
+ onLoad={(e) => {
344
+ if (arrivalHash) e.currentTarget.contentWindow?.postMessage({ type: 'bevel.jump', hash: arrivalHash }, '*');
345
+ }}
313
346
  // In a pane the frame fills it and scrolls inside; where the host
314
347
  // grows with the page, the frame has the reader's height (a
315
348
  // flex-grown frame in an auto-height column would collapse to the
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Where an in-app link inside rendered content leads, as the app's file-nav
3
+ * hook answers it (`useFileNav().linkTarget`, `useNodeIdNav().nodeIdTarget`):
4
+ * `href` is the address the click opens, `newTab` whether it opens there in a
5
+ * new tab (another file) or in this one (a section of the file on screen).
6
+ */
7
+ export interface KbLinkTarget {
8
+ href: string;
9
+ newTab: boolean;
10
+ }
11
+
12
+ /**
13
+ * An in-app link the caller follows on click (`onOpen`, with the destination
14
+ * as written). With a `target` the anchor carries the address the click goes
15
+ * to, and — when that is a new tab — `target="_blank"` and `rel="noopener"`,
16
+ * so a middle-click, the context menu and a screen reader all agree with the
17
+ * click. A click the reader modified (Ctrl, ⌘, Shift, Alt) or made with
18
+ * another button is left to the browser, on a new-tab link and a section link
19
+ * alike: the anchor's `href` is already the address the click would open, so
20
+ * the browser does with it what it does with any link — a Ctrl-click on a
21
+ * section link opens that section in a new tab rather than moving this one.
22
+ * Without a `target` (no resolver) the anchor is what it always was, every
23
+ * click taken by `onOpen`: its `href` is the destination as written, not an
24
+ * address the browser could follow.
25
+ */
26
+ export function KbAppLink({
27
+ href,
28
+ target,
29
+ onOpen,
30
+ className = 'cursor-pointer',
31
+ children,
32
+ ...props
33
+ }: {
34
+ href: string;
35
+ target: KbLinkTarget | null;
36
+ onOpen: () => void;
37
+ className?: string;
38
+ children?: React.ReactNode;
39
+ }) {
40
+ const newTab = target?.newTab === true;
41
+ return (
42
+ <a
43
+ {...props}
44
+ href={target?.href ?? href}
45
+ {...(newTab ? { target: '_blank', rel: 'noopener' } : {})}
46
+ onClick={(e) => {
47
+ if (target && (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return;
48
+ e.preventDefault();
49
+ onOpen();
50
+ }}
51
+ className={className}
52
+ >
53
+ {children}
54
+ </a>
55
+ );
56
+ }