@bevel-software/platform-core-frontend 0.29.0 → 0.31.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 (43) hide show
  1. package/package.json +2 -2
  2. package/src/{modules/access/__tests__ → __tests__}/tailwindDeclarations.ts +1 -1
  3. package/src/__tests__/title-ink-room.ts +30 -0
  4. package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +1 -1
  5. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +35 -2
  6. package/src/modules/audit/components/AuditEventsPanel.tsx +2 -1
  7. package/src/modules/audit/components/AuditLogPage.tsx +20 -12
  8. package/src/modules/audit/services/audit.api.ts +6 -4
  9. package/src/modules/embed/__tests__/EmbedView.test.tsx +20 -0
  10. package/src/modules/embed/components/EmbedView.tsx +2 -0
  11. package/src/modules/git/index.ts +3 -0
  12. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +50 -0
  13. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +37 -0
  14. package/src/modules/library/__tests__/SkillPage.test.tsx +44 -1
  15. package/src/modules/library/__tests__/ToolPage.test.tsx +8 -0
  16. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +25 -0
  17. package/src/modules/library/components/LibraryPage.tsx +2 -2
  18. package/src/modules/library/components/LockedPluginView.tsx +2 -2
  19. package/src/modules/library/components/PersonalPluginPage.tsx +5 -4
  20. package/src/modules/library/components/PluginPage.tsx +7 -4
  21. package/src/modules/library/components/skill-page/SkillFilePane.tsx +11 -1
  22. package/src/modules/library/components/skill-page/SkillPage.tsx +12 -2
  23. package/src/modules/library/components/tool-page/ToolPage.tsx +8 -4
  24. package/src/modules/library/routes/WorkspaceItemRoute.tsx +8 -2
  25. package/src/modules/workspace/components/FileViewer.tsx +6 -1
  26. package/src/modules/workspace/components/KbPageHeader.tsx +7 -4
  27. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +7 -0
  28. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +164 -4
  29. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +1 -0
  30. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +272 -0
  31. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +1 -0
  32. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +44 -3
  33. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +62 -0
  34. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +232 -0
  35. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +29 -1
  36. package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +1 -0
  37. package/src/modules/workspace/components/renderers/htmlSandbox.ts +92 -1
  38. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +383 -0
  39. package/src/modules/workspace/components/renderers/rendererSurface.ts +6 -0
  40. package/src/modules/workspace/index.ts +9 -2
  41. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +7 -0
  42. package/src/modules/workspace/routing/kb-routes.ts +33 -1
  43. package/src/shared/theme/header.ts +20 -0
@@ -3,7 +3,7 @@ import { DEFAULT_BRANCH, type FileTreeEntry } from '@bevel-software/platform-sha
3
3
  import { Link, useNavigate, useParams } from 'react-router-dom';
4
4
  import { Banner, Button } from '../../../shared/components';
5
5
  import { cn } from '../../../lib/utils';
6
- import { HEADER_BAND, PAGE_HEADER_TESTID } from '../../../shared/theme/header';
6
+ import { HEADER_BAND, PAGE_HEADER_TESTID, TITLE_INK_ROOM } from '../../../shared/theme/header';
7
7
  import { attentionOf, useLibrary, type LibraryItem } from '../state/library-data';
8
8
  import { useLibraryToast } from '../state/toast.context';
9
9
  import { isInPlugin, withLinkHealth } from '../utils/status';
@@ -374,10 +374,13 @@ export function PluginPage() {
374
374
  viewport a group that could only shrink would push its content
375
375
  straight across the manifest and action buttons instead. Clipped,
376
376
  the title truncates first, the trail goes last, and the controls
377
- stay where they are and stay clickable. */}
378
- <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
377
+ stay where they are and stay clickable. The ink room is on this
378
+ group as well as on the title: the group clips too, to exactly the
379
+ title's line box, so without it the tails the title's own room
380
+ uncovers are cut off one box further out. */}
381
+ <div className={`flex min-w-0 flex-1 items-center gap-2 overflow-hidden ${TITLE_INK_ROOM}`}>
379
382
  <PluginBreadcrumb />
