@bevel-software/platform-core-frontend 0.32.0 → 0.33.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 (167) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +1 -1
  3. package/src/modules/access/api.ts +1 -1
  4. package/src/modules/access/components/ManageAccessDialog.tsx +4 -5
  5. package/src/modules/access/hooks/useAccessRequests.ts +1 -1
  6. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  7. package/src/modules/access/index.ts +11 -0
  8. package/src/modules/access/requests.api.ts +1 -1
  9. package/src/modules/admin/components/AddMemberInput.tsx +1 -1
  10. package/src/modules/admin/components/UserAccountsPage.tsx +3 -3
  11. package/src/modules/admin/index.ts +7 -0
  12. package/src/modules/admin/state/admin.context.tsx +1 -1
  13. package/src/modules/audit/components/AuditEventsPanel.tsx +1 -1
  14. package/src/modules/audit/components/AuditLogPage.tsx +2 -2
  15. package/src/modules/auth/index.ts +12 -0
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +0 -1
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +0 -1
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +0 -1
  19. package/src/modules/change-requests/__tests__/ChangeRequestDialog.edit.test.tsx +166 -0
  20. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +0 -1
  21. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +0 -1
  22. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +0 -1
  23. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +0 -1
  24. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +0 -2
  25. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +0 -1
  26. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +0 -1
  27. package/src/modules/change-requests/components/BranchFilePreview.tsx +4 -12
  28. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +138 -30
  29. package/src/modules/change-requests/components/ChangeRequestLink.tsx +2 -3
  30. package/src/modules/change-requests/components/CrFileTree.tsx +1 -1
  31. package/src/modules/change-requests/components/FileChangeBoxes.tsx +2 -3
  32. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +3 -5
  33. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +1 -1
  34. package/src/modules/change-requests/index.ts +14 -0
  35. package/src/modules/change-requests/services/change-requests.api.ts +2 -2
  36. package/src/modules/change-requests/services/denied-file.api.ts +2 -2
  37. package/src/modules/change-requests/services/propose.api.ts +3 -4
  38. package/src/modules/change-requests/utils/diff.ts +1 -1
  39. package/src/modules/change-requests/utils/readFailure.ts +1 -1
  40. package/src/modules/embed/__tests__/EmbedView.test.tsx +19 -2
  41. package/src/modules/embed/components/EmbedLinkPage.tsx +1 -2
  42. package/src/modules/git/components/BranchSwitcher.tsx +3 -4
  43. package/src/modules/git/components/FileHistoryPanel.tsx +2 -2
  44. package/src/modules/git/components/GitSyncFailedBanner.tsx +2 -4
  45. package/src/modules/git/components/HistoryVersionPreview.tsx +4 -15
  46. package/src/modules/git/components/PullNeededBanner.tsx +1 -1
  47. package/src/modules/git/hooks/useAutoPullUpdates.ts +1 -1
  48. package/src/modules/git/index.ts +11 -0
  49. package/src/modules/layout/components/MobileChatLayout.tsx +1 -1
  50. package/src/modules/layout/index.ts +9 -0
  51. package/src/modules/library/__tests__/SkillPage.test.tsx +39 -0
  52. package/src/modules/library/__tests__/propose-change.test.ts +75 -0
  53. package/src/modules/library/components/AddToPluginDialog.tsx +1 -1
  54. package/src/modules/library/components/ChangeRequestDock.tsx +1 -1
  55. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  56. package/src/modules/library/components/LibraryPage.tsx +3 -3
  57. package/src/modules/library/components/ManagedPluginRequests.tsx +1 -1
  58. package/src/modules/library/components/NewSkillPanel.tsx +2 -2
  59. package/src/modules/library/components/PersonalAddDialog.tsx +1 -1
  60. package/src/modules/library/components/PersonalPluginPage.tsx +1 -1
  61. package/src/modules/library/components/PluginExtras.tsx +1 -4
  62. package/src/modules/library/components/PluginPage.tsx +1 -1
  63. package/src/modules/library/components/PluginRows.tsx +1 -1
  64. package/src/modules/library/components/SkillsTree.tsx +1 -4
  65. package/src/modules/library/components/plugin-page-parts.tsx +1 -1
  66. package/src/modules/library/components/skill-page/SkillFilePane.tsx +19 -7
  67. package/src/modules/library/components/skill-page/SkillPage.tsx +19 -26
  68. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +2 -4
  69. package/src/modules/library/components/tool-page/ToolVarRow.tsx +2 -2
  70. package/src/modules/library/hooks/useJoinRequests.ts +1 -1
  71. package/src/modules/library/hooks/useLibraryData.ts +3 -3
  72. package/src/modules/library/hooks/useToolPage.ts +1 -1
  73. package/src/modules/library/hooks/useToolSource.ts +1 -1
  74. package/src/modules/library/index.ts +12 -0
  75. package/src/modules/library/routes/LibraryRoutes.tsx +1 -1
  76. package/src/modules/library/routes/WorkspaceItemRoute.tsx +1 -3
  77. package/src/modules/library/routes/library-paths.ts +1 -1
  78. package/src/modules/library/services/library.api.ts +10 -8
  79. package/src/modules/library/services/plugins.api.ts +1 -1
  80. package/src/modules/library/services/teams.api.ts +1 -1
  81. package/src/modules/library/utils/status.ts +2 -2
  82. package/src/modules/onboarding/components/ConnectAgentPill.tsx +1 -1
  83. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +2 -3
  84. package/src/modules/onboarding/components/GetStartedColumn.tsx +6 -13
  85. package/src/modules/onboarding/components/InviteButton.tsx +2 -2
  86. package/src/modules/onboarding/components/InviteDialog.tsx +4 -6
  87. package/src/modules/onboarding/components/RootLanding.tsx +2 -2
  88. package/src/modules/onboarding/components/StarterPackCard.tsx +1 -1
  89. package/src/modules/onboarding/components/WelcomePage.tsx +2 -5
  90. package/src/modules/onboarding/index.ts +10 -0
  91. package/src/modules/onboarding/paths.ts +1 -1
  92. package/src/modules/onboarding/state/agent-connection.ts +2 -2
  93. package/src/modules/onboarding/state/onboarding.ts +1 -1
  94. package/src/modules/onboarding/state/starter-packs.ts +1 -1
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +1 -1
  96. package/src/modules/pr/index.ts +14 -0
  97. package/src/modules/pr/services/pr-approvals.api.ts +1 -1
  98. package/src/modules/pr/services/pr-cancel.api.ts +1 -1
  99. package/src/modules/pr/services/pr-detail.api.ts +2 -2
  100. package/src/modules/pr/services/pr-edit.api.ts +22 -0
  101. package/src/modules/pr/services/pr-merge.api.ts +1 -1
  102. package/src/modules/pr/services/pr-open.api.ts +1 -1
  103. package/src/modules/review/components/DiffViewer.tsx +1 -1
  104. package/src/modules/review/components/MarkdownDiffViewer.tsx +1 -2
  105. package/src/modules/review/components/ReviewPanel.tsx +2 -3
  106. package/src/modules/review/state/ReviewProvider.tsx +2 -2
  107. package/src/modules/secrets-vault/index.ts +6 -0
  108. package/src/modules/settings/components/DeploymentPage.tsx +2 -2
  109. package/src/modules/settings/components/SettingsLayout.tsx +2 -2
  110. package/src/modules/settings/index.ts +8 -0
  111. package/src/modules/setup/components/FirstRunStorage.tsx +1 -1
  112. package/src/modules/setup/index.ts +6 -0
  113. package/src/modules/toolbar/commands/actions.tsx +3 -3
  114. package/src/modules/toolbar/commands/useCommandActions.ts +5 -9
  115. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +2 -2
  116. package/src/modules/toolbar/components/AppSwitcher.tsx +1 -2
  117. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +1 -1
  118. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +1 -1
  119. package/src/modules/toolbar/components/ProfileMenu.tsx +3 -3
  120. package/src/modules/toolbar/components/SearchPalette.tsx +4 -8
  121. package/src/modules/toolbar/components/Toolbar.tsx +2 -5
  122. package/src/modules/toolbar/index.ts +6 -0
  123. package/src/modules/toolbar/search/sources.ts +4 -7
  124. package/src/modules/toolbar/services/agent-instructions.api.ts +1 -1
  125. package/src/modules/tools/ToolsExplorerPage.tsx +217 -18
  126. package/src/modules/tools/__tests__/ToolsExplorerPage.read-only.test.tsx +220 -0
  127. package/src/modules/tools/tool-hints.api.ts +44 -0
  128. package/src/modules/workflow/index.ts +7 -0
  129. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +1 -0
  130. package/src/modules/workflow/state/EventBusFocusBinder.tsx +1 -1
  131. package/src/modules/workspace/components/FileExplorer.tsx +35 -8
  132. package/src/modules/workspace/components/FilePaneCard.tsx +37 -12
  133. package/src/modules/workspace/components/FileRoute.tsx +10 -3
  134. package/src/modules/workspace/components/FileViewer.tsx +169 -25
  135. package/src/modules/workspace/components/FullScreenView.tsx +93 -0
  136. package/src/modules/workspace/components/KbFileRail.tsx +1 -1
  137. package/src/modules/workspace/components/KbPageHeader.tsx +9 -0
  138. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +137 -0
  139. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +11 -0
  140. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +487 -3
  141. package/src/modules/workspace/components/readingCarry.ts +59 -0
  142. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +36 -175
  143. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +1 -1
  144. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +168 -42
  145. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +20 -3
  146. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +63 -4
  147. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +235 -1
  148. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +14 -3
  149. package/src/modules/workspace/components/renderers/__tests__/pageToolsHarness.ts +79 -0
  150. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +316 -0
  151. package/src/modules/workspace/components/renderers/htmlSandbox.ts +75 -13
  152. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +196 -25
  153. package/src/modules/workspace/components/renderers/index.ts +10 -0
  154. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +253 -0
  155. package/src/modules/workspace/hooks/useFullScreenView.ts +52 -0
  156. package/src/modules/workspace/hooks/useImageRevision.ts +1 -1
  157. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +1 -1
  158. package/src/modules/workspace/hooks/useLastCommit.ts +1 -1
  159. package/src/modules/workspace/hooks/useWorkspaceState.ts +4 -4
  160. package/src/modules/workspace/index.ts +30 -1
  161. package/src/modules/workspace/routing/kb-routes.ts +1 -1
  162. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +0 -1
  163. package/src/modules/workspace/state/open-change-requests.tsx +1 -1
  164. package/src/modules/workspace/utils/frameEscape.ts +15 -0
  165. package/src/modules/workspace/utils/treeConfirm.ts +1 -1
  166. package/src/shared/theme/measure.ts +7 -0
  167. package/src/modules/pr/services/pr-comments.api.ts +0 -45
