@bevel-software/platform-core-frontend 0.33.0 → 0.34.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 +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 +3 -4
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  8. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  9. package/src/modules/admin/services/groups.api.ts +11 -1
  10. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  11. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  12. package/src/modules/agents/connect-as.ts +15 -0
  13. package/src/modules/agents/index.ts +5 -0
  14. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  15. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  16. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  17. package/src/modules/audit/components/AuditLogPage.tsx +9 -0
  18. package/src/modules/audit/services/audit.api.ts +5 -0
  19. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  20. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  21. package/src/modules/auth/components/AccountPage.tsx +8 -2
  22. package/src/modules/auth/services/account.api.ts +18 -2
  23. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  24. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  25. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  26. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  27. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  28. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  29. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  30. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  31. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  32. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  33. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  34. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  35. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +38 -4
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  37. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  38. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +26 -0
  39. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  40. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  41. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  42. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  43. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  44. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  45. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  46. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  47. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  48. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  49. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  50. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  51. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  52. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  53. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  54. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  55. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  56. package/src/modules/workspace/index.ts +21 -2
  57. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  58. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  59. package/src/modules/workspace/utils/fileTree.ts +1 -1
@@ -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 —
@@ -9,6 +9,7 @@ import {
9
9
  useKbMarkdownComponents,
10
10
  type KbImageResolver,
11
11
  } from '../../workspace/components/renderers/kbMarkdownPipeline';
12
+ import type { KbLinkTarget } from '../../workspace';
12
13
 
13
14
  const MAX_RENDERED_LINES = 5000;
14
15
 