380
- <h1 className="min-w-0 truncate text-display font-semibold" title={label}>
383
+ <h1 className={`min-w-0 truncate text-display font-semibold ${TITLE_INK_ROOM}`} title={label}>
381
384
  {label}
382
385
  </h1>
383
386
  </div>
@@ -4,6 +4,7 @@ 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 } from '../../../workspace';
7
8
  import type { DiffLine } from '../../../change-requests/utils/diff';
8
9
 
9
10
  /** The pane never writes — editing goes through the page's Edit / Propose. */
@@ -32,6 +33,12 @@ interface SkillFilePaneProps {
32
33
  headingLink?(slug: string): string;
33
34
  /** Image source resolver, same contract as `KbMarkdownView`; absent ⇒ plain `<img>` tags. */
34
35
  resolveImage?: KbImageResolver;
36
+ /**
37
+ * Open this file on the app's file page — what an HTML page's "Open in the
38
+ * platform" does here, since `file` is relative to the skill, not a
39
+ * workspace path.
40
+ */
41
+ onOpenInPlatform?(): void;
35
42
  }
36
43
 
37
44
  /**
@@ -55,6 +62,7 @@ export function SkillFilePane({
55
62
  onOpenNodeId,
56
63
  headingLink,
57
64
  resolveImage,
65
+ onOpenInPlatform,
58
66
  }: SkillFilePaneProps) {
59
67
  return (
60
68
  <FilePaneCard file={file} actions={actions} notice={notice} className="mt-4">
@@ -83,7 +91,9 @@ export function SkillFilePane({
83
91
  // Sized wrapper because the renderer fills its parent, and this card
84
92
  // has no height of its own.
85
93
  <div className="h-[70vh]">
86
- <HtmlRenderer content={raw} filePath={file} readOnly onSave={NOOP_SAVE} />
94
+ <OpenPageInPlatformContext.Provider value={onOpenInPlatform ?? null}>
95
+ <HtmlRenderer content={raw} filePath={file} readOnly onSave={NOOP_SAVE} />
96
+ </OpenPageInPlatformContext.Provider>
87
97
  </div>
88
98
  ) : (
89
99
  <pre className="whitespace-pre-wrap break-words font-mono text-detail leading-relaxed text-ink-muted">
@@ -1,7 +1,7 @@
1
1
  import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react';
2
2
  import { useLocation, useNavigate, useParams } from 'react-router-dom';
3
3
  import { cn } from '../../../../lib/utils';
4
- import { HEADER_BAND, HEADER_BAND_LEAD, PAGE_HEADER_TESTID } from '../../../../shared/theme/header';
4
+ import { HEADER_BAND, HEADER_BAND_LEAD, PAGE_HEADER_TESTID, TITLE_INK_ROOM } from '../../../../shared/theme/header';
5
5
  import { ArrowLeft, History } from 'lucide-react';
6
6
  import {
7
7
  DEFAULT_BRANCH,
@@ -677,7 +677,7 @@ export function SkillPage({
677
677
  // `title` because `truncate` hides the rest of a long skill name,
678
678
  // and a heading you cannot finish reading needs somewhere to say it.
679
679
  title={skill?.name ?? name}
680
- className="min-w-0 truncate text-display font-semibold text-ink focus:outline-none"
680
+ className={`min-w-0 truncate text-display font-semibold text-ink focus:outline-none ${TITLE_INK_ROOM}`}
681
681
  >
682
682
  {skill?.name ?? name}
683
683
  </h1>
@@ -853,6 +853,16 @@ export function SkillPage({
853
853
  // No workspace yet means no base to resolve against: images render
854
854
  // as plain tags, exactly as before the resolver existed.
855
855
  resolveImage={fileWorkspacePath ? resolveImage : undefined}
856
+ // A page of the skill opens on the Knowledge file page, where its
857
+ // tools are. The URL alone would route straight back here (every
858
+ // file under a skill's folder IS the skill page); `rawFile` asks the
859
+ // item route for the file route itself, as the plugin page's file
860
+ // links do.
861
+ onOpenInPlatform={
862
+ fileWorkspacePath
863
+ ? () => navigate(kbFileUrl(DEFAULT_BRANCH, fileWorkspacePath), { state: { rawFile: true } })
864
+ : undefined
865
+ }
856
866
  /*
857
867
  * ONE action, decided by the ACL. An `Edit` used to sit beside
858
868
  * `Propose changes` for EVERYONE and jump to the Knowledge editor —
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useId, useState, type ReactNode } from 'react';
2
2
  import { Link, useNavigate, useParams } from 'react-router-dom';
3
3
  import { ChevronRight } from 'lucide-react';
4
- import { HEADER_BAND, HEADER_BAND_LEAD, PAGE_HEADER_TESTID } from '../../../../shared/theme/header';
4
+ import { HEADER_BAND, HEADER_BAND_LEAD, PAGE_HEADER_TESTID, TITLE_INK_ROOM } from '../../../../shared/theme/header';
5
5
  import { cn } from '../../../../lib/utils';
6
6
  import { Banner, Button, buttonClasses } from '../../../../shared/components';
7
7
  import { announceToolCredentialsChanged } from '../../../../core/events';
@@ -191,15 +191,19 @@ export function ToolPage({
191
191
  exactly as on the plugin page: with nowhere to go, anything
192
192
  past the width goes across the way back unless it is clipped.
193
193
  Clipped, the title gives way first and the way back stays
194
- clickable. */}
194
+ clickable.
195
+
196
+ `TITLE_INK_ROOM` on both boxes that clip — the row's
197
+ `overflow-hidden` and the name's `truncate` — so the tails of
198
+ g, y and p survive the clipping, as on every other page title. */}
195
199
  <NameWithBadges