@@ -9,32 +9,45 @@ import { authFetch } from '../../../../lib/api';
9
9
  * the viewer's session, so a page sees and reaches exactly the tools the
10
10
  * viewer's own agent does — the same listing, the same refusals, nothing of
11
11
  * the enterprise agent's internal tools — and the server records it in the
12
- * Audit log under the page's path (`X-Bevel-Page`). The four members map to
12
+ * Audit log under the page's path (`X-Bevel-Page`). The five members map to
13
13
  * what an agent calls:
14
14
  *
15
- * searchTools(query) → `list_tools`, narrowed to the names that contain
16
- * every word of `query` (all of them for an empty one)
17
- * toolsInfo(names) → `tools_info`
18
- * callTool(name, args) → `tools/call`
19
- * callToolChain(code) → `call_tool_chain`
15
+ * searchTools(query) → `list_tools`, narrowed to the names that
16
+ * contain every word of `query` (all of them
17
+ * for an empty one)
18
+ * toolsInfo(names) → `tools_info`
19
+ * callTool(name, args) → `tools/call`
20
+ * callToolChain(code) → `call_tool_chain`
21
+ * uploadFile(file, options) → `request_file_upload`, the bytes POSTed to the
22
+ * upload endpoint, then `apply_file_upload`
20
23
  *