@@ -29,6 +30,9 @@ interface MarkdownDiffViewerProps {
29
30
  onOpenFile?: (href: string) => void;
30
31
  /** Same contract as {@link onOpenFile}, for bare node-id links. */
31
32
  onOpenNodeId?: (id: string) => void;
33
+ /** Where each kind of link leads, for its anchor — `KbAppLink` in the pipeline. */
34
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
35
+ nodeIdLinkTarget?: (id: string) => KbLinkTarget | null;
32
36
  /**
33
37
  * Resolves a workspace image in the diff to the URL that serves it from the
34
38
  * CHECKED-OUT tree. It applies to unchanged and added fragments only; a
@@ -76,7 +80,15 @@ interface MarkdownDiffViewerProps {
76
80
  * routes, which sit outside those providers entirely. A `useNavigate()` in
77
81
  * here would be a runtime crash in all three.
78
82
  */
79
- export function MarkdownDiffViewer({ payload, onOpenFile, onOpenNodeId, resolveImage, scroll = true }: MarkdownDiffViewerProps) {
83
+ export function MarkdownDiffViewer({
84
+ payload,
85
+ onOpenFile,
86
+ onOpenNodeId,
87
+ fileLinkTarget,
88
+ nodeIdLinkTarget,
89
+ resolveImage,
90
+ scroll = true,
91
+ }: MarkdownDiffViewerProps) {
80
92
  const data = useMemo(() => {
81
93
  const baseline = payload.baseline ?? '';
82
94
  const current = payload.current ?? '';
@@ -133,6 +145,8 @@ export function MarkdownDiffViewer({ payload, onOpenFile, onOpenNodeId, resolveI
133
145
  blocks={data.bodyBlocks}
134
146
  onOpenFile={onOpenFile}
135
147
  onOpenNodeId={onOpenNodeId}
148
+ fileLinkTarget={fileLinkTarget}
149
+ nodeIdLinkTarget={nodeIdLinkTarget}
136
150
  resolveImage={resolveImage}
137
151
  />
138
152
  </div>
@@ -294,11 +308,15 @@ function DiffPreview({
294
308
  blocks,
295
309
  onOpenFile,
296
310
  onOpenNodeId,
311
+ fileLinkTarget,
312
+ nodeIdLinkTarget,
297
313
  resolveImage,
298
314
  }: {
299
315
  blocks: DisplayBlock[];
300
316
  onOpenFile?: (href: string) => void;
301
317
  onOpenNodeId?: (id: string) => void;
318
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
319
+ nodeIdLinkTarget?: (id: string) => KbLinkTarget | null;
302
320
  resolveImage?: KbImageResolver;
303
321
  }) {
304
322
  // Images, per fragment. The caller's resolver serves the CURRENT tree, which
@@ -334,12 +352,16 @@ function DiffPreview({
334
352
  const components = useKbMarkdownComponents({
335
353
  onOpenFile,
336
354
  onOpenNodeId,
355
+ fileLinkTarget,
356
+ nodeIdLinkTarget,
337
357
  onMermaidError: 'source',
338
358
  resolveImage: liveImages,
339
359
  });
340
360
  const baselineComponents = useKbMarkdownComponents({
341
361
  onOpenFile,
342
362
  onOpenNodeId,
363
+ fileLinkTarget,
364
+ nodeIdLinkTarget,
343
365
  onMermaidError: 'source',
344
366
  resolveImage: baselineImages,
345
367
  });
@@ -109,14 +109,14 @@ function kindLabel(kind: PendingChange['kind']): string {
109
109
  export function ReviewPanel({ onClose }: { onClose?: () => void }) {
110
110
  const review = useReview();
111
111
  const { refreshFileTree, kbDirName, workspaceId } = useWorkspace();
112
- const { openFile, openLink } = useFileNav();
112
+ const { openFile, openLink, linkTarget } = useFileNav();
113
113
  // Links inside a rendered diff. Both resolvers navigate relative to
114
114
  // `git.status.branch`, which is CORRECT here and only here: this panel
115
115
  // reviews the agent's uncommitted changes on the branch you are already
116
116
  // standing on, so "the diff's branch" and "the current branch" are the same
117
117
  // thing. (The change-request dialog is not in that position, which is why it
118
118
  // passes no resolvers — see the comment at its MarkdownDiffViewer call.)
119
- const { openNodeId } = useNodeIdNav();
119
+ const { openNodeId, nodeIdTarget } = useNodeIdNav();
120
120
  const diffPath = review.fileDiff?.path ?? '';
121
121
  // Resolved against the diffed file by `openLink`: decoded, an absolute URL
122
122
  // keeping its own branch. The same grammar MarkdownRenderer uses.
@@ -124,6 +124,10 @@ export function ReviewPanel({ onClose }: { onClose?: () => void }) {
124
124
  (href: string) => openLink(href, diffPath),
125
125
  [openLink, diffPath],
126
126
  );
127
+ const diffLinkTarget = useCallback(
128
+ (href: string) => linkTarget(href, diffPath),
129
+ [linkTarget, diffPath],
130
+ );
127
131
  // Images inside a rendered diff, bound to the CHECKED-OUT workspace for the
128
132
  // reason above: the working tree IS the diff's new state, so an image the
129
133
  // agent added is on disk and can be shown. The viewer applies this to the
@@ -373,6 +377,8 @@ export function ReviewPanel({ onClose }: { onClose?: () => void }) {
373
377
  payload={fileDiff}
374
378
  onOpenFile={openDiffLink}
375
379
  onOpenNodeId={openNodeId}
380
+ fileLinkTarget={diffLinkTarget}
381
+ nodeIdLinkTarget={nodeIdTarget}
376
382
  resolveImage={resolveDiffImage}
377
383
  scroll={false}
378
384
  />
@@ -103,6 +103,37 @@ describe('MarkdownDiffViewer', () => {
103
103
  await userEvent.click(screen.getByText('the process'));
104
104
  expect(onOpenNodeId).toHaveBeenCalledWith('order-intake');
105
105
  });
106
+
107
+ it("carry the target the caller resolves: the new tab's address, target=_blank, rel=noopener", () => {
108
+ const nodeIdLinkTarget = vi.fn(() => ({ href: '/workspace/main/order-intake', newTab: true }));
109
+ render(
110
+ <MarkdownDiffViewer payload={withIdLink} onOpenNodeId={vi.fn()} nodeIdLinkTarget={nodeIdLinkTarget} />,
111
+ );
112
+ const link = screen.getByRole('link', { name: 'the process' });
113
+ expect(nodeIdLinkTarget).toHaveBeenCalledWith('order-intake');
114
+ expect(link).toHaveAttribute('href', '/workspace/main/order-intake');
115
+ expect(link).toHaveAttribute('target', '_blank');
116
+ expect(link).toHaveAttribute('rel', 'noopener');
117
+ });
118
+ });
119
+
120
+ it("gives a file link the target the caller resolves, and follows a click through the caller", async () => {
121
+ const onOpenFile = vi.fn();
122
+ const fileLinkTarget = vi.fn(() => ({ href: '/workspace/main/Knowledge/Plan.md', newTab: true }));
123
+ render(
124
+ <MarkdownDiffViewer
125
+ payload={payload('Nothing\n', 'See [the plan](Plan.md)\n')}
126
+ onOpenFile={onOpenFile}
127
+ fileLinkTarget={fileLinkTarget}
128
+ />,
129
+ );
130
+ const link = screen.getByRole('link', { name: 'the plan' });
131
+ expect(fileLinkTarget).toHaveBeenCalledWith('Plan.md');
132
+ expect(link).toHaveAttribute('href', '/workspace/main/Knowledge/Plan.md');
133
+ expect(link).toHaveAttribute('target', '_blank');
134
+ expect(link).toHaveAttribute('rel', 'noopener');
135
+ await userEvent.click(link);
136
+ expect(onOpenFile).toHaveBeenCalledWith('Plan.md');
106
137
  });
107
138
 
108
139
  it('escapes spaces in link destinations so KB links resolve', () => {
@@ -8,6 +8,8 @@ import { setUserVar, setAdminVar, deleteUserVar, setOAuthClientSecret } from '..
8
8
  import { SavedKeyProbeResult } from '../probe/SavedKeyProbeResult';
9
9
  import { useSavedKeyProbe, type SavedKeyProbe } from '../probe/useSavedKeyProbe';
10
10
  import { announceToolCredentialsChanged } from '../../../core/events';
11
+ import { useConnectAsChoice } from '../../agents';
12
+ import { ConnectAsChoice } from '../../agents/components/ConnectAsChoice';
11
13
  import {
12
14
  getConnectPending,
13
15
  startToolOAuth,
@@ -31,6 +33,20 @@ import {
31
33
  * alive across that round-trip. Cleared on Finish or when the state goes stale.
32
34
  */
33
35
  const MCP_OAUTH_STATE_KEY = 'mcp-oauth-state';
36
+ /** The "Connect as" choice made on the way, kept beside the state for the same round-trip. */
37
+ const MCP_OAUTH_AGENT_KEY = 'mcp-oauth-agent';
38
+
39
+ /**
40
+ * The choice to start from: the one made earlier in THIS authorization (the
41
+ * page came back from a tool sign-in, its query stripped), else Everything —
42
+ * an authorization arriving in the address that is not the remembered one is
43
+ * a new connection, and starts at Everything.
44
+ */
45
+ function rememberedConnectAs(): string | null {
46
+ const fromUrl = new URLSearchParams(window.location.search).get('oauth');
47
+ if (fromUrl && fromUrl !== sessionStorage.getItem(MCP_OAUTH_STATE_KEY)) return null;
48
+ return sessionStorage.getItem(MCP_OAUTH_AGENT_KEY);
49
+ }
34
50
 
35
51
  /**
36
52
  * "Connect your tools" — the page a person lands on from the needs-authorization
@@ -99,6 +115,12 @@ export function ConnectToolsPage() {
99
115
  // Agent-connect mode: the signed authorization state + who is asking.
100
116
  const [agentState, setAgentState] = useState<string | null>(null);
101
117
  const [agentName, setAgentName] = useState<string | null>(null);
118
+ // "Connect as": the agents on offer and the choice — Everything unless the
119
+ // person picks one — kept across a tool sign-in's round-trip
120
+ // (`rememberedConnectAs`). Finish waits until the CURRENT request's agents
121
+ // have answered (before that it would approve Everything unseen), and for
122
+ // Everything to be confirmed when they could not be loaded.
123
+ const connectAs = useConnectAsChoice({ initial: rememberedConnectAs, expect: agentState });
102
124
  const [finishing, setFinishing] = useState(false);
103
125
  // Entries the user took OUT. Everything the server sent is in by default —
104
126
  // it used to be the other way round, and an unconfigured tool the reader had
@@ -118,6 +140,14 @@ export function ConnectToolsPage() {
118
140
  */
119
141
  const loadSeq = useRef(0);
120
142
 
143
+ // The agent the list is for: the "Connect as" choice, in agent-connect mode
144
+ // only. A connection made as an agent loads only the connectors its file
145
+ // lists, so the page asks for the sign-ins and keys of those and no other —
146
+ // asking for hubspot's sign-in on the way to an agent that never loads
147
+ // hubspot sends the person off to sign in for nothing. Everything (null)
148
+ // lists what it always listed.
149
+ const chosenAgent = agentState != null ? connectAs.value : null;
150
+
121
151
  /**
122
152
  * @param quiet keep the list on screen while it refetches.
123
153
  *
@@ -132,7 +162,7 @@ export function ConnectToolsPage() {
132
162
  if (!quiet) setLoading(true);
133
163
  setRefreshing(true);
134
164
  try {
135
- const pending = await getConnectPending();
165
+ const pending = await getConnectPending(chosenAgent);
136
166
  if (loadSeq.current !== mine) return;
137
167
  setTools(pending.tools);
138
168
  setOauth(pending.oauth);
@@ -148,17 +178,27 @@ export function ConnectToolsPage() {
148
178
  setRefreshing(false);
149
179
  }
150
180
  }
151
- }, []);
152
-
181
+ }, [chosenAgent]);
182
+
183
+ // The first load, loud; and again, quietly, whenever the choice changes —
184
+ // `refresh` is remade for the chosen agent, and the list on screen is the
185
+ // other agent's until the new one answers, which is the one case a loud
186
+ // reload would have nothing to protect (no row holds a probe's verdict
187
+ // for a list that is about to be replaced) and still nothing to gain.
188
+ const loadedOnce = useRef(false);
153
189
  useEffect(() => {
154
- // eslint-disable-next-line react-hooks/set-state-in-effect -- the first load; refresh sets state once it answers
155
- void refresh();
190
+ const quiet = loadedOnce.current;
191
+ loadedOnce.current = true;
192
+ void refresh(quiet);
156
193
  }, [refresh]);
157
194
 
158
195
  // Pick up (and persist) the external-agent authorization state.
159
196
  useEffect(() => {
160
197
  const fromUrl = new URLSearchParams(window.location.search).get('oauth');
161
198
  if (fromUrl) {
199
+ // A NEW authorization starts at Everything (see `rememberedConnectAs`):
200
+ // a choice remembered from another one is not this connection's.
201
+ if (sessionStorage.getItem(MCP_OAUTH_STATE_KEY) !== fromUrl) sessionStorage.removeItem(MCP_OAUTH_AGENT_KEY);
162
202
  sessionStorage.setItem(MCP_OAUTH_STATE_KEY, fromUrl);
163
203
  // eslint-disable-next-line react-hooks/set-state-in-effect -- the query is read once, on arrival
164
204
  setAgentState(fromUrl);
@@ -169,23 +209,27 @@ export function ConnectToolsPage() {
169
209
 
170
210
  // Resolve who is asking; a stale/expired state silently drops the mode (the
171
211
  // agent restarts the flow if the user takes too long).
212
+ const settleConnectAs = connectAs.settle;
172
213
  useEffect(() => {
173
214
  if (!agentState) return;
174
215
  let cancelled = false;
175
216
  getMcpOAuthRequest(agentState)
176
217
  .then((r) => {
177
- if (!cancelled) setAgentName(r.clientName);
218
+ if (cancelled) return;
219
+ setAgentName(r.clientName);
220
+ settleConnectAs({ agents: r.agents ?? [], failed: r.agentsUnavailable === true }, agentState);
178
221
  })
179
222
  .catch(() => {
180
223
  if (cancelled) return;
181
224
  sessionStorage.removeItem(MCP_OAUTH_STATE_KEY);
225
+ sessionStorage.removeItem(MCP_OAUTH_AGENT_KEY);
182
226
  setAgentState(null);
183
227
  setAgentName(null);
184
228
  });
185
229
  return () => {
186
230
  cancelled = true;
187
231
  };
188
- }, [agentState]);
232
+ }, [agentState, settleConnectAs]);
189
233
 
190
234
  // A sign-in came back to this page (the callback lands on whichever page
191
235
  // started it): the fragment it carried is stripped, now that it has been
@@ -220,11 +264,12 @@ export function ConnectToolsPage() {
220
264
  };
221
265
 
222
266
  const onFinish = async () => {
223
- if (!agentState) return;
267
+ if (!agentState || !connectAs.mayConnect) return;
224
268
  setFinishing(true);
225
269
  try {
226
- const redirectTo = await completeMcpOAuth(agentState);
270
+ const redirectTo = await completeMcpOAuth(agentState, connectAs.value);
227
271
  sessionStorage.removeItem(MCP_OAUTH_STATE_KEY);
272
+ sessionStorage.removeItem(MCP_OAUTH_AGENT_KEY);
228
273
  window.location.href = redirectTo;
229
274
  } catch (err) {
230
275
  setError(err instanceof Error ? err.message : String(err));
@@ -348,12 +393,26 @@ export function ConnectToolsPage() {
348
393
  variant="primary"
349
394
  size="sm"
350
395
  className="shrink-0"
351
- disabled={finishing}
396
+ disabled={finishing || !connectAs.mayConnect}
352
397
  onClick={() => void onFinish()}
353
398
  >
354
399
  {finishing ? 'Finishing…' : 'Finish & return to your agent'}
355
400
  </Button>
356
401
  </div>
402
+ <div className="mt-4">
403
+ <ConnectAsChoice
404
+ agents={connectAs.agents}
405
+ value={connectAs.value}
406
+ disabled={finishing}
407
+ hint="What this connection loads. An agent narrows it to the tools, skills and plugins its configuration lists, and only those you may read."
408
+ onChange={(path) => {
409
+ connectAs.setValue(path);
410
+ if (path) sessionStorage.setItem(MCP_OAUTH_AGENT_KEY, path);
411
+ else sessionStorage.removeItem(MCP_OAUTH_AGENT_KEY);
412
+ }}
413
+ unavailable={connectAs.unavailable}
414
+ />
415
+ </div>
357
416
  </Surface>
358
417
  )}
359
418
 
@@ -378,11 +437,13 @@ export function ConnectToolsPage() {
378
437
  so before they wonder why a row has no field. */}
379
438
  {!nothingToDo && (
380
439
  <p className="mb-5 text-ui text-ink-muted">
381
- These tools need a sign-in or a key before they will work in your agent. Authorize
382
- each connection and enter any keys below, then head back to your agent and run the
383
- tool again. Anything greyed out is not yours to do — it is waiting on the tool&apos;s
384
- owner, or you took it out yourself. Your values are stored securely and never shown
385
- again after saving.
440
+ {chosenAgent
441
+ ? 'These are the tools the chosen agent loads that need a sign-in or a key before they will work in your agent. '
442
+ : 'These tools need a sign-in or a key before they will work in your agent. '}
443
+ Authorize each connection and enter any keys below, then head back to your agent and
444
+ run the tool again. Anything greyed out is not yours to do — it is waiting on the
445
+ tool&apos;s owner, or you took it out yourself. Your values are stored securely and
446
+ never shown again after saving.
386
447
  </p>
387
448
  )}
388
449
 
@@ -394,7 +455,9 @@ export function ConnectToolsPage() {
394
455
  // every shared tool works without a personal credential, so the
395
456
  // user's only job is to finish.
396
457
  <Banner role="status" tone="ok">
397
- You&apos;re all set: none of your tools need a personal sign-in or key. Click
458
+ {chosenAgent
459
+ ? 'You’re all set: none of the tools the chosen agent loads need a personal sign-in or key. Click '
460
+ : 'You’re all set: none of your tools need a personal sign-in or key. Click '}
398
461
  “Finish &amp; return to your agent” above to complete the connection.
399
462
  </Banner>
400
463
  ) : (