196
200
  as="h1"
197
201
  wrap={false}
198
- className="min-w-0 flex-1 overflow-hidden"
202
+ className={cn('min-w-0 flex-1 overflow-hidden', TITLE_INK_ROOM)}
199
203
  gap="gap-4"
200
204
  leading={<ToolLogo slug={tool.slug} name={tool.name} size="lg" />}
201
205
  name={tool.name}
202
- nameClassName="text-display font-semibold text-ink"
206
+ nameClassName={cn('text-display font-semibold text-ink', TITLE_INK_ROOM)}
203
207
  />
204
208
  {/* No `Manage access` here, deliberately. Access is decided at the
205
209
  PLUGIN — a tool inherits its folder's `access.md`, so an editor
@@ -2,6 +2,7 @@ import { Link, Navigate, useLocation, useParams, useSearchParams } from 'react-r
2
2
  import { DEFAULT_BRANCH, PLUGINS_DIR, SKILLS_DIR, type FileTreeEntry } from '@bevel-software/platform-shared';
3
3
  import { useWorkspace } from '../../workspace/state/workspace.context';
4
4
  import { safeDecode } from '../../workspace/routing/kb-routes';
5
+ import { asksForFilePage } from '../../workspace';
5
6
  import { useLibrary } from '../state/library-data';
6
7
  import type { PluginSummary } from '../services/plugins.api';
7
8
  import { pluginHoldingPath } from '../utils/plugin-summary';
@@ -43,7 +44,9 @@ import { LIBRARY_ROOT, pathForPlugin } from './library-paths';
43
44
  * Router state `rawFile` asks for that raw view OUTRIGHT, whatever the URL
44
45
  * would otherwise resolve to — the tool page's "Edit the tool file", the
45
46
  * plugin page's manifest button. State, not URL: a shared link never carries
46
- * it, so nobody lands on the editor by accident.
47
+ * it, so nobody lands on the editor by accident. The one URL form of the ask
48
+ * is `?as=file` (`kbFilePageUrl`), for a page opened on its file page in a
49
+ * NEW tab, which carries no state — the embed's "Open in the platform".
47
50
  *
48
51
  * The catalog is consulted only to REFINE a tool's slug (a `.tool` may
49
52
  * declare an explicit id different from its filename); the filename is the
@@ -95,8 +98,11 @@ export function WorkspaceItemRoute() {
95
98
  </>
96
99
  );
97
100
 
98
- // Asked for the raw file by name: no resolution, the editor it is.
101
+ // Asked for the raw file by name: no resolution, the editor it is. The
102
+ // query is the same ask from a NEW tab, which has no router state — the
103
+ // embed's "Open in the platform" for a page inside a skill's folder.
99
104
  if ((location.state as { rawFile?: boolean } | null)?.rawFile === true) return fileView();
105
+ if (asksForFilePage(searchParams)) return fileView();
100
106
 
101
107
  /**
102
108
  * `key={name}` is load-bearing. A provisional name gets CORRECTED once the
@@ -47,6 +47,7 @@ import { suggestedPages } from '../utils/fileTree';
47
47
  import { getRendererLayout, isViewOnlyFile, pickFileRenderer } from './renderers';
48
48
  import { READ_PANE } from './renderers/readPane';
49
49
  import { CanDownloadContext } from './renderers/DownloadFileButton';
50
+ import { PageToolsContext } from './renderers/htmlToolBridge';
50
51
  import type { RendererSaveState } from './renderers';
51
52
  import { KbDocumentShell } from './KbDocumentShell';
52
53
  import { FilePaneCard } from './FilePaneCard';
@@ -1189,8 +1190,11 @@ export function FileViewer() {
1189
1190
  // The renderer is a dynamic per-extension lookup resolved in a useMemo
1190
1191
  // above — not a component created during render. The provider hands the
1191
1192
  // open file's `download:` verdict to any DownloadFileButton inside the
1192
- // renderer without widening the renderer contract.
1193
+ // renderer without widening the renderer contract. The page-tools
1194
+ // provider is what makes this the file page for an HTML page: the one
1195
+ // place its `window.bevel.tools` is answered, under its own path.
1193
1196
  <CanDownloadContext.Provider value={access.canDownload}>
1197
+ <PageToolsContext.Provider value={{ pagePath: repoRelativePath ?? openFilePath }}>
1194
1198
  {/* eslint-disable-next-line react-hooks/static-components */}