21
24
  * A call that only reads runs at once. A call that may write — a tool the
22
25
  * deployment's UTCP manual tags `write`, a tool the manual does not list (a
23
- * `.tool`'s, a plugin's MCP server's: nothing says they only read), and every
24
- * chain (a chain may call writers) — waits for the viewer's answer to one
25
- * card per page view. See {@link PageConsent}.
26
+ * `.tool`'s, a plugin's MCP server's: nothing says they only read), every
27
+ * chain (a chain may call writers) and every upload — waits for the viewer's
28
+ * answer to one card per page view. See {@link PageConsent}.
26
29
  */
27
30
 
28
- /** What the file page tells the HTML renderer: that tools are answered here, and for which page. */
31
+ /** What a host that is the platform tells the HTML renderer: that tools are answered here, and for which page. */
29
32
  export interface PageTools {
30
33
  /** The page's knowledge-base path (`Dashboards/Roadmap.html`), what the Audit log shows as the agent. */
31
34
  pagePath: string;
32
35
  }
33
36
 
34
37
  /**
35
- * Provided by the app's file page and nowhere else: its presence is what
36
- * gives a page `window.bevel.tools`. The embed, a skill page and every other
37
- * preview mount the renderer without it, and their pages get `null`.
38
+ * Its presence is what gives a page `window.bevel.tools`. The hosts that
39
+ * provide it — the surfaces the app itself shows a page on, and only those:
40
+ *
41
+ * - the file page (`FileViewer.tsx`);
42
+ * - the skill page's file pane (`SkillFilePane.tsx`), under the file's
43
+ * knowledge-base path — the one the file page uses — never the
44
+ * skill-relative tab name.
45
+ *
46
+ * Every other mount goes without, and its pages get `null`: the embed and
47
+ * the MCP App pane (outside the platform — they show the "only available in
48
+ * the platform" card), the change-request file preview and the history
49
+ * preview (a page shown as a version, not opened). A new host is added
50
+ * here, deliberately, or not at all.
38
51
  */
39
52
  export const PageToolsContext = createContext<PageTools | null>(null);
40
53
 
@@ -54,14 +67,23 @@ export function useOpenPageInPlatform(): (() => void) | null {
54
67
  return useContext(OpenPageInPlatformContext);
55
68
  }
56
69
 
57
- /** The four members a page calls, by the name the frame posts. */
58
- export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain';
70
+ /** The five members a page calls, by the name the frame posts. */
71
+ export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain' | 'uploadFile';
59
72
 
60
- const PAGE_TOOL_FUNCTIONS: ReadonlySet<string> = new Set(['searchTools', 'toolsInfo', 'callTool', 'callToolChain']);
73
+ const PAGE_TOOL_FUNCTIONS: ReadonlySet<string> = new Set([
74
+ 'searchTools',
75
+ 'toolsInfo',
76
+ 'callTool',
77
+ 'callToolChain',
78
+ 'uploadFile',
79
+ ]);
61
80
 
62
81
  /** The code-mode meta-tools by the name a page may also `callTool` them under: two read, the chain may write. */
63
82
  const READING_META_TOOLS: ReadonlySet<string> = new Set(['list_tools', 'tools_info']);
64
83
  const CHAIN_TOOL = 'call_tool_chain';
84
+ /** The agent upload path a page's `uploadFile` runs: the token, then the bytes, then the landing. */
85
+ const UPLOAD_REQUEST_TOOL = 'request_file_upload';
86
+ const UPLOAD_APPLY_TOOL = 'apply_file_upload';
65
87
 
66
88
  /** The answer a page gets when its viewer chose Deny. */
67
89
  export const DENIED = 'denied';
@@ -133,6 +155,72 @@ export class PageToolsClient {
133
155
  return this.callTool(CHAIN_TOOL, { code });
134
156
  }
135
157
 
158
+ /**
159
+ * Put a file into the knowledge base the way an agent does, with the
160
+ * viewer's session: `request_file_upload` for a token, the file's bytes
161
+ * POSTed as the raw body to the upload endpoint with the token in the
162
+ * `x-upload-token` header (never in the address, and never back to the
163
+ * page), then `apply_file_upload` into `destination` on `branch`.
164
+ *
165
+ * Resolves with what `apply_file_upload` answers, every path listed (the
166
+ * apply is asked with `all: true`). Rejects with the message
167
+ * of the step that failed: the upload endpoint's own (a file over the
168
+ * deployment's limit is refused there, naming it, before the apply runs),
169
+ * or the apply's — thrown whole (a destination the viewer may not write),
170
+ * or, when the upload landed no path at all, the first path's refusal with
171
+ * its code (`exists` under `create`, `missing` under `update`).
172
+ *
173
+ * The token is this call's alone — the page never sees it, so nobody can
174
+ * retry with it — so whenever no apply answered, it is given up at once
175
+ * (`DELETE` on the same endpoint, the token again in the header) and any
176
+ * bytes staged with it are deleted rather than left until it expires. An
177
+ * apply that answered has spent the token itself.
178
+ */
179
+ async uploadFile(file: unknown, options: unknown): Promise<unknown> {
180
+ const opts = (options && typeof options === 'object' ? options : {}) as Record<string, unknown>;
181
+ if (!(file instanceof Blob)) throw new PageToolError('uploadFile needs a File, or a Blob with a `name` option.');
182
+ const name = typeof opts.name === 'string' && opts.name !== '' ? opts.name : file instanceof File ? file.name : '';
183
+ if (name === '') throw new PageToolError('uploadFile needs a file name: pass a File, or a Blob with a `name` option.');
184
+ const { branch, destination, mode } = opts;
185
+ if (typeof branch !== 'string' || branch === '') throw new PageToolError('uploadFile needs `branch`.');
186
+ if (typeof destination !== 'string' || destination === '') {
187
+ throw new PageToolError('uploadFile needs `destination`, the folder the file lands in.');
188
+ }
189
+
190
+ const issued = (await this.callTool(UPLOAD_REQUEST_TOOL, { body: {} })) as { uploadUrl?: unknown; token?: unknown };
191
+ if (typeof issued?.uploadUrl !== 'string' || typeof issued.token !== 'string') {
192
+ throw new PageToolError('The upload could not start: the server answered no upload address.');
193
+ }
194
+ const token = issued.token;
195
+ const address = headerAddress(issued.uploadUrl);
196
+ let answer: { count?: unknown; files?: unknown };
197
+ try {
198
+ const sent = await this.fetchImpl(`${address}?filename=${encodeURIComponent(name)}`, {
199
+ method: 'POST',
200
+ headers: { 'Content-Type': 'application/octet-stream', 'x-upload-token': token },
201
+ body: file,
202
+ });
203
+ if (!sent.ok) throw new PageToolError(await refusalOf(sent));
204
+ // `all: true`: the page gets every path's outcome, never the tool's
205
+ // 25-entry cut with a `truncated` flag it has no way to act on.
206
+ answer = (await this.callTool(UPLOAD_APPLY_TOOL, {
207
+ body: { branch, token, destination, all: true, ...(mode !== undefined ? { mode } : {}) },
208
+ })) as { count?: unknown; files?: unknown };
209
+ } catch (err) {
210
+ await this.discardUpload(address, token);
211
+ throw err;
212
+ }
213
+ const files = Array.isArray(answer?.files) ? (answer.files as Array<Record<string, unknown>>) : [];
214
+ if (answer?.count === 0 && files.length > 0) {
215
+ const refused = files[0]!;
216
+ throw new PageToolError(
217
+ typeof refused.message === 'string' ? refused.message : 'Nothing was written.',
218
+ typeof refused.error === 'string' ? refused.error : undefined,
219
+ );
220
+ }
221
+ return answer;
222
+ }
223
+
136
224
  /**
137
225
  * `tools/call`, answered the way the page reads it: the tool's structured
138
226
  * content when it has some, else its text — parsed when it is JSON. A tool
@@ -153,7 +241,7 @@ export class PageToolsClient {
153
241
  */
154
242
  async mayWrite(fn: PageToolFunction, args: unknown[]): Promise<boolean> {
155
243
  if (fn === 'searchTools' || fn === 'toolsInfo') return false;
156
- if (fn === 'callToolChain') return true;
244
+ if (fn === 'callToolChain' || fn === 'uploadFile') return true;
157
245
  const name = args[0];
158
246
  if (typeof name !== 'string') return false; // refused by callTool itself, before anything runs
159
247
  if (READING_META_TOOLS.has(name)) return false;
@@ -176,6 +264,15 @@ export class PageToolsClient {
176
264
  }
177
265
  }
178
266
 
267
+ /** Give an unapplied upload token up, with its staged bytes. Best-effort: the refusal stands either way. */
268
+ private async discardUpload(address: string, token: string): Promise<void> {
269
+ try {
270
+ await this.fetchImpl(address, { method: 'DELETE', headers: { 'x-upload-token': token } });
271
+ } catch {
272
+ // Unreached, the token still expires, and its bytes with it.
273
+ }
274
+ }
275
+
179
276
  /** The deployment's UTCP manual, read at most once a `MANUAL_TTL_MS`: tool name → whether it is tagged `write`. */
180
277
  private writingTools(): Promise<Map<string, boolean> | null> {
181
278
  const now = this.now();
@@ -219,6 +316,26 @@ export class PageToolsClient {
219
316
  }
220
317
  }
221
318
 