1195
1199
  <Renderer
1196
1200
  // **Why we key on `openFileSavedContent` (read-only mode only).**
@@ -1247,6 +1251,7 @@ export function FileViewer() {
1247
1251
  onSaveStateChange={setManualSaveState}
1248
1252
  readOnly={isReviewingPending || !(editMode || proposeMode)}
1249
1253
  />
1254
+ </PageToolsContext.Provider>
1250
1255
  </CanDownloadContext.Provider>
1251
1256
  );
1252
1257
 
@@ -14,7 +14,7 @@ import {
14
14
  import { cn } from '../../../lib/utils';
15
15
  import { Badge, Button, IconButton, MenuItem, MenuPanel } from '../../../shared/components';
16
16
  import { useDismissableMenu } from '../../../shared/components';
17
- import { HEADER_BAND, PAGE_HEADER_TESTID } from '../../../shared/theme/header';
17
+ import { HEADER_BAND, PAGE_HEADER_TESTID, TITLE_INK_ROOM } from '../../../shared/theme/header';
18
18
  import { rootAnchoredPath } from '../utils/pasteLink';
19
19
  import { displayFileName, fileNameTooltip } from '../utils/display-file-name';
20
20
  import { SELF_HOLD_MESSAGE } from '../../workflow';
@@ -246,8 +246,11 @@ export function KbPageHeader({
246
246
  band cannot wrap, so something has to give first, and a file name
247
247
  the reader can still hover for (`title`, below) is a far cheaper
248
248
  loss than a Share button pushed off the side of the page. The
249
- chips clip from the right in the order they are least urgent. */}
250
- <div className="flex min-w-0 flex-1 items-center gap-3 overflow-hidden">
249
+ chips clip from the right in the order they are least urgent. The
250
+ ink room is on this group as well as on the title inside it: the
251
+ group clips to the title's line box too, so the tails of g, y and p
252
+ that the title's own room uncovers would be cut off here instead. */}
253
+ <div className={`flex min-w-0 flex-1 items-center gap-3 overflow-hidden ${TITLE_INK_ROOM}`}>
251
254
  {/* `tabIndex={-1}` keeps the heading out of the tab order while letting
252
255
  `.focus()` land on it — the standard way to hand focus to a region
253
256
  after a view swap. No focus ring: this is a programmatic landing
@@ -259,7 +262,7 @@ export function KbPageHeader({
259
262
  // a heading you cannot finish reading needs somewhere to say it. A
260
263
  // platform file shown by its plain name hovers its real one.
261
264
  title={fileNameTooltip(path, kbDirName) ?? titleOf(path, kbDirName)}
262
- className="min-w-0 truncate text-display font-semibold text-ink focus:outline-none"
265
+ className={`min-w-0 truncate text-display font-semibold text-ink focus:outline-none ${TITLE_INK_ROOM}`}
263
266
  >
264
267
  {titleOf(path, kbDirName)}
265
268
  </h1>
@@ -2,6 +2,8 @@ import { describe, it, expect, vi } from 'vitest';
2
2
  import { render, screen, act, fireEvent } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
4
  import { KbPageHeader, type KbPageHeaderProps } from '../KbPageHeader';
5
+ import { PAGE_HEADER_TESTID } from '../../../../shared/theme/header';
6
+ import { expectTitleKeepsItsInk } from '../../../../__tests__/title-ink-room';
5
7
 
6
8
  function renderHeader(overrides: Partial<KbPageHeaderProps> = {}) {
7
9
  const props: KbPageHeaderProps = {
@@ -38,6 +40,11 @@ describe('KbPageHeader', () => {
38
40
  expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Invariant');
39
41
  });
40
42
 
43
+ it('keeps the tails of the title: it truncates, with room for its ink on it and on the group that clips it', () => {
44
+ renderHeader();
45
+ expectTitleKeepsItsInk(screen.getByTestId(PAGE_HEADER_TESTID));
46
+ });
47
+
41
48
  it("titles a plugin's plugin.json Plugin settings, with the file name on hover", () => {
42
49
  renderHeader({ path: 'knowledge-base/Plugins/GTM/plugin.json' });
43
50
  const h1 = screen.getByRole('heading', { level: 1 });
@@ -1,9 +1,19 @@
1
- import { useState, useCallback, useEffect, useRef } from 'react';
1
+ import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
2
2
  import { Pencil, Eye, RotateCw } from 'lucide-react';
3
3
  import { useFileNav } from '../../routing/kb-routes';
4
4
  import type { FileRendererProps, RendererSaveState } from './types';
5
5
  import { buildSandboxedHtml, sanitizeAgentHtml } from './htmlSandbox';
6
6
  import { useRendererSurface } from './rendererSurface';
7
+ import { Button, Dialog } from '../../../../shared/components';
8
+ import {
9
+ PageConsent,
10
+ PageToolsClient,
11
+ answerToolCall,
12
+ asToolCall,
13
+ pageName,
14
+ useOpenPageInPlatform,
15
+ usePageTools,
16
+ } from './htmlToolBridge';
7
17
  import {
8
18
  HTML_FRAME_KEY_STEP,
9
19
  HTML_FRAME_MAX_HEIGHT,
@@ -12,6 +22,13 @@ import {
12
22
  attachFrameResizeHandle,
13
23
  } from './frameResizeHandle';
14
24
 
25
+ /**
26
+ * The card the app shows over a page, outside its frame: the page cannot draw,
27
+ * see or answer it. `write`: the page's first writing call asks the viewer.
28
+ * `platform`: a page that needs tools asked for them where there are none.
29
+ */
30
+ type PageCard = { kind: 'write' | 'platform'; answer: (ok: boolean | null) => void };
31
+
15
32
  /**
16
33
  * Where the reader's chosen frame height is kept, per browser: a
17
34
  * convenience, like a remembered tab. A browser that cannot store it is
@@ -48,10 +65,16 @@ export function HtmlRenderer({
48
65
  onSaveStateChange,
49
66
  readOnly = false,
50
67
  }: FileRendererProps) {
51
- const { openLink } = useFileNav();
68
+ const { openLink, openFilePage } = useFileNav();
69
+ const surface = useRendererSurface();
52
70
  // Whether the surface's host grows with the page (an issue panel) rather
53
71
  // than giving it a pane to scroll in (the app, the MCP App's pane).
54
- const sizesToContent = useRendererSurface()?.sizesToContent === true;
72
+ const sizesToContent = surface?.sizesToContent === true;
73
+ // The viewer's tools, for a page on the app's file page — the one place
74
+ // that provides them. Everywhere else the page gets `bevel.tools = null`.
75
+ const pageTools = usePageTools();
76
+ const openPageInPlatform = useOpenPageInPlatform();
77
+ const toolPagePath = surface === null && pageTools ? pageTools.pagePath : null;
55
78
  const [mode, setMode] = useState<'preview' | 'edit'>('preview');
56
79
  /**
57
80
  * The frame's height where the host grows with the page: the standard
@@ -73,6 +96,12 @@ export function HtmlRenderer({
73
96
  const [reloadKey, setReloadKey] = useState(0);
74
97
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
75
98
  const prevFilePathRef = useRef(filePath);
99
+ const [card, setCard] = useState<PageCard | null>(null);
100
+ const cardRef = useRef<PageCard | null>(null);
101
+ const toolsClient = useMemo(() => (toolPagePath ? new PageToolsClient(toolPagePath) : null), [toolPagePath]);
102
+ // The viewer's answer about this page's writes holds for one VIEW of it: a
103
+ // new frame document (a reload, a saved edit, another file) asks again.
104
+ const consentRef = useRef<PageConsent | null>(null);
76
105
 
77
106
  const dirty = !readOnly && value !== savedValue;
78
107
 
@@ -115,12 +144,13 @@ export function HtmlRenderer({
115
144
  // extension.)
116
145
  libModuleSources: [],
117
146
  bodyHtml: sanitizeAgentHtml(savedValue),
147
+ toolBridge: toolPagePath !== null,
118
148
  });
119
149
  setBundledSrcdoc(doc);
120
150
  } catch (err) {
121
151
  setPreviewError(err instanceof Error ? err.message : 'Failed to build preview');
122
152
  }
123
- }, [mode, savedValue, filePath, reloadKey]);
153
+ }, [mode, savedValue, filePath, reloadKey, toolPagePath]);
124
154
 
125
155
  // (The enterprise build additionally installs a postMessage bridge here that
126
156
  // serves the iframe's KB-graph client from `/api/workspace/:id/graph` — the
@@ -148,6 +178,100 @@ export function HtmlRenderer({
148
178
  return () => window.removeEventListener('message', onNavMessage);
149
179
  }, [openLink, filePath]);
150
180
 
181
+ /** Show one of the app's cards over the page and resolve with the viewer's answer. A card already up answers this ask too. */
182
+ function showCard(kind: PageCard['kind']): Promise<boolean | null> {
183
+ const open = cardRef.current;
184
+ if (open && open.kind === kind) {
185
+ return new Promise((resolve) => {
186
+ const first = open.answer;
187
+ open.answer = (ok) => {
188
+ first(ok);
189
+ resolve(ok);
190
+ };
191
+ });
192
+ }
193
+ return new Promise((resolve) => {
194
+ const next: PageCard = { kind, answer: resolve };
195
+ cardRef.current = next;
196
+ setCard(next);
197
+ });
198
+ }
199
+
200
+ /** Close the card with the viewer's answer, or null when the view went before they gave one. */
201
+ const closeCard = useCallback((ok: boolean | null) => {
202
+ const open = cardRef.current;
203
+ cardRef.current = null;
204
+ setCard(null);
205
+ open?.answer(ok);
206
+ }, []);
207
+
208
+ // When the page's document goes (a reload, a saved edit, another file, or
209
+ // Edit, which unmounts the frame even when the document comes back the same)
210
+ // its consent goes with it, and a card left open answers no: nothing the old
211
+ // view asked for runs in the new one.
212
+ useEffect(
213
+ () => () => {
214
+ consentRef.current = null;
215
+ closeCard(null);
216
+ },
217
+ [bundledSrcdoc, reloadKey, mode, closeCard],
218
+ );
219
+
220
+ // Tool bridge: a page's `window.bevel.tools` calls and its
221
+ // `requireTools()`, posted by the runtime in the frame (see
222
+ // `htmlSandbox.ts`), answered here with the viewer's session.
223
+ useEffect(() => {
224
+ function onToolMessage(event: MessageEvent) {
225
+ const iframeWin = iframeRef.current?.contentWindow;
226
+ if (!iframeWin || event.source !== iframeWin) return;
227
+ const reply = (message: unknown) => {
228
+ // Only to the document that asked: a reloaded frame is a new window.
229
+ if (iframeRef.current?.contentWindow === iframeWin) iframeWin.postMessage(message, '*');
230
+ };
231
+ const data = event.data as { type?: unknown; requestId?: unknown } | null;
232
+ if (data && data.type === 'bevel.tools.require' && typeof data.requestId === 'string') {
233
+ const requestId = data.requestId;
234
+ if (toolsClient) {
235
+ reply({ type: 'bevel.tools.require.response', requestId, ok: true, result: true });
236
+ return;
237
+ }
238
+ void showCard('platform').then(() =>
239
+ // Either way the page that asked carries on without tools: Open in
240
+ // the platform opened it elsewhere, it did not give it tools here.
241
+ reply({ type: 'bevel.tools.require.response', requestId, ok: true, result: false }),
242
+ );
243
+ return;
244
+ }
245
+ const call = asToolCall(data);
246
+ if (!call) return;
247
+ if (!toolsClient) {
248
+ reply({
249
+ type: 'bevel.tool.response',
250
+ requestId: call.requestId,
251
+ ok: false,
252
+ error: 'Tools are only available on the page in the platform.',
253
+ code: 'unavailable',
254
+ });
255
+ return;
256
+ }
257
+ consentRef.current ??= new PageConsent(() => showCard('write'));
258
+ void answerToolCall(call, toolsClient, consentRef.current).then(reply);
259
+ }
260
+ window.addEventListener('message', onToolMessage);
261
+ return () => window.removeEventListener('message', onToolMessage);
262
+ }, [toolsClient]);
263
+
264
+ const openInPlatform = useCallback(() => {
265
+ closeCard(false);
266
+ // The host's own way when it has one (a skill page, whose filePath is
267
+ // relative to the skill); otherwise the file page, by an address that
268
+ // asks for it outright: on the embed the surface opens it through the
269
+ // host in a new tab, which carries no router state, and a page inside a
270
+ // skill's folder would otherwise open as that skill's page again.
271
+ if (openPageInPlatform) openPageInPlatform();
272
+ else openFilePage(filePath);
273
+ }, [closeCard, openPageInPlatform, openFilePage, filePath]);
274
+
151
275
  useEffect(() => {
152
276
  frameHeightRef.current = frameHeight;
153
277
  }, [frameHeight]);
@@ -325,6 +449,42 @@ export function HtmlRenderer({
325
449
  Loading preview…
326
450
  </div>
327
451
  )}
452
+ <Dialog
453
+ open={card?.kind === 'write'}
454
+ onClose={() => closeCard(false)}
455
+ title={`${pageName(filePath)} wants to write to the knowledge base`}
456
+ size="md"
457
+ footer={
458
+ <>
459
+ <Button variant="outline" onClick={() => closeCard(false)}>
460
+ Deny
461
+ </Button>
462
+ <Button variant="primary" onClick={() => closeCard(true)}>
463
+ Allow while open
464
+ </Button>
465
+ </>
466
+ }
467
+ >
468
+ <p className="font-mono text-detail text-ink-muted break-all">{toolPagePath ?? filePath}</p>
469
+ </Dialog>
470
+ <Dialog
471
+ open={card?.kind === 'platform'}
472
+ onClose={() => closeCard(false)}
473
+ title={`${pageName(filePath)} uses tools that are only available in the platform`}
474
+ size="md"
475
+ footer={
476
+ <>
477
+ <Button variant="outline" onClick={() => closeCard(false)}>
478
+ Continue without tools
479
+ </Button>
480
+ <Button variant="primary" onClick={openInPlatform}>
481
+ Open in the platform
482
+ </Button>
483
+ </>
484
+ }
485
+ >
486
+ <p className="font-mono text-detail text-ink-muted break-all">{filePath}</p>
487
+ </Dialog>
328
488
  </div>
329
489
  );
330
490
  }
@@ -12,6 +12,7 @@ function surface(extra: Partial<RendererSurface>): RendererSurface {
12
12
  kbDirName: 'knowledge-base',
13
13
  openLink: () => undefined,
14
14
  openWorkspacePath: () => undefined,
15
+ openFilePage: () => undefined,
15
16
  openNodeId: () => undefined,
16
17
  canonicalUrlFor: () => null,
17
18
  rawUrl: (path) => `/raw/${path}`,