319
+ /**
320
+ * The upload endpoint's header-token address: `uploadUrl` without its token
321
+ * segment, on this app's own origin — the server builds `uploadUrl` from its
322
+ * public base URL, which the browser may reach under another name.
323
+ */
324
+ function headerAddress(uploadUrl: string): string {
325
+ return new URL(uploadUrl, 'http://app.invalid').pathname.replace(/\/[^/]*$/, '');
326
+ }
327
+
328
+ /** The `{ error }` an HTTP refusal carries, or its status when it carries none. */
329
+ async function refusalOf(res: Response): Promise<string> {
330
+ try {
331
+ const body = (await res.json()) as { error?: unknown };
332
+ if (typeof body?.error === 'string' && body.error !== '') return body.error;
333
+ } catch {
334
+ // Not JSON: say what the status says.
335
+ }
336
+ return `The upload was refused (HTTP ${res.status}).`;
337
+ }
338
+
222
339
  interface RpcMessage {
223
340
  id?: unknown;
224
341
  result?: unknown;
@@ -271,9 +388,15 @@ function toPageResult(result: CallToolResult | undefined): unknown {
271
388
  * call asks again. Calls that arrive while the card is open wait on that same
272
389
  * card, so a page that fires ten writes at once sees one card, and every one
273
390
  * of the ten gets the answer.
391
+ *
392
+ * When the view ends the renderer {@link PageConsent.close}s it: from then on
393
+ * nothing asks and nothing is allowed, so a call the old view made that is
394
+ * still being decided when it ends is answered `closed` instead of opening a
395
+ * card in the next view, or running on an Allow the old view gave.
274
396
  */
275
397
  export class PageConsent {
276
398
  private allowed = false;
399
+ private ended = false;
277
400
  private asking: Promise<boolean | null> | null = null;
278
401
  private readonly ask: () => Promise<boolean | null>;
279
402
 
@@ -287,12 +410,24 @@ export class PageConsent {
287
410
  return this.asking;
288
411
  }
289
412
 
290
- /** Whether the viewer allows this page to write, asking them if no answer holds; null when nobody answered. */
413
+ /** Whether the view this consent belongs to has ended. */
414
+ get closed(): boolean {
415
+ return this.ended;
416
+ }
417
+
418
+ /** The view ended: every request from now on answers null and asks nobody. */
419
+ close(): void {
420
+ this.ended = true;
421
+ }
422
+
423
+ /** Whether the viewer allows this page to write, asking them if no answer holds; null when nobody answered or the view ended. */
291
424
  request(): Promise<boolean | null> {
425
+ if (this.ended) return Promise.resolve(null);
292
426
  if (this.allowed) return Promise.resolve(true);
293
427
  this.asking ??= this.ask().then(
294
428
  (ok) => {
295
429
  this.asking = null;
430
+ if (this.ended) return null;
296
431
  if (ok) this.allowed = true;
297
432
  return ok;
298
433
  },
@@ -309,6 +444,8 @@ export class PageConsent {
309
444
  export interface ToolCallMessage {
310
445
  type: 'bevel.tool.call';
311
446
  requestId: string;
447
+ /** The identity the app minted for the document that posted this (see `htmlSandbox.ts`), when it was given one. */
448
+ documentId?: string;
312
449
  fn: PageToolFunction;
313
450
  args: unknown[];
314
451
  }
@@ -324,13 +461,22 @@ export function asToolCall(data: unknown): ToolCallMessage | null {
324
461
  const msg = data as Partial<ToolCallMessage>;
325
462
  if (msg.type !== 'bevel.tool.call' || typeof msg.requestId !== 'string') return null;
326
463
  if (typeof msg.fn !== 'string' || !PAGE_TOOL_FUNCTIONS.has(msg.fn)) return null;
327
- return { type: 'bevel.tool.call', requestId: msg.requestId, fn: msg.fn, args: Array.isArray(msg.args) ? msg.args : [] };
464
+ return {
465
+ type: 'bevel.tool.call',
466
+ requestId: msg.requestId,
467
+ ...(typeof msg.documentId === 'string' ? { documentId: msg.documentId } : {}),
468
+ fn: msg.fn,
469
+ args: Array.isArray(msg.args) ? msg.args : [],
470
+ };
328
471
  }
329
472
 
473
+ const CLOSED_MESSAGE = 'The page was closed before the viewer answered.';
474
+
330
475
  /**
331
476
  * Answer one of a page's tool calls: wait out an open card, ask for consent
332
- * when the call may write, run it, and say how it went. Never throws — every
333
- * outcome is a response for the frame.
477
+ * when the call may write, run it, and say how it went. A call whose view
478
+ * ended (its `consent` closed) before it was decided runs nothing and is
479
+ * answered `closed`. Never throws — every outcome is a response for the frame.
334
480
  */
335
481
  export async function answerToolCall(
336
482
  msg: ToolCallMessage,
@@ -349,10 +495,9 @@ export async function answerToolCall(
349
495
  // A write that arrives while the card is open joins it, and gets its answer.
350
496
  const allowed = await consent.request();
351
497
  // The view ended before the viewer chose: nothing ran, and nobody refused.
352
- if (allowed === null) return fail('The page was closed before the viewer answered.', 'closed');
498
+ if (allowed === null) return fail(CLOSED_MESSAGE, 'closed');
353
499
  if (!allowed) {
354
- const name = msg.fn === 'callToolChain' ? CHAIN_TOOL : String(msg.args[0] ?? '');
355
- const args = msg.fn === 'callToolChain' ? { code: msg.args[0] } : msg.args[1];
500
+ const { name, args } = refusedCall(msg);
356
501
  void client.recordRefusal(name, args);
357
502
  return fail(DENIED, DENIED);
358
503
  }
@@ -360,6 +505,8 @@ export async function answerToolCall(
360
505
  // Nothing of the page runs while the viewer is being asked about it.
361
506
  while (consent.open) await consent.open;
362
507
  }
508
+ // The view ended while the call was being decided: it is no longer the view's to run.
509
+ if (consent.closed) return fail(CLOSED_MESSAGE, 'closed');
363
510
  const [a, b] = msg.args;
364
511
  const result =
365
512
  msg.fn === 'searchTools'
@@ -368,13 +515,37 @@ export async function answerToolCall(
368
515
  ? await client.toolsInfo(a)
369
516
  : msg.fn === 'callToolChain'
370
517
  ? await client.callToolChain(a)
371
- : await client.callTool(a, b);
518
+ : msg.fn === 'uploadFile'
519
+ ? await client.uploadFile(a, b)
520
+ : await client.callTool(a, b);
372
521
  return { type: 'bevel.tool.response', requestId: msg.requestId, ok: true, result };
373
522
  } catch (err) {
374
523
  return fail(err instanceof Error ? err.message : String(err), err instanceof PageToolError ? err.code : undefined);
375
524
  }
376
525
  }
377
526
 
527
+ /**
528
+ * A refused call as the Audit log names it: the tool the page asked for, with
529
+ * the arguments it would have run with. An upload is refused as the
530
+ * `apply_file_upload` it would have ended in: its `body` holds only what that
531
+ * tool takes (no token, since none was asked for), and the file's name — not
532
+ * an argument of the tool, it travels with the bytes — sits beside it as
533
+ * `file`, so the record says what was refused without inventing an argument.
534
+ */
535
+ function refusedCall(msg: ToolCallMessage): { name: string; args: unknown } {
536
+ const [a, b] = msg.args;
537
+ if (msg.fn === 'callToolChain') return { name: CHAIN_TOOL, args: { code: a } };
538
+ if (msg.fn === 'uploadFile') {
539
+ const opts = (b && typeof b === 'object' ? b : {}) as Record<string, unknown>;
540
+ const file = typeof opts.name === 'string' ? opts.name : a instanceof File ? a.name : undefined;
541
+ return {
542
+ name: UPLOAD_APPLY_TOOL,
543
+ args: { body: { branch: opts.branch, destination: opts.destination, mode: opts.mode }, file },
544
+ };
545
+ }
546
+ return { name: String(a ?? ''), args: b };
547
+ }
548
+
378
549
  /** A page's display name: its file name without the extension. */
379
550
  export function pageName(path: string): string {
380
551
  const file = path.slice(path.lastIndexOf('/') + 1);
@@ -21,6 +21,16 @@ export {
21
21
  // and a renderer is tested through this module's entry, never its files.
22
22
  export { RendererSurfaceContext, useRendererSurface, type RendererRawRead, type RendererSurface } from './rendererSurface';
23
23
  export { CanDownloadContext } from './DownloadFileButton';
24
+ // The page tool bridge, for every renderer that shows an HTML page: the one
25
+ // controller a renderer calls for a page's `window.bevel.tools`, and the two
26
+ // contexts a host provides it through (the file page's tools; a skill
27
+ // page's way to the platform). A renderer and its tests need nothing else.
28
+ export {
29
+ useHtmlToolBridge,
30
+ type HtmlToolBridgeOptions,
31
+ type HtmlToolBridgeResult,
32
+ } from './useHtmlToolBridge';
33
+ export { OpenPageInPlatformContext, PageToolsContext, type PageTools } from './htmlToolBridge';
24
34
  export { useKbGraphLoader } from './kbGraphLoader';
25
35
 
26
36
  /**
@@ -0,0 +1,253 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
2
+ import { useFileNav } from '../../routing/kb-routes';
3
+ import { useRendererSurface } from './rendererSurface';
4
+ import { Button, Dialog } from '../../../../shared/components';
5
+ import {
6
+ PageConsent,
7
+ PageToolsClient,
8
+ answerToolCall,
9
+ asToolCall,
10
+ pageName,
11
+ useOpenPageInPlatform,
12
+ usePageTools,
13
+ } from './htmlToolBridge';
14
+
15
+ /**
16
+ * The card the app shows over a page, outside its frame: the page cannot draw,
17
+ * see or answer it. `write`: the page's first writing call asks the viewer.
18
+ * `platform`: a page that needs tools asked for them where there are none.
19
+ */
20
+ type PageCard = { kind: 'write' | 'platform'; answer: (ok: boolean | null) => void };
21
+
22
+ export interface HtmlToolBridgeOptions {
23
+ /** The renderer's frame: only messages from its window are answered, and only to it. */
24
+ iframeRef: RefObject<HTMLIFrameElement | null>;
25
+ /** The file the renderer shows, as its own props name it: what the cards name, and what Open in the platform opens. */
26
+ filePath: string;
27
+ /**
28
+ * The page VIEW's identity, compared with `Object.is`: change it whenever
29
+ * the frame's document goes — a reload, a rebuilt document, the frame
30
+ * unmounted (Edit). The viewer's answer about writes holds for one view;
31
+ * when the key changes an open card closes, every call the old view made
32
+ * that has not yet run is answered `closed` and runs nothing, and no reply
33
+ * to the old view's calls is posted into the new one — a document rebuilt
34
+ * in the same frame keeps the frame's window, so the window alone cannot
35
+ * tell the two apart. A key that does not change across a reload keeps the
36
+ * consent across it.
37
+ */
38
+ viewKey: unknown;
39
+ }
40
+
41
+ export interface HtmlToolBridgeResult {
42
+ /**
43
+ * What to build the frame's document with — `buildSandboxedHtml`'s
44
+ * `toolBridge`: the identity minted for this view's document, which the
45
+ * runtime stamps on every message so the app answers only the document it
46
+ * built, and whether that document gets the tools (`tools: false` leaves
47
+ * it `bevel.tools = null`, still asking `requireTools()` as itself). A new
48
+ * identity per `viewKey`, so a renderer that builds its document from this
49
+ * value rebuilds it when the view changes, as it must.
50
+ */
51
+ toolBridge: { documentId: string; tools: boolean };
52
+ /** The two cards, for the renderer to render beside its frame. */
53
+ cards: ReactNode;
54
+ }
55
+
56
+ /** A document's identity: unique per view, meaningful to nobody else. */
57
+ function newDocumentId(): string {
58
+ return `doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
59
+ }
60
+
61
+ /**
62
+ * The app's half of a page's `window.bevel.tools` and `requireTools()`, for
63
+ * any renderer that shows an HTML page in a sandboxed frame: which pages get
64
+ * tools (the app's file page, never a surface), the viewer's tool client, the
65
+ * per-view consent, the cards, and the frame's tool messages. A renderer
66
+ * passes its frame, its file and its view key, builds its document with
67
+ * `toolBridge`, and renders `cards` — it holds no bridge logic of its own.
68
+ */
69
+ export function useHtmlToolBridge({ iframeRef, filePath, viewKey }: HtmlToolBridgeOptions): HtmlToolBridgeResult {
70
+ const { openFilePage } = useFileNav();
71
+ const surface = useRendererSurface();
72
+ // The viewer's tools, for a page on a host that provides them (the file
73
+ // page, the skill page — `PageToolsContext` lists them) and never on a
74
+ // surface. 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;
78
+ const toolsClient = useMemo(() => (toolPagePath ? new PageToolsClient(toolPagePath) : null), [toolPagePath]);
79
+ const [card, setCard] = useState<PageCard | null>(null);
80
+ const cardRef = useRef<PageCard | null>(null);
81
+ // The viewer's answer about this page's writes holds for one VIEW of it: a
82
+ // new frame document (a reload, a saved edit, another file) asks again.
83
+ const consentRef = useRef<PageConsent | null>(null);
84
+ // Which document this view's is: an identity minted per `viewKey` — for
85
+ // every view, tools or not, since a page without tools still asks
86
+ // `requireTools()` — built into the document, and stamped by its runtime
87
+ // on every message. The window is not enough — a document rebuilt in the
88
+ // same frame element keeps the frame's window, and a message the old
89
+ // document queued can be delivered after the new one is committed. A
90
+ // message is answered only when it carries the current identity, and its
91
+ // reply is posted only while that identity is still current. The ref flips
92
+ // in the SAME commit that puts the new document in the frame (a layout
93
+ // effect), so nothing decided in the gap before passive effects run finds
94
+ // the old one current.
95
+ const documentId = useMemo(() => {
96
+ void viewKey; // a new identity per view, whatever the key's value
97
+ return newDocumentId();
98
+ }, [viewKey]);
99
+ const documentIdRef = useRef(documentId);
100
+ useLayoutEffect(() => {
101
+ documentIdRef.current = documentId;
102
+ }, [documentId]);
103
+
104
+ /** 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. */
105
+ const showCard = useCallback((kind: PageCard['kind']): Promise<boolean | null> => {
106
+ const open = cardRef.current;
107
+ if (open && open.kind === kind) {
108
+ return new Promise((resolve) => {
109
+ const first = open.answer;
110
+ open.answer = (ok) => {
111
+ first(ok);
112
+ resolve(ok);
113
+ };
114
+ });
115
+ }
116
+ return new Promise((resolve) => {
117
+ const next: PageCard = { kind, answer: resolve };
118
+ cardRef.current = next;
119
+ setCard(next);
120
+ });
121
+ }, []);
122
+
123
+ /** Close the card with the viewer's answer, or null when the view went before they gave one. */
124
+ const closeCard = useCallback((ok: boolean | null) => {
125
+ const open = cardRef.current;
126
+ cardRef.current = null;
127
+ setCard(null);
128
+ open?.answer(ok);
129
+ }, []);
130
+
131
+ // When the page's view ends its consent is closed — a call the old view
132
+ // made that is still deciding (the manual lookup in flight) or waiting is
133
+ // answered `closed` and runs nothing — and a card left open answers no:
134
+ // nothing the old view asked for runs in, or asks from, the new one. A
135
+ // layout effect, like the generation above: the old view's consent is
136
+ // closed in the commit that ends it, not after the paint that follows.
137
+ useLayoutEffect(
138
+ () => () => {
139
+ consentRef.current?.close();
140
+ consentRef.current = null;
141
+ closeCard(null);
142
+ },
143
+ [viewKey, closeCard],
144
+ );
145
+
146
+ // A page's `window.bevel.tools` calls and its `requireTools()`, posted by
147
+ // the runtime in the frame (see `htmlSandbox.ts`), answered here with the
148
+ // viewer's session.
149
+ useEffect(() => {
150
+ function onToolMessage(event: MessageEvent) {
151
+ const iframeWin = iframeRef.current?.contentWindow;
152
+ if (!iframeWin || event.source !== iframeWin) return;
153
+ const data = event.data as { type?: unknown; requestId?: unknown; documentId?: unknown } | null;
154
+ // Only from the document this view built: a message from one the view
155
+ // has since replaced — queued before the change, delivered after it,
156
+ // through the same window — is nobody's to answer.
157
+ const asked = documentIdRef.current;
158
+ if (data?.documentId !== asked) return;
159
+ const reply = (message: unknown) => {
160
+ // Only to the document that asked: a reloaded frame is a new window,
161
+ // and a document rebuilt in the same window carries a new identity.
162
+ // A reply to a document that is gone reaches nobody.
163
+ if (documentIdRef.current === asked && iframeRef.current?.contentWindow === iframeWin) {
164
+ iframeWin.postMessage(message, '*');
165
+ }
166
+ };
167
+ if (data && data.type === 'bevel.tools.require' && typeof data.requestId === 'string') {
168
+ const requestId = data.requestId;
169
+ if (toolsClient) {
170
+ reply({ type: 'bevel.tools.require.response', requestId, ok: true, result: true });
171
+ return;
172
+ }
173
+ void showCard('platform').then(() =>
174
+ // Either way the page that asked carries on without tools: Open in
175
+ // the platform opened it elsewhere, it did not give it tools here.
176
+ reply({ type: 'bevel.tools.require.response', requestId, ok: true, result: false }),
177
+ );
178
+ return;
179
+ }
180
+ const call = asToolCall(data);
181
+ if (!call) return;
182
+ if (!toolsClient) {
183
+ reply({
184
+ type: 'bevel.tool.response',
185
+ requestId: call.requestId,
186
+ ok: false,
187
+ error: 'Tools are only available on the page in the platform.',
188
+ code: 'unavailable',
189
+ });
190
+ return;
191
+ }
192
+ consentRef.current ??= new PageConsent(() => showCard('write'));
193
+ void answerToolCall(call, toolsClient, consentRef.current).then(reply);
194
+ }
195
+ window.addEventListener('message', onToolMessage);
196
+ return () => window.removeEventListener('message', onToolMessage);
197
+ }, [iframeRef, toolsClient, showCard]);
198
+
199
+ const openInPlatform = useCallback(() => {
200
+ closeCard(false);
201
+ // The host's own way when it has one (a skill page, whose filePath is
202
+ // relative to the skill); otherwise the file page, by an address that
203
+ // asks for it outright: on the embed the surface opens it through the
204
+ // host in a new tab, which carries no router state, and a page inside a
205
+ // skill's folder would otherwise open as that skill's page again.
206
+ if (openPageInPlatform) openPageInPlatform();
207
+ else openFilePage(filePath);
208
+ }, [closeCard, openPageInPlatform, openFilePage, filePath]);
209
+
210
+ const cards = (
211
+ <>
212
+ <Dialog
213
+ open={card?.kind === 'write'}
214
+ onClose={() => closeCard(false)}
215
+ title={`${pageName(filePath)} wants to write to the knowledge base`}
216
+ size="md"
217
+ footer={
218
+ <>
219
+ <Button variant="outline" onClick={() => closeCard(false)}>
220
+ Deny
221
+ </Button>
222
+ <Button variant="primary" onClick={() => closeCard(true)}>
223
+ Allow while open
224
+ </Button>
225
+ </>
226
+ }
227
+ >
228
+ <p className="font-mono text-detail text-ink-muted break-all">{toolPagePath ?? filePath}</p>
229
+ </Dialog>
230
+ <Dialog
231
+ open={card?.kind === 'platform'}
232
+ onClose={() => closeCard(false)}
233
+ title={`${pageName(filePath)} uses tools that are only available in the platform`}
234
+ size="md"
235
+ footer={
236
+ <>
237
+ <Button variant="outline" onClick={() => closeCard(false)}>
238
+ Continue without tools
239
+ </Button>
240
+ <Button variant="primary" onClick={openInPlatform}>
241
+ Open in the platform
242
+ </Button>
243
+ </>
244
+ }
245
+ >
246
+ <p className="font-mono text-detail text-ink-muted break-all">{filePath}</p>
247
+ </Dialog>
248
+ </>
249
+ );
250
+
251
+ const toolBridge = useMemo(() => ({ documentId, tools: toolPagePath !== null }), [documentId, toolPagePath]);
252
+ return { toolBridge, cards };
253
+ }
@@ -0,0 +1,52 @@
1
+ import { useCallback } from 'react';
2
+ import { useLocation, useNavigate } from 'react-router-dom';
3
+ import { useLatestRef } from '../../../shared/components';
4
+
5
+ /**
6
+ * The file page's "fill the window" view — the host's, never a renderer's.
7
+ *
8
+ * The URL IS the state: `?fullscreen=1` on the file's address. There is no
9
+ * React state beside it, so a reload, a shared link and the button all reach
10
+ * the same view the same way. Entering and leaving REPLACE the history entry:
11
+ * the view is a way of looking at the same file, not a place of its own, so
12
+ * Back leaves the file rather than the view.
13
+ *
14
+ * "Full screen" is the browser's viewport, not the Fullscreen API: no
15
+ * permission prompt, it works when the app is itself framed, and the address
16
+ * bar stays so the URL can be copied.
17
+ */
18
+ export const FULL_SCREEN_PARAM = 'fullscreen';
19
+
20
+ export interface FullScreenView {
21
+ fullscreen: boolean;
22
+ enter(): void;
23
+ leave(): void;
24
+ }
25
+
26
+ export function useFullScreenView(): FullScreenView {
27
+ const location = useLocation();
28
+ const navigate = useNavigate();
29
+ const fullscreen = new URLSearchParams(location.search).get(FULL_SCREEN_PARAM) === '1';
30
+ // Read at the moment of the toggle, so the handlers stay stable.
31
+ const locationRef = useLatestRef(location);
32
+
33
+ const setParam = useCallback(
34
+ (on: boolean) => {
35
+ const current = locationRef.current;
36
+ const params = new URLSearchParams(current.search);
37
+ if (on) params.set(FULL_SCREEN_PARAM, '1');
38
+ else params.delete(FULL_SCREEN_PARAM);
39
+ const search = params.toString();
40
+ // The same entry under a different view: its router state (a
41
+ // `startEditing` request not yet acted on) and its hash ride along.
42
+ navigate(
43
+ { pathname: current.pathname, search: search ? `?${search}` : '', hash: current.hash },
44
+ { replace: true, state: current.state },
45
+ );
46
+ },
47
+ [locationRef, navigate],
48
+ );
49
+ const enter = useCallback(() => setParam(true), [setParam]);
50
+ const leave = useCallback(() => setParam(false), [setParam]);
51
+ return { fullscreen, enter, leave };
52
+